Reader small image

You're reading from  Django 5 By Example - Fifth Edition

Product typeBook
Published inApr 2024
PublisherPackt
ISBN-139781805125457
Edition5th Edition
Right arrow
Author (1)
Antonio Melé
Antonio Melé
author image
Antonio Melé

Antonio Melé has been crafting Django projects since 2006, for clients spanning multiple industries. He is Engineering Director at Backbase, a leading global fintech firm dedicated to facilitating the digital transformation of financial institutions. He co-founded Nucoro, a digital wealth management platform. In 2009 Antonio founded Zenx IT, a company specialized in developing digital products. He has been working as CTO and consultant for several tech-centric startups. He has also managed development teams building projects for large enterprise clients. He has an MSc in Computer Science from Universidad Pontificia Comillas and completed the Advanced Management Program at MIT Sloan. His father inspired his passion for computers and coding.
Read more about Antonio Melé

Right arrow

Implementing Social Authentication

In the previous chapter, you built user registration and authentication into your website. You implemented password change, reset, and recovery functionalities, and you learned how to create a custom profile model for your users.

In this chapter, you will add social authentication to your site using Google. You will use Python Social Auth for Django to implement social authentication using OAuth 2.0, the industry-standard protocol for authorization. You will also modify the social authentication pipeline to create a user profile for new users automatically.

This chapter will cover the following points:

  • Using the messages framework
  • Building a custom authentication backend
  • Preventing users from using an existing email
  • Adding social authentication with Python Social Auth
  • Running the development server through HTTPS using Django Extensions
  • Adding authentication using Google
  • Creating a profile for...

Functional overview

Figure 5.1 shows a representation of the views, templates, and functionalities that will be built in this chapter:

Figure 5.1: Diagram of functionalities built in Chapter 5

In this chapter, you will generate success and error messages in the edit view using the Django messages framework. You will build a new authentication backend named EmailAuthBackend for users to authenticate using their email addresses. You will serve your site over HTTPS during development using Django Extensions, and you will implement social authentication with Google on your site using Python Social Auth. Users will be redirected to the dashboard view after successful authentication. You will customize the authentication pipeline to create user profiles automatically when a new user is created with social authentication.

Before you begin: Join our book community on Discord

Give your feedback straight to the author himself and chat to other readers on the book's dedicated Discord server (find the "early-access-fifth-edition" channel under "FEEDBACK AND SUGGESTIONS").

https://packt.link/D5BE

In the preceding chapter, you learned how to implement a tagging system and how to recommend similar posts. You implemented custom template tags and filters. You also learned how to create sitemaps and feeds for your site, and you built a full-text search engine using PostgreSQL.

In this chapter, you will learn how to develop user account functionalities to create a social website, including user registration, password management, profile editing, and authentication. We will implement social features into this site in the next few chapters, to let users share images and interact with each other. Users will be able to bookmark any image on the internet and share it with other users. They will...

Creating a social website project

We are going to create a social application that will allow users to share images that they find on the internet. We will need to build the following elements for this project:

  • An authentication system for users to register, log in, edit their profile, and change or reset their password
  • A follow system to allow users to follow each other on the website
  • Functionality to display shared images and a system for users to share images from any website
  • An activity stream that allows users to see the content uploaded by the people that they follow

This chapter will address the first point on the list.

Starting the social website project

Open the terminal and use the following commands to create a virtual environment for your project:

mkdir env
python -m venv env/bookmarks

If you are using Linux or macOS, run the following command to activate your virtual environment:

source env/bookmarks/bin/activate

If you are using Windows, use the following...

Using the Django authentication framework

Django comes with a built-in authentication framework that can handle user authentication, sessions, permissions, and user groups. The authentication system includes views for common user actions such as logging in, logging out, password change, and password reset.

The authentication framework is located at django.contrib.auth and is used by other Django contrib packages. Remember that we already used the authentication framework in Chapter 1, Building a Blog Application, to create a superuser for the blog application to access the administration site.

When we create a new Django project using the startproject command, the authentication framework is included in the default settings of our project. It consists of the django.contrib.auth application and the following two middleware classes found in the MIDDLEWARE setting of our project:

  • AuthenticationMiddleware: Associates users with requests using sessions
  • SessionMiddleware: Handles the current...

User registration and user profiles

Site users can now log in, log out, change their password, and reset their password. However, we need to build a view to allow visitors to create a user account.

User registration

Let’s create a simple view to allow user registration on your website. Initially, you have to create a form to let the user enter a username, their real name, and a password. We will take the following steps:

Edit the forms.py file located inside the account application directory and add the following lines highlighted in bold:

from django import forms
from django.contrib.auth.models import User
class LoginForm(forms.Form):
    username = forms.CharField()
    password = forms.CharField(widget=forms.PasswordInput)
class UserRegistrationForm(forms.ModelForm):
    password = forms.CharField(label='Password',
                               widget=forms.PasswordInput)
    password2 = forms.CharField(label='Repeat password',
                       ...

Additional resources

The following resources provide additional information related to the topics covered in this chapter:

Summary

In this chapter, you learned how to build an authentication system for your site. You implemented all the necessary views for users to register, log in, log out, edit their password, and reset their password. You built a model to store custom user profiles.

In the next chapter, you will learn how to use the Django messages framework. You will create a custom authentication backend for users to login using their email address, and you will implement social authentication with Google on your site using Python Social Auth. You will also learn how to serve the development server over HTTPS using Django Extensions. You will customize the authentication pipeline to create user profiles automatically.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Django 5 By Example - Fifth Edition
Published in: Apr 2024Publisher: PacktISBN-13: 9781805125457
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime

Author (1)

author image
Antonio Melé

Antonio Melé has been crafting Django projects since 2006, for clients spanning multiple industries. He is Engineering Director at Backbase, a leading global fintech firm dedicated to facilitating the digital transformation of financial institutions. He co-founded Nucoro, a digital wealth management platform. In 2009 Antonio founded Zenx IT, a company specialized in developing digital products. He has been working as CTO and consultant for several tech-centric startups. He has also managed development teams building projects for large enterprise clients. He has an MSc in Computer Science from Universidad Pontificia Comillas and completed the Advanced Management Program at MIT Sloan. His father inspired his passion for computers and coding.
Read more about Antonio Melé