Introduction
Let me start with the question of why a user authentication system is needed at all?
-
Authentication is needed for something like this:
- Provide exclusive opportunities and access to previously closed site features. For example, commenting.
- Collect a database of your clients, who are already loyal to you
- Be constantly in touch with users. You can send them email newsletters or website notifications.
It is important to have an authentication system on your website, if only because this way you will expand your network of clients/friends/partners/readers/customers (underline what is appropriate)
Let me make a reservation right away that the authentication system that you and I will write is not based on the built-in Django application, django.contrib.auth. This will be a separate application with a separate model for it. We will create a simple and understandable authorization system, based on anonymous browser session keys.
Let's get down to business.. Implementing user registration and authentication in Django is not difficult, although it requires specific skills. To begin with, we need a project we will implement user authentication system for .
Here is the finished basic project.
Or a link to the repository on github
And if you still haven’t skipped to the finished solution, please follow me.
How session key authentication works
Now, so that you understand what I will write about , I need to explain how sessions generally work in django and how we can use them to create users.
A session is a small file generated by the server that stores information about the user. This file remains on the server so that the server knows who it is communicating with.
By user we mean the browser.
The process of communication between the user and the server
I talk more about sessions in django in the chapter setting up views in django
Setting up scripts and jQuery
Let's say you have your own website on which you need to implement an authentication system. To create a login page and a registration page. The question arises, where to start? I suggest starting with writing ajax requests.
But before that, let's create the appropriate directories for storing scripts and connect these scripts to our templates. Let's put you now in the Auth application folder. Then:
In the signup.html template, insert it at the very end before endblock
In the login.html template, do the same thing, just insert
Now that everything you need has been pre-configured, you can move on to the essence or how to make this ajax request work.
Ajax request for registration
The most important thing is at the very beginning. Code of the previously connected script on_signup.js
Now let's deal with it in order.
What is csrftoken? CSRF token (Cross-Site Request Forgery) is a unique server-generated string. It allows you to protect yourself from hackers faking requests to the server for unauthorized access to site user resources.
In order for the form to be sent using the POST method, this token must be transferred to the server through a request.
Next, we collect data from the completed form and save it into a form object which we will send to the server.
We define the method for sending, the address at which we will contact the server. You need to remember it, because you will need to create the appropriate function to process this address.
Next, we define the behavior of our script. When the code returns 200, meaning the user has successfully registered, we will add a caption above the form and redirect him to the main page.
If it fails, that is, if the code is returned 406 (in my case), we will give a completely different message to the user. So that he corrects the identified errors.
Well, in the end, as I’m already used to, I set up the appropriate events. In this case, pressing the Singup button.
Ajax login request
It’s the same technique, only for confirmation, that is, entry to the site.
And here a little less data will be sent than during registration
Create and configure django user model
Now that you have working ajax requests, you need to make an appropriate model for the user.
In the models.py file add:
Don't forget to apply migrations to the database
Setting up views
Now you have a user model, scripts for sending requests to the server, templates, styles. After all, the site that based on django. What else do we need? I left the most important thing for later, namely validation, authentication and authorization of users. All this happens on the server. I added 3 more paths to urls.py in the Auth application. In total, your Auth/urls.py should look something like this:
Now let's look at each of them separately. Let's discuss all the nuances, so to speak.
Registration view
If we describe this function in general, then it is a set of a wide variety of checks. Such as password length, email address format compliance, and others. And if all checks are passed, a user is created.
Login view
The login function is also a bunch of checks for the correctness of the entered data. Except that we create additional variables in the current session, such as is_auth and username. And if all the entered data is correct, the function will return the corresponding message and code.
Logout view
Everything is quite simple here. We tell the server to clear (forget) about the current session with the user, and then redirect to the main one.
Authentication Use Case
Now that our site can register new users and detect the entry of existing ones, a question arises. What exactly should we do next?
Firstly, I suggest changing the login label to logout. To do this, we modify our home page. In home.html Instead
Than paste
Secondly, I propose to display the name and email of our user.
Insert this piece of template after the last element of the list
And in Main/views.py the home function will need to be improved
First we imported the Users model. Then we find the user using the value we saved earlier in the session,a username. We received it during logging, if you haven't forgotten yet.
After reloading the page and logging in, you will be redirected to the main page and see something like this
This is the basic application of an authentication system. There's still a lot you can do with this. For example, create a separate page for each user or provide the ability to comment. But this is beyond the scope of this article. My goal was to show you how you can implement a user authentication system yourself in django, and it’s up to you to decide how to use it.
Conclusions
Now, you have everything you need to create your own user registration and authorization forms. It wasn't difficult, was it? Although, if you are not used to it, it may seem otherwise. To summarize.
-
Losses:
- You wasted 30 minutes of your life.
- Approximately 100 Mb of hard disk space
-
Acquisitions:
- We learned, studied and most importantly tried to use sessions and cookies in practice
- Django application and skills to connect it to your project
- Purchased templates and scripts that can be referenced and which can be used as a basis for your own
- Update content on the page without reloading it
- Skills in writing templates and forms for registration and authorization
- Ability to process ajax requests in python
- Ability to create ajax requests, POST and GET
I hope the time spent was well spent. And you learned something for yourself.
For those looking for a ready-made solution
Here is a link to download thefinished Django application.
Or a link to download the entire Django project.
Or if you don’t want to mindlessly download files from unknown sites, here is a link to the github repository.
If you decide to download the application, congratulations, you grasp the main feature of django, namely its modularity. This is how you can connect it to your site.
Add the application to settings.py
In urls.py at the project level, connect routes.
Everything is ready and configured.
Materials used and useful resources
- How to upload files
- How to send a ajax request
- Events in jQuery
- Manipulation of page elements
- Using crfs-token with django
- A good start for those just starting out