DEV Community

Kelly Kiiru
Kelly Kiiru

Posted on

Django User Registration with Google

OAuth, short for Open Authorization, is a mechanism that enables websites or applications to exchange user data with other platforms, all without necessitating the disclosure of a user’s password. It empowers users to access multiple websites with a single set of login credentials.

Prominent OAuth service providers include Google, Facebook, and GitHub. In this tutorial, we will explore the process of user registration within a Django application using Google OAuth as our chosen authentication method.

Prerequisites

To follow along with this article, you will need to have the following:
A GitHub account.

Python, pip and Django installed

Visual Studio Code — Integrated Development Environment(IDE)

Step 1 — Create and set up a new Django project

Create a folder(directory) and name it Google-Oauth. Inside of this folder create a virtual environment:

python -m venv venv

Enter fullscreen mode Exit fullscreen mode

You can name your virtual environment anything. In this case, I named it ‘venv’.

For Windows OS activate the virtual environment using:

venv\Scripts\activate

Enter fullscreen mode Exit fullscreen mode

For Linux and mac OS use:

source venv/bin/activate

Enter fullscreen mode Exit fullscreen mode

or:

. venv/bin/activate
Enter fullscreen mode Exit fullscreen mode

On activation, install django:

pip install django

Enter fullscreen mode Exit fullscreen mode

Create a django project:

django-admin createproject auth_project .

Enter fullscreen mode Exit fullscreen mode

Create a django app:

django-admin createapp auth_app

Enter fullscreen mode Exit fullscreen mode

Add ‘auth_app’ to the INSTALLED_APPS array:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.sites', //add this line too

    'auth_app',
]
Enter fullscreen mode Exit fullscreen mode

Apply and migrate these changes to SQLite:

python manage.py migrate

Enter fullscreen mode Exit fullscreen mode

Step 2 — Install and set up django-allauth

Install the django-allauth

pip install django-allauth

Enter fullscreen mode Exit fullscreen mode

Add it to the INSTALLED_APPS array:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.sites',

    'auth_app',

    //all auth configurations
    'allauth',
    'allauth.account',
    'allauth.socialaccount',
    'allauth.socialaccount.providers.google'
]

Enter fullscreen mode Exit fullscreen mode

The last item of this array specifies the django-allauth provider you will use which in this case is google. django-allauth also supports other providers.

Add AUTHENTICATION_BACKENDS to settings.py at the bottom of your page:

AUTHENTICATION_BACKENDS = [
    'django.contrib.auth.backends.ModelBackend',
    'allauth.account.auth_backends.AuthenticationBackend'
]

Enter fullscreen mode Exit fullscreen mode

Add SOCIALACCOUNT_PROVIDERS configurations array to settings.py:

SOCIALACCOUNT_PROVIDERS = {
    'google': {
        'SCOPE' : [
            'profile',
            'email'
        ],
        'APP': {
            'client_id': os.environ['CLIENT_ID'],
            'secret': os.environ['CLIENT_SECRET'],
        },
        'AUTH_PARAMS': {
            'access_type':'online',
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

The SCOPE key outlines the required parameters for Google APIs. In the absence of a specified scope, it will default to ‘profile.’ To enable background authentication refresh, configure AUTH_PARAMS[‘access_type’] as ‘offline.’

Step 3 — Create and configure templates

In this project we will use django templates to view our code. In auth_app, create a folder called ‘templates’. Django has an inbuilt mechanism that will find this templates folder.

Replace this TEMPLATES array in settings.py:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

Enter fullscreen mode Exit fullscreen mode

with

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR/'templates'], //updated line
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

Enter fullscreen mode Exit fullscreen mode

Inside of ‘templates’ folder in auth_app create an index.html file.

Add the following code to it:

{% load socialaccount %} //make sure to add this
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1 style="text-align: center;"> My google OAuth Project </h1>
    {% if user.is_authenticated %}
    <p>Welcome. You are logged in as {{user.username}} </p>
    {% else %}
    <a href="{% provider_login_url 'google' %}">Login with Google</a>
    {% endif %}
</body>
</html>

Enter fullscreen mode Exit fullscreen mode

Step 4 — Configure Project URLs

Inside of auth_project/urls.py define the urlpatterns:

from django.contrib import admin
from django.urls import path,include
from django.views.generic import TemplateView // useful in displaying index.html template
from django.contrib.auth.views import LogoutView

urlpatterns = [
    path('admin/', admin.site.urls),
    path('app/',include('auth_app.urls')), //app_auth urls

    path('', TemplateView.as_view(template_name='index.html')),
    path('accounts/', include('allauth.urls')), // all OAuth operations will be performed under this route
    path('logout', LogoutView.as_view()) // default Django logout view at /logout
]

Enter fullscreen mode Exit fullscreen mode

Step 5— Create and configure a new Google APIs project

Head over to google developer APIs console and navigate to NEW PROJECT under ‘select project’

Image description

Set your app name and user support email in the OAuth Consent Screen

Image description

Switch to the Credentials tab and configure the following.

Note that it's http and not https.

Image description

At this point create a .env and a .gitignore file in the root folder (google-Oauth) of your application. We will store our environment variables(secrets) in this file.

In your .gitignore file add the following lines. This will prevent git from pushing this code to GitHub as these folders will be ignored.

venv/
/.env

Enter fullscreen mode Exit fullscreen mode

In your .env add the following:

Image description

These will be found in the credentials tab:

Image description

To access the environment variables download load_dotenv from pip

pip install python-dotenv
Enter fullscreen mode Exit fullscreen mode

In settings.py add these:

import os
from pathlib import Path
from dotenv import load_dotenv

load_dotenv()
Enter fullscreen mode Exit fullscreen mode

This configuration will make it possible for django to locate the environment variables. In this case:

SOCIALACCOUNT_PROVIDERS = {
    'google': {
        'SCOPE' : [
            'profile',
            'email'
        ],
        'APP': {
            'client_id': os.environ['CLIENT_ID'], // in .env file
            'secret': os.environ['CLIENT_SECRET'], // in .env file
        },
        'AUTH_PARAMS': {
            'access_type':'online',
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Migrate these changes:

Step 6— Configuring admin site

Create super user:

python manage.py createsuperuser
Enter fullscreen mode Exit fullscreen mode

Run the server:

python manage.py runserver
Enter fullscreen mode Exit fullscreen mode

In your browser, open http://127.0.0.1:8000/admin and login with the superuser details and set the domain as well as display names like this.
Navigate to the sites tab on the left menu:
Configure both the domain name and display name with 127.0.0.1:8000

Select the social applications tab and configure it with the client id and secret key obtained from your google console project. We stored these values in the .env file

Add SITE_ID and redirect users to the base route after a successful login or logout.

SITE_ID = 2

LOGIN_REDIRECT_URL = '/'
LOGOUT_REDIRECT_URL = '/'
Enter fullscreen mode Exit fullscreen mode

Since django already has a pre-made site(example.com) as seen above. The SITE_ID setting in settings.py might bring errors if its value is 1. Make sure its value is 2.

To test out if the configuratio was successful, log out on the top right and log in again but with google this time.

On logging out, log in with google, your application will ask you to do so with your google account. This information will be saved in your auth_user table of your database. You can also confirm this by checking http://127.0.0.1:8000/admin/socialaccount/socialaccount/

Conclusion

In this article, you learned how to start and configure a django project as well as adding Google Oauth for auth_users.
You configured your google developer APIs console with the right details.

The code is available on GitHub. I hope this article was beneficial to you. If so, leave a github star.

Happy coding.

Top comments (0)