“an easy-to-setup social authentication / registration method with support for multiple frameworks and auth providers” is what the Python Social Auth library offers. In this guide, we’ll show you how to add this library’s authentication features to your Django app. We’re making use of
:
- Django==1.7.1
- python-social-auth==0.2.1
Config of Django
You may skip this part if you have a project planned and ready to launch.
Start a new Django project by creating a virtualenv, installing Django, and activating it.
project:
$ django-admin.py startproject django_social_project
$ cd django_social_project
$ python manage.py startapp django_social_app
Create the primary data tables and insert a
superuser:
$ python manage.py migrate
Operations to perform:
Apply all migrations: admin, contenttypes, auth, sessions
Running migrations:
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying sessions.0001_initial... OK
$ python manage.py createsuperuser
Username (leave blank to use 'michaelherman'): admin
Email address: ad@min.com
Password:
Password (again):
Superuser created successfully.
Make a new folder named “templates” in the Project’s root, and then point the settings to that location.
py
file:
TEMPLATE_DIRS = (
os.path.join(BASE_DIR, 'templates'),
)
Start the development server at http://localhost:8000/ and check that it’s working properly. The “It worked!” page should load.
This is what your project should look like after you’re done with it.
this:
└── django_social_project
├── db.sqlite3
├── django_social_app
│ ├── __init__.py
│ ├── admin.py
│ ├── migrations
│ │ └── __init__.py
│ ├── models.py
│ ├── tests.py
│ └── views.py
├── django_social_project
│ ├── __init__.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
├── manage.py
└── templates
Initiating Python Social Auth
If you’re having trouble getting started, check out the official installation guide or just use the instructions down below.
Installation
Utilize the
pip:
$ pip install python-social-auth==0.2.1
Configuration
Modify settings.py to include the library and register it with our
project:
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django_social_project',
'social.apps.django_app.default',
)
TEMPLATE_CONTEXT_PROCESSORS = (
'django.contrib.auth.context_processors.auth',
'django.core.context_processors.debug',
'django.core.context_processors.i18n',
'django.core.context_processors.media',
'django.core.context_processors.static',
'django.core.context_processors.tz',
'django.contrib.messages.context_processors.messages',
'social.apps.django_app.context_processors.backends',
'social.apps.django_app.context_processors.login_redirect',
)
AUTHENTICATION_BACKENDS = (
'social.backends.facebook.FacebookOAuth2',
'social.backends.google.GoogleOAuth2',
'social.backends.twitter.TwitterOAuth',
'django.contrib.auth.backends.ModelBackend',
)
Maintaining an up-to-date
database:
$ python manage.py makemigrations
Migrations for 'default':
0002_auto_20141109_1829.py:
- Alter field user on usersocialauth
$ python manage.py migrate
Operations to perform:
Apply all migrations: admin, default, contenttypes, auth, sessions
Running migrations:
Applying default.0001_initial... OK
Applying default.0002_auto_20141109_1829... OK
Add the primary authentication url to the Project’s urlpatterns in urls.py.
URLs:
urlpatterns = patterns(
'',
url(r'^admin/', include(admin.site.urls)),
url('', include('social.apps.django_app.urls', namespace='social')),
)
Afterwards, you’ll need to gather the necessary authentication keys from each social platform you want to integrate. A number of well-known social media platforms, including Twitter, Facebook, and Google, follow a very similar procedure. To illustrate, let’s use Twitter as an example…
Keys to access your Twitter account
The callback address should be http://127.0.0.1:8000/complete/twitter when you create a new application on Twitter at https://apps.twitter.com/app/new.
Create a file named config.py in the “django social project” folder. To configure Twitter, you must first get a Consumer Key (API Key) and a Consumer Secret (API Secret) from the “Keys and Access Tokens” page.
so:
SOCIAL_AUTH_TWITTER_KEY = 'update me'
SOCIAL_AUTH_TWITTER_SECRET = 'update me'
Let’s additionally add the login and redirect URLs (when a user logs in) to config.py:
authenticates):
SOCIAL_AUTH_LOGIN_REDIRECT_URL = '/home/'
SOCIAL_AUTH_LOGIN_URL = '/'
To settings.py, add the following import.
:
from config import *
config.py should be excluded from version control and hence included to your.gitignore file.
Please refer to the documents for more clarification.
Logic Examined
Well, let’s put this to the test. Start the server by going to http://127.0.0.1:8000/login/twitter, granting permission to the app; if successful, you will be routed to http://127.0.0.1:8000/home/. (this value is related with the SOCIAL AUTH LOGIN REDIRECT URL variable). Because no route, view, or template has been created just yet, a 404 error should be shown.
What are we waiting for?
Opinions that are friendly
At this time, just the login and home screens will do.
URLs
Modify urls.py to use the most recent URL pattern.
:
urlpatterns = patterns(
'',
url(r'^admin/', include(admin.site.urls)),
url('', include('social.apps.django_app.urls', namespace='social')),
url(r'^$', 'django_social_app.views.login'),
url(r'^home/$', 'django_social_app.views.home'),
url(r'^logout/$', 'django_social_app.views.logout'),
)
To complement the already existing / and home/ routes, we developed a logout/ route.
Views
As a further step, please include the below perspective
functions:
from django.shortcuts import render_to_response, redirect, render
from django.contrib.auth import logout as auth_logout
from django.contrib.auth.decorators import login_required
# from django.template.context import RequestContext
def login(request):
# context = RequestContext(request, {
# 'request': request, 'user': request.user})
# return render_to_response('login.html', context_instance=context)
return render(request, 'login.html')
@login_required(login_url='/')
def home(request):
return render_to_response('home.html')
def logout(request):
auth_logout(request)
return redirect('/')
It is possible to get the currently logged-in user by using the RequestContext in the login() method. The most obscure means of doing so are noted out for completeness’ sake.
Templates
Upload two new templates, “home.html” and “login.html.”
login.html
<h1>Welcome</h1>
<p><a href="/logout">Logout</a>
{% if user and not user.is_anonymous %}
<a>Hello, {{ user.get_full_name }}!</a>
<br>
<a href="/logout">Logout</a>
{% else %}
<a href="{% url 'social:begin' 'twitter' %}?next={{ request.path }}">Login with Twitter</a>
{% endif %}
That’s what your project should look like now.
this:
└── django_social_project
├── db.sqlite3
├── django_social_app
│ ├── __init__.py
│ ├── admin.py
│ ├── migrations
│ │ └── __init__.py
│ ├── models.py
│ ├── tests.py
│ └── views.py
├── django_social_project
│ ├── __init__.py
│ ├── config.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
├── manage.py
└── templates
├── home.html
└── login.html
Re-evaluate the results. Start the server up. In order to test logging in and out, you must first logout, since the user will already be in the system from the last test. It is expected that whenever a person logs in, they will be sent to their home directory (/home).