Tuesday, March 10, 2015

Authentication with Social Medias in Django



Now no one waste the too much  for registration on a website , they need a flexible authentication  most popular is social-media( Facebook , Google Plus and twitter ).I needed to add Social media authentication to a Django app today, and instead of writing it directly against the Social Media API .I decided to look around and see if there’s a pre-packaged solution for this common task. Turns out, there’s an excellent project called Python Social Auth, and it covers pretty much any social website with an authentication API.. In this Blog, we will use Facebook, Twitter and Google, as the most common social APIs, but we could easily substitute them with LinkedIn, Yahoo  or a bunch of other providers supported by Python Social Auth library.
Django Version : 1.7.4

Step 1 :  Create a project 

         Here am create a project  called  SocialAuth

project in Tree Structre
         SocialAuth/
              manage.py
             SocialAuth/
                __init__.py
                 settings.py
                urls.py
                uwsgi.py
step 2 : Now, the very small customization's we’ll add are

  • Add ‘SocialAuth’ to INSTALLED_APPS
  • Create the template for the home page
  • Add a view for the home page
  • Add a URL pointing to the home page view

Relevant portion of settings.py:



INSTALLED_APPS = (

    'django.contrib.admin',

    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'SocialAuth',
)

set the static and template root and url in settings.py [ Reffer django Documentaion]

step 3 : Create a folder called templates

    Template: SocialAuth/templates/base.html:


 <!DOCTYPE html>

<html lang="en">
 <head>
   <meta charset="utf-8">
   <meta http-equiv="X-UA-Compatible" content="IE=edge">
   <meta name="viewport" content="width=device-width, initial-scale=1">
   <title>{% block title %}Social Media Authentication Tutorial{% endblock %}</title>

   <!-- Bootstrap -->
   <link href="/static/css/bootstrap.min.css" rel="stylesheet">
   <link href="/static/css/bootstrap-theme.min.css" rel="stylesheet">
   <link href="/static/css/fbposter.css" rel="stylesheet">
 </head>
 <body>
   {% block main %}{% endblock %}
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
   <script src="/static/js/bootstrap.min.js"></script>
 </body>
 </html>


Template: SocialAuth/templates/index.html:


{% extends 'base.html' %}

{% block main %}
 <div>
 <h1>Social Media authentication demo</h1>

 <p>
   <ul>
   {% if user and not user.is_anonymous %}
     <li>
       <a>Hello {{ user.get_full_name|default:user.username }}!</a>
     </li>
     <li>
       <a href="{% url 'auth:logout' %}?next={{ request.path }}">Logout</a>
     </li>
   {% else %}
     <li>
       <a href="{% url 'social:begin' 'facebook' %}?next={{ request.path }}">Login with Facebook</a>
     </li>
     <li>
       <a href="{% url 'social:begin' 'google-oauth2' %}?next={{ request.path }}">Login with Google</a>
     </li>
     <li>
     <li>
       <a href="{% url 'social:begin' 'twitter' %}?next={{ request.path }}">Login with Twitter</a>
     </li>
   {% endif %}
   </ul>
 </p>
 </div>
{% endblock %}

step 4 : Create Views.py  inside your SocialAuth project directory

SocialAuth/Views.py



from django.shortcuts import render_to_response

from django.template.context import RequestContext


def home(request):
   context = RequestContext(request,'request': request,'user': request.user})
   return render_to_response('index.html',context_instance=context)


step 5 : Create a file called urls.py

 SocialAuth/urls.py 

from django.conf.urls import patterns, include, url

from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
   url(r'^$', 'SocialAuth.views.home', name='home'),
   url(r'^admin/', include(admin.site.urls)),
)

step 6 : Install  Python Scoial Auth

            pip install python-social-auth

step 7 :  Second, let’s make some modifications to our settings.py to include python-social-auth in our project:

     INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'thirdauth',
    'social.apps.django_app.default',
    )

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
    'django.template.loaders.eggs.Loader',
)

AUTHENTICATION_BACKENDS = (
   'social.backends.facebook.FacebookOAuth2',
   'social.backends.google.GoogleOAuth2',
   'social.backends.twitter.TwitterOAuth',
   'django.contrib.auth.backends.ModelBackend',
)

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',
)

LOGIN_REDIRECT_URL = ' / ' ( root )


step 8 : Let’s update the urls module to include the new group of URLs : 

from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
   url(r'^$', 'thirdauth.views.home', name='home'),
   url(r'^admin/', include(admin.site.urls)),
   url('', include('social.apps.django_app.urls', namespace='social')),
   url('', include('django.contrib.auth.urls', namespace='auth')),(  add urls for looging in and looging out.)
)

step 8 : python manage.py migrate and run our project ( python manage.py runserver )

And then start adding API-specific parameters for social networks. Right this moment, if you click on any of the“login with X” links, you’ll get redirected to the corresponding social site, but will get an error about invalid client ID. That’s because we have not provided any client IDs yet.

Facebook

  • Go to https://developers.facebook.com/apps/?action=create and click the green “Create New App” button.
  • In the settings of the newly-created application, click “Add Platform”. From the options provided, choose Web, and fill in the URL of the site (http://127.0.0.1:8000/in our example).
  • Copy the App ID and App Secret, and place them into settings.py file:
  • SOCIAL_AUTH_FACEBOOK_KEY = …
  • SOCIAL_AUTH_FACEBOOK_SECRET = …
  • This should be enough to get your app to login with Facebook! Try logging in and out – you should get redirected between your app and FB OAuth2 service, and a new record in the User social auths table will get created, along with a new User record pointing to it.
Twitter 

Google 

  • Go to https://console.developers.google.com/ and create a new application.
  • Under APIs and Auth > Credentials, create a new Client ID.
  • Make sure to specify the right callback URL: http://127.0.0.1:8000/complete/google-oauth2/
  • Copy the values into settings file:
  • SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = …
  • SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = …

Conclusion

Python Social Auth can provide more than just authentication. 

                                                         <----- Thank You ------>


1 comment: