29 Nov 2013

Using Django Social Auth

I have been trying to integrate a facebook login for my side-project site. There are various modules available but that works for me is django-social-auth.
This module provides the integration of various social platforms like facebook, twitter, google etc.
Please install that module before preceding . It also had a good documentation, which ca be found here.

 In this post i'm just posting about stuff to how to integrate facebook login in your Django app.

Step 1. Create a facebook app.
facebook app which will gives you App ID/API Key and App Secret which will be used in Django settings.
Please make sure that  following app settings: 
  >> Sandbox Mode is ON
  >>  Site URL is a http://127.0.0.1:8000/ . 
        This should be the url from which you going to make a login request.

Step 2. Django Setting for facebook intergation.

AUTHENTICATION_BACKENDS = (
    'social_auth.backends.facebook.FacebookBackend',
    'django.contrib.auth.backends.ModelBackend',
)

FACEBOOK_APP_ID =  "app_id"
FACEBOOK_API_SECRET = "app_secret"


LOGIN_URL          = '/login-form/'
LOGIN_REDIRECT_URL = '/logged-in/'
LOGIN_ERROR_URL    = '/login-error/'
LOGOUT_REDIRECT_URL = '/'



SOCIAL_AUTH_DEFAULT_USERNAME = 'auth_user'
SOCIAL_AUTH_UID_LENGTH = 16
SOCIAL_AUTH_ASSOCIATION_HANDLE_LENGTH = 16
SOCIAL_AUTH_NONCE_SERVER_URL_LENGTH = 16
SOCIAL_AUTH_ASSOCIATION_SERVER_URL_LENGTH = 16
SOCIAL_AUTH_ASSOCIATION_HANDLE_LENGTH = 16

SOCIAL_AUTH_ENABLED_BACKENDS = ('facebbok',)
FACEBOOK_EXTENDED_PERMISSIONS= ['email']


Step 3. Login link in your html page.
 <a href="{% url socialauth_begin 'facebook' %}">Login with Facebook</a> 
you can make that link a bit fancy using facebook login button. but for now that will serve our purpose.

Step 4. Add url for social-auth.

Add follwoing url for social-auth login in urls.py .
url(r'', include('social_auth.urls')),

and 
following url will take to a view , once user is logged successfully.

url(r'^logged-in/$', 'pollsite.views.home', name='home'),

in above line you can use , LOGIN_REDIRECT_URL which is same as 'logged-in'.



When you click on that link, a familiar facebook login page will appear.




Thats it.  If you encounter any problem , please post it as a comment and i'll be happy to help you out.
 And keep reading.