Django Social Authentication

 

    It's hard to trust that Python (1990) was introduced 5 years earlier than Java (1995). At first, it was not popular but as we see, currently, Python is one of the best, easy to learn, and famous worldwide. Python already takes the place for every field. Let me help you to know the domains where Python is used -

Web Development - Django, Pyramid, Bottle, Flask

GUI Development - wxPython, Tkinter, PyGtk, PyQt

Scientific and Numeric - SciPy, NumPy, Pandas

Software Development - Buildbot, Trac, Roundup

Embedded Computing - Raspberry Pi, Micro Python, BeagleBone

Education - Raspberry Pi, Turtle, Robotics

Here, I just specify the popular ones. I'm sure I forgot to write many of the domains. You can refer to this Wikipedia Page to know Python in detail.

Today, in this article, we'll see one of the most popular Python web-framework Django.

We'll cover below concepts in this article -

  • What is Django?
  • Top companies use Django
  • What is Django-social-auth?
  •  Installation and Setup
  • Build an application that uses Facebook, GitHub, LinkedIn, Twitter, and Google Login Authentication

Please use desktop view , if code is not visiable
Get the full code at my GitHub account

So let's get started. If you find this article useful👀 then please do, Follow🙌 and subscribe👍 to me for more articles like this.

What is Django?

Django is a high-level Python Web framework that encourages rapid development and clean pragmatic design. The primary goal of Django is to make the easy creation of a complex database-driven website. Django provides a standard way to build web-applications faster and in an easy way. You can read this Documentation of Django for more information.

Top international companies that use Django -

  • Instagram
  • Youtube
  • Spotify
  • Disqus
  • Dropbox
  • Bitbucket
  • Eventbrite and many more.
     

What is Django-social-auth?

Django-social-auth is a library that provides Social authentication and registration mechanism with many social auth providers. Also, the library itself allows us to make customization. 

Many people find it difficult to implement but today I'll help you to easily understand and implement it and in the end, you will have a fully functional social authentication application.

Installation and Setup

I'm working on Lenovo G50 Windows 10 laptop. Make sure your system has the following packages:

1. Python 3.8.1

2. pipenv 

Let’s start over by creating your awesome Python application. First, spawn a shell in a virtual environment to isolate the development of this app:

$ pipenv shell

Let's install Django first,

$ pip install django

*I have django 3.0.5. This is the recommended way to install Django.

You can see Django version by -

>>> import django

>>> print(django.__version__)

3.0.5

Create Django application

$ django-admin startproject socialauthentication

This will create a socialauthentication directory in your current directory. If it didn’t work, see Problems running django-admin.

Go in the directory

$ cd socialauthentication

also, create a new application in this -

$ python manage.py startapp accounts

Run the development server by executing below the cell and then navigate to http://localhost:8000/. You should see the “It worked!” page.

$ python manage.py runserver


After that let's download django-social-auth package.

$ pip install social-auth-app-django

Create two directories called "templates" and "static" in your project's root directory and create your front-end files here. Put all .html files in the templates folder and all other (CSS, JS, Images) in the static folder. I already have done it with my front-end. You can access these files here.

Update your app's setting.py - 

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'accounts.apps.AccountsConfig', #add
    'social_django', #add
]

Specify your templates and static file's path - 

TEMPLATES = [
    {
        ...
        'DIRS': [os.path.join(BASE_DIR,'templates')],
        ...
    },
]

...

STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR,'static')]
STATIC_ROOT = os.path.join(BASE_DIR,'assert')

For external social authentication, we have to tell Django, which authentication method it should follow?

for this add this code in your setting.py - 

AUTHENTICATION_BACKENDS = (
    'social_core.backends.facebook.FacebookOAuth2',
    'social_core.backends.github.GithubOAuth2',
    'social_core.backends.linkedin.LinkedinOAuth2',
    'social_core.backends.google.GoogleOAuth2',
    'social_core.backends.twitter.TwitterOAuth',
   
    'django.contrib.auth.backends.ModelBackend',
)

Don’t forget to write django.contrib.auth.backends.ModelBackend because without it users cannot do manual login/signup or users won’t be able to login by username/password method.

Let’s set the default values for the SOCIAL_AUTH_LOGIN_REDIRECT_URL and the SOCIAL_AUTH_LOGIN_URL. After authenticating from Django Login and Social Auth the SOCIAL_AUTH_LOGIN_REDIRECT_URL will be used to redirect the user.

SOCIAL_AUTH_LOGIN_REDIRECT_URL = '/'

SOCIAL_AUTH_LOGIN_URL = '/'

edit socialauthentication/urls.py file -

urlpatterns = [
    ...
    path('',include('accounts.urls')),
]

specify all routes in your accounts/urls.py file -

from django.contrib import admin
from django.urls import path, include
from . import views

urlpatterns = [
    path('',views.index, name='index'),
    path('login',views.login, name='login'),
    path('signup',views.signup, name='signup'),
    path('logout',views.logout, name='logout'),
    path('', include('social_django.urls', namespace='social'))
   
]

update your accounts/views.py file -

In this file, the login and signup functions are for manual Login/Signup. It is not related with Social Authentication.

from django.shortcuts import render, redirect
from django.contrib.auth.models import User,auth
from django.contrib import messages
from . import models
from django.conf import settings

# Create your views here.
def index(request):
    return render(request, 'index.html')

def signup(request):
    if request.method == 'GET':
        return render(request,'signup.html')
    else:
        username = request.POST['username']
        email = request.POST['email']
        password = request.POST['pass']
        password1 = request.POST['pass1']
        if password==password1:
            if User.objects.filter(username=username).exists():
                messages.info(request,"Username is taken")
                return redirect('signup')
            elif User.objects.filter(email=email).exists():
                messages.error(request,"Email id is already registered")
                return redirect('signup')
            else:
                user = User.objects.create_user(password=password,username=username,email=email)
                user.save()
                return redirect('login')
        else:
            messages.warning(request,"Password not match")
            return redirect('signup')
        return redirect('/')
               
    #return render(request, 'signup.html')

def login(request):
    if request.method == 'GET':
        return render(request,'login.html')
    else:
        username = request.POST['username']
        password = request.POST['pass']
        user = auth.authenticate(username=username,password=password)
        if user is not None:
            auth.login(request,user)
            return redirect('/')
        else:
            messages.warning(request,"Check your Username or Password.")
            return redirect('login')
           
    #return render(request, 'login.html')
   
def logout(request):
    auth.logout(request)
    return redirect('/')

Once, you complete all the steps, do migrations -

$ python manage.py makemigration

$ python manage.py migrate


Great !!! Now, we have to just create our APIs on different social platforms. You can go with as many platforms as listed here as you want, but here I use the following social APIs –

SocialApp Developer Link
Facebook https://developers.facebook.com/
GitHub https://github.com/settings/applications/new
Google https://console.developers.google.com/
Linkedin https://www.linkedin.com/developers/
Twitter https://developer.twitter.com/en/portal/dashboard

Go with the link and create your APIs. One by one put all API's ACCESS_KEY and ACCESS_SECRET in your setting.py just like this -

# Facebook API Details

SOCIAL_AUTH_FACEBOOK_KEY  = ' ' #add key

SOCIAL_AUTH_FACEBOOK_SECRET= ' '  #add secret

# LinkedIn API Details

SOCIAL_AUTH_LINKEDIN_OAUTH2_KEY= ' ' #add key

SOCIAL_AUTH_LINKEDIN_OAUTH2_SECRET= ' ' #add secret

# Github API Details

SOCIAL_AUTH_GITHUB_KEY= ' ' #add key

SOCIAL_AUTH_GITHUB_SECRET= ' ' #add secret # Twitter API Details

SOCIAL_AUTH_TWITTER_KEY= ' ' #add key

SOCIAL_AUTH_TWITTER_SECRET= ' ' #add secret

SOCIAL_AUTH_TWITTER_TOKEN= ' ' #Not necessary to add

# Google API Details

SOCIAL_AUTH_GOOGLE_OAUTH2_KEY= ' ' #add key

SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET= ' ' #add secret

 

After completing this step. now you're one step to go. Just give the link in the anchor tag to your social logo buttons. 

Edit templates/login.html and templates/signup.html files - 

<div class="flex-c-m">
   <a href="{% url 'social:begin' 'facebook' %}" class="login100-social-item bg2">
         <i class="fa fa-facebook"></i>
   </a>

   <a href="{% url 'social:begin' 'github' %}" class="login100-social-item bg2">
         <i class="fa fa-github"></i>
   </a>
                      
   <a href="{% url 'social:begin' 'linkedin-oauth2'%}" class="login100-social-item bg2">
         <i class="fa fa-linkedin"></i>
   </a>
                      
   <a href="{% url 'social:begin' 'twitter' %}" class="login100-social-item bg2">
         <i class="fa fa-twitter"></i>
   </a>

   <a href="{% url 'social:begin' 'google-oauth2'%}" class="login100-social-item bg2">
        <i class="fa fa-google"></i>
   </a> 

</div>

Booom !!!

You have created the Django application which can do both Social Authentication and Manual Login/Signups.

Run the server and redirect to http://localhost:8000/login

Now access your login and signup page manually and with django-social-auth.

Get the full code at my GitHub account
 
 
If you really like this💯, then follow🌈 me by Clicking Follow💥 button next to comment section.🤩🥰
Stay Connect with me 😇
Thank you 😍💙
 

Thank you for visiting my blog. My team is here to help you. Let us know if you have any doubts.

Post a Comment (0)
Previous Post Next Post