Laughing Blog Tutorial part 4 - Django Authentication System

published on: | by cindy In category: Tutorial Series

This is the fourth part of the laughing Blog Series and In this article we will talk about Django authentication system. Django has a powerful inbuilt authentication system that handles both authentication and authorization but both commonly just termed as authentication

The authentication is bundled in the django.contrib.auth and also the django.contrib.contenttypes to support authorization both in settings.INSTALLED_APPs

NSTALLED_APPS = [
''django.contrib.auth'',
''django.contrib.contenttypes'',
]

In addition to the installed apps, Django also has two middleware classes found in the setting.MIDDLEWARE_CLASSES of your project. AuthenticationMiddleware which associates users with creators SessionMiddleware handles the current session across requests using sessions

Django authentication has the capability to handle:

  1. Authentication : login ,logout

!!! achiengBytes "What is the difference between authentication and login " Authenticate verify user credentials and returns a user object if correct; login sets the user in the current session.

  1. Password Management: Changes password and allow for resets as well

What is the difference between authentication and authorization?

Authentication: verify user credentials such as username against password to ascertain the user is who they say they are.

Authorization determines that the authenticated user is authorized to perform some given operation (usually by checking against granted permissions)

!!! achiengBytes "Authorization vs Authentication" Authentication: verify user credentials such as username against password to ascertain the user is who they say they are. Authorization determines that the authenticated user is authorized to perform some given operation (usually by checking against granted permissions)

Users

The authentication system comprises of Users, Permissions, Groups, Forms and view tools for logging in users, or restricting content.

The User object sits at the heart of the Django authentication system representing the people who interact with the application. The user object is used to grant permission, register user profiles and associated content with creators.
The primary attributes are:username, password, email,First name and last name

With that background, let us get started.

Create an app called accounts

python manage.py startapp accounts
. Next, we have to install it in settings. Installed-apps
INSTALLED_APPS = [
...
''accounts'',
]

Using Authentication Views

To use all the views Django authentication has to offer,simply define the urls in the main urls.py as shown :

path(''accounts/'', include(''django.contrib.auth.urls'')),

If you run the server and navigate to http://127.0.0.1:8000/accounts/ on the browser, you will see all the views associated with accounts.

accounts/ login/ [name=''login'']
accounts/ logout/ [name=''logout'']
accounts/ password_change/ [name=''password_change'']
accounts/ password_change/done/ [name=''password_change_done'']
accounts/ password_reset/ [name=''password_reset'']
accounts/ password_reset/done/ [name=''password_reset_done'']
accounts/ reset/<uidb64>/<token>/ [name=''password_reset_confirm'']
accounts/ reset/done/ [name=''password_reset_complete'']

At this point if you try to navigate to any of the views say http://127.0.0.1:8000/account/login/, it throws template doesn't exist error.

To use the views, we have to create the templates.

Creating Templates Directory

By default, Django will look for templates in a folder called registration. So, inside accounts app,create a new directory and name it templates, inside templates create another directory and call it registration

cd accounts && mkdir templates
cd templates && mkdir registration

We will create all the templates related to Django authentication Inside registration,

Creating Login template

Create the login.html file add a basic form as shown below

{% extends "base.html" %}
{% block title %}Log-in{% endblock %}
{% block content %}
 <h2>Log-in</h2>
Please, use the following form to log-in. 
<div class="login-form">
<form  action="{% url ''login'' %}"  method="post">method="post">
{{ form.as_p }}
{% csrf_token %}
<input type="submit" value="Log-in">
</form>
</div>

To make sure the login template works fine,Navigate to login url on your browser http://127.0.0.1:8000/account/login/` and this time you should see the login form

At this point, we can only log in existing users and we have one already!.

Login using the superusercredentials you created in Handling Forms

And yes our login works well!. However, After a successful login, Django redirects to profile.

Can we really blame Django, we have not told it where to redirect the authenticated users.

Let's direct them to the home page by adding this to settings.py

LOGIN_REDIRECT_URL =  ''/''

Creating Logout Template

Now that we can login in users successfully, its time to log them out! Inside the registration directory, Create another file and call it logged_out.html

{% block title %}Logout{% endblock %}
{% block content %}
<p>You have sucessfully logged out</p>
<p><a  href="{% url "login" %}">Click here to Login again</a></p>
{% endblock %}

When you go to log out url: http://127.0.0.1:8000/accounts/logout/, you should see

Achiengbytes

  1. The logout template must be named logged_out.html
  2. In settings.py.INSTALLED_APPS make sure 'django.contrib.auth'',` comes after the app class="python">INSTALLED_APPS = [

''accounts', 'django.contrib.admin', ]

Now if you visit the logout url, you should be able to see the template we created and not Django admin logout page

Conclusion

We can successfully login in and log out already existing users. In the next tutorial, we will learn how to register new users.

The source code for this tutorial is available on Github . Connect with me on Twitter'