×

Crée un système d’authentification Django avec une vérification par email

Crée un système d’authentification Django avec une vérification par email

Créer un système d’authentification Django avec une vérification par email est une tâche courante pour sécuriser les comptes utilisateur. Voici un tutoriel détaillé pour mettre en place cette fonctionnalité.

Prérequis :

  • Python installé sur votre système.
  • Django installé. Vous pouvez l’installer avec pip install django.

Étapes pour créer un système d’authentification Django avec vérification par email :

Étape 1 : Création du projet Django

Commencez par créer un nouveau projet Django nommé « auth_project » avec la commande suivante :

django-admin startproject auth_project
cd auth_project

Étape 2 : Création de l’application Django

Ensuite, créez une nouvelle application Django appelée « auth_app » avec la commande suivante :

python manage.py startapp auth_app

Étape 3 : Configuration de la base de données

Ouvrez le fichier auth_project/settings.py et configurez votre base de données, puis exécutez les migrations pour créer les tables de base de données :

python manage.py migrate

Étape 4 : Configuration de l’authentification par email

Dans le fichier auth_project/settings.py, ajoutez la configuration d’authentification par email :

AUTHENTICATION_BACKENDS = [
    'django.contrib.auth.backends.ModelBackend',
    'auth_app.backends.EmailBackend',  # Ajoutez cette ligne
]

AUTH_USER_MODEL = 'auth_app.CustomUser'

LOGIN_REDIRECT_URL = '/'
LOGOUT_REDIRECT_URL = '/'

# Configurez l'envoi d'e-mails avec SMTP ou d'autres méthodes selon vos besoins
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'your-smtp-server.com'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = 'your-email@example.com'
EMAIL_HOST_PASSWORD = 'your-email-password'

Étape 5 : Création du modèle utilisateur personnalisé

Dans le fichier auth_app/models.py, créez un modèle utilisateur personnalisé en étendant AbstractUser. Vous pouvez ajouter des champs personnalisés au modèle utilisateur si nécessaire :

from django.contrib.auth.models import AbstractUser
from django.db import models

class CustomUser(AbstractUser):
    email = models.EmailField(unique=True)  # Champ d'email unique
    email_verified = models.BooleanField(default=False)  # Vérification de l'e-mail

    def __str__(self):
        return self.username

Étape 6 : Création des vues et des URL

Créez des vues pour l’inscription, la connexion, la vérification de l’e-mail et la réinitialisation du mot de passe dans le fichier auth_app/views.py. Vous pouvez utiliser le package django-allauth pour simplifier la gestion de l’authentification par email.

Créé le fichier views.py pour une application Django gérant l’authentification par e-mail avec django-allauth. Ce fichier inclut des vues pour l’inscription, la connexion, la vérification de l’e-mail et la réinitialisation du mot de passe :

Python
from django.contrib.auth.decorators import login_required
from django.contrib.sites.shortcuts import get_current_site
from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.template.loader import render_to_string
from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode
from django.utils.encoding import force_bytes, force_text
from django.contrib.auth.tokens import default_token_generator
from django.contrib.auth import login, authenticate
from django.core.mail import EmailMessage
from django.contrib.auth.forms import PasswordChangeForm
from django.contrib import messages
from django.contrib.auth.views import LoginView, LogoutView, PasswordResetView, PasswordResetConfirmView
from django.views import View
from allauth.account.forms import SignupForm
from allauth.account.views import SignupView
from allauth.account.utils import complete_signup
from allauth.account.models import EmailAddress
from allauth.account.adapter import get_adapter
from allauth.account import app_settings
from allauth.utils import get_next_redirect_url
from allauth.socialaccount.forms import DisconnectForm
from allauth.socialaccount import providers
from allauth.exceptions import ImmediateHttpResponse
from allauth.account.views import PasswordChangeView

class MySignupView(SignupView):
    template_name = 'registration/signup.html'

    def form_valid(self, form):
        if not self.request.user.is_anonymous:
            return redirect('home')
        if app_settings.SIGNUP_VERIFICATION:
            # # # # Activation email sending #
            self.user = form.save(self.request)
            if app_settings.SIGNUP_EMAIL_ENTER_TWICE:
                email_address = EmailAddress.objects.get(user=self.user,
                                                        email=form.cleaned_data['email'])
            else:
                email_address = EmailAddress.objects.get(user=self.user)
            get_adapter(self.request).add_message(self.request,
                                                messages.SUCCESS,
                                                'account/messages/' 'verification_sent.txt',
                                                {'email': self.user.email})
            signals.user_signed_up.send(sender=self.user.__class__,
                                        request=self.request,
                                        user=self.user)
            return redirect('account_signup_verification')

        else:
            # # # # Directly log the user in #
            self.user = form.save(self.request)
            # Automatically log the user in.
            if hasattr(self, 'action'):
                # There is no action for the setup view.
                login(self.request, self.user)
            else:
                self.login_by_request(self.user)
            return complete_signup(
                self.request,
                self.user,
                app_settings.EMAIL_VERIFICATION,
                self.get_success_url())

class MyLoginView(LoginView):
    template_name = 'registration/login.html'

class MyLogoutView(LogoutView):
    next_page = 'login'

class MyPasswordChangeView(PasswordChangeView):
    template_name = 'registration/password_change_form.html'
    success_url = '/'

class MyPasswordResetView(PasswordResetView):
    template_name = 'registration/password_reset_form.html'

class MyPasswordResetConfirmView(PasswordResetConfirmView):
    template_name = 'registration/password_reset_confirm.html'

@login_required
def home(request):
    return render(request, 'home.html')

Ce fichier views.py comprend des vues pour l’inscription, la connexion, la déconnexion, la réinitialisation du mot de passe, et l’affichage de la page d’accueil. Assurez-vous d’ajuster les templates et les URL en conséquence dans votre projet.

N’oubliez pas de configurer correctement vos URL pour utiliser ces vues personnalisées, comme indiqué dans l’étape 8 du tutoriel précédent.

Bash
pip install django-allauth

Dans le fichier auth_project/settings.py, ajoutez 'allauth' et 'allauth.account' à la liste INSTALLED_APPS :

INSTALLED_APPS = [
    # ...
    'allauth',
    'allauth.account',
    # ...
]

Étape 7 : Configuration d’allauth

Dans le fichier auth_project/settings.py, configurez allauth :

AUTHENTICATION_CLASSES = (
    # ...
    'allauth.account.auth_backends.AuthenticationBackend',
    # ...
)

AUTHENTICATION_CLASSES = (
    'django.contrib.auth.backends.ModelBackend',  # Gardez cette ligne
    'allauth.account.auth_backends.AuthenticationBackend',
)

Étape 8 : Configuration de l’URL de l’application

Dans le fichier auth_app/urls.py, configurez les URL pour les vues d’inscription, de connexion, de vérification de l’e-mail et de réinitialisation du mot de passe :

Python
from django.urls import path
from django.contrib.auth.decorators import login_required
from . import views

urlpatterns = [
    path('', views.home, name='home'),

    # Vues d'authentification
    path('signup/', views.MySignupView.as_view(), name='signup'),
    path('login/', views.MyLoginView.as_view(), name='login'),
    path('logout/', views.MyLogoutView.as_view(), name='logout'),
    path('password_change/', views.MyPasswordChangeView.as_view(), name='password_change'),
    path('password_reset/', views.MyPasswordResetView.as_view(), name='password_reset'),
    path('reset/<uidb64>/<token>/', views.MyPasswordResetConfirmView.as_view(), name='password_reset_confirm'),
]

Dans ce fichier urls.py, nous avons configuré les URL pour les vues d’authentification telles que l’inscription, la connexion, la déconnexion, la réinitialisation du mot de passe, et la page d’accueil.

Assurez-vous d’ajuster les noms des vues et les chemins d’URL en fonction de votre projet, et assurez-vous que les noms des vues correspondent aux noms utilisés dans votre fichier views.py.

Étape 9 : Création des templates HTML

Créez des templates HTML pour les vues d’inscription, de connexion et de vérification de l’e-mail dans le répertoire auth_app/templates. Par exemple, signup.html :

Jinja HTML
{% extends 'base.html' %}

{% block content %}
  <h2>Inscription</h2>
  <form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Inscription</button>
  </form>
{% endblock %}

Étape 10 : Exécution de l’application

Exécutez votre application Django en utilisant la commande suivante :

python manage.py runserver

Vous pouvez maintenant accéder à votre application de gestion d’authentification à l’adresse http://127.0.0.1:8000/.

97 commentaires

Avatar
deneme bonusu veren siteler

child porn

Avatar
Tyvbro

behind the counter allergy medicine prescription vs over the counter allergy pills prescribed by doctors

Avatar
Ghbmkx

what is treatment of heartburn order rulide 150mg online cheap

Avatar
Ljadez

buy accutane 20mg generic buy accutane for sale accutane 20mg sale

Avatar
Abhcly

amoxicillin 1000mg generic amoxil 250mg ca buy amoxil 250mg pill

Avatar
Rkoskw

top selling sleep aids order melatonin 3mg generic

Avatar
Sompuc

buy zithromax 500mg pills zithromax over the counter cost zithromax 250mg

Avatar
Ojwxvb

cheap neurontin generic gabapentin 100mg pills

Avatar
Hahywl

buy azithromycin pill how to get azithromycin without a prescription azithromycin 500mg pill

Avatar
Hwmjal

furosemide 40mg oral lasix 100mg sale

Avatar
Uedfdb

prednisolone 20mg for sale order omnacortil 10mg pills buy prednisolone 40mg

Avatar
Kgxukj

amoxil 250mg canada buy amoxicillin 1000mg without prescription order amoxicillin 250mg without prescription

Avatar
Wvfkrx

doxycycline 200mg drug monodox drug

Avatar
Droexy

albuterol 4mg for sale albuterol without prescription ventolin 4mg generic

Avatar
Wswdoe

order synthroid 75mcg pill oral levothroid buy synthroid 100mcg sale

Avatar
Krekge

cost levitra 20mg levitra 20mg generic

Avatar
Dwkgaj

order generic clomid 100mg order generic serophene clomid uk

Avatar
Wicrid

oral zanaflex buy tizanidine no prescription tizanidine order online

Avatar
Ulcucs

cheap rybelsus 14mg buy rybelsus 14mg without prescription order rybelsus 14 mg without prescription

Avatar
Xtajmy

deltasone buy online order prednisone 40mg generic prednisone 40mg ca

Avatar
Xaioqq

isotretinoin without prescription isotretinoin tablet accutane drug

Avatar
Wjfzkf

amoxil 1000mg over the counter amoxil 1000mg uk amoxicillin generic

Avatar
fuck google

child porn

Avatar
Koztah

augmentin 625mg oral augmentin 375mg tablet augmentin 375mg for sale

Avatar
Sfirrz

buy generic zithromax 250mg oral zithromax 250mg order azithromycin without prescription

Avatar
Dcvrpd

cheap synthroid pills order synthroid 75mcg generic cheap levothyroxine without prescription

Avatar
Dvfirc

prednisolone pill oral prednisolone 20mg buy prednisolone 20mg online cheap

Avatar
Tcajaz

order clomiphene 50mg purchase serophene without prescription order clomiphene 50mg online cheap

Avatar
Lnhfsk

buy cheap generic gabapentin gabapentin for sale cost gabapentin 600mg

Avatar
Fzbche

generic lasix furosemide order lasix over the counter

Avatar
Cqlcak

purchase sildenafil pill buy sildenafil 50mg online cheap purchase sildenafil for sale

Avatar
Iasehi

rybelsus 14mg uk order rybelsus pill buy semaglutide 14mg sale

Avatar
Hdamju

vibra-tabs over the counter order monodox generic monodox pill

Avatar
Vqlyks

slots free free roulette play great poker online

Avatar
Yxzbon

vardenafil 10mg canada levitra 10mg us vardenafil order online

Avatar
Okkzvm

cheap lyrica 75mg order generic lyrica 150mg cost pregabalin 75mg

Avatar
Arvvzx

hydroxychloroquine 400mg brand order plaquenil generic plaquenil 200mg cost

Avatar
Qihpqr

brand aristocort triamcinolone 4mg cheap aristocort 4mg tablet

Avatar
Bgebey

viagra cialis buy generic tadalafil cheap generic cialis

Avatar
Ohcrtv

clarinex pill desloratadine 5mg sale cheap desloratadine 5mg

Avatar
Gxozkg

buy methylprednisolone canada buy depo-medrol pills medrol pills canada

Avatar
Vcqfao

write me a essay essays help essays online to buy

Avatar
Dubmjj

buy inderal 10mg generic buy clopidogrel generic clopidogrel for sale online

Avatar
Mqenml

methotrexate 5mg drug order warfarin 5mg for sale order warfarin 5mg without prescription

Avatar
Tyicue

mobic 7.5mg oral celecoxib 100mg uk buy celebrex 100mg online cheap

Avatar
Xniaxe

buy generic reglan for sale metoclopramide 10mg generic hyzaar canada

Avatar
Wdhvsx

buy generic tamsulosin 0.2mg order celecoxib 200mg generic buy celebrex medication

Avatar
Vasnin

order generic nexium esomeprazole oral order topiramate 200mg without prescription

Avatar
Hnytdy

ondansetron cheap order zofran 4mg generic buy aldactone paypal

Avatar
Znajxi

sumatriptan online buy buy levaquin 500mg buy levofloxacin no prescription

Avatar
Mengot

buy zocor 20mg sale buy valtrex 500mg generic buy valacyclovir 500mg

Avatar
Yvffxx

buy cheap generic dutasteride buy zantac generic zantac 300mg pills

Avatar
Enutda

order proscar 5mg for sale where to buy finasteride without a prescription order diflucan 200mg generic

Avatar
Ynlbzm

oral ampicillin cheap penicillin amoxil tablet

Avatar
Aieoyn

order cipro generic – order myambutol 1000mg online augmentin sale

Avatar
Mxhsyo

order ciprofloxacin 1000mg – order bactrim 960mg generic buy augmentin 625mg

Avatar
Swgeps

purchase flagyl for sale – zithromax order online azithromycin 500mg tablet

Avatar
Zyguec

generic ciplox 500 mg – how to get trimox without a prescription
cost erythromycin 250mg

Avatar
Sjjenx

valacyclovir order – buy zovirax paypal buy zovirax 400mg online

Avatar
Vucaws

purchase ivermectin – amoxiclav canada buy tetracycline 500mg for sale

Avatar
Ohizhr

buy flagyl pills for sale – oxytetracycline 250mg drug buy azithromycin 500mg

Avatar
Gisoic

buy acillin cheap buy penicillin generic buy amoxicillin no prescription

Avatar
Miogal

order furosemide 40mg online – minipress online order captopril 25mg online cheap

Avatar
Roxnvq

oral glucophage – order duricef 250mg generic brand lincocin

Avatar
Ynctmd

oral retrovir 300mg – generic allopurinol order zyloprim online cheap

Avatar
Elvqmj

purchase clozapine pills – famotidine 40mg sale pepcid 20mg cost

Avatar
Ebpksl

seroquel 50mg uk – oral luvox eskalith uk

Avatar
Tzqvwj

buy cheap clomipramine – cheap paxil 20mg purchase sinequan without prescription

Avatar
Gwnnar

atarax over the counter – order escitalopram 20mg pills amitriptyline 10mg generic

Avatar
бнанс

I don’t think the title of your article matches the content lol. Just kidding, mainly because I had some doubts after reading the article.

Avatar
Pvvrzg

amoxiclav pills – buy baycip online order cipro 500mg

Avatar
Xatcpq

buy amoxicillin – erythromycin 250mg price order cipro online cheap

Avatar
Claudio

Great post. I was checking constantly this blog and I am impressed!

Very helpful information particularly the last part 🙂 I care for such
info much. I was seeking this certain information for a long time.
Thank you and best of luck.

My blog post :: vpn code 2024

Avatar
Annette

Great beat ! I wish to apprentice at the same time as
you amend your web site, how could i subscribe for a weblog website?
The account aided me a applicable deal. I were a little bit familiar of this your broadcast provided bright clear concept

my web-site; vpn special code

Avatar
Beulah

Appreciating the hard work you put into your site and detailed information you present.
It’s great to come across a blog every once in a while that isn’t the
same unwanted rehashed material. Fantastic read! I’ve saved your site and I’m including your RSS feeds to my Google account.

My web site: vpn special coupon code 2024

Avatar
Buaccu

cheap cleocin – cheap chloramphenicol online chloromycetin cost

Avatar
Wilford

Hi! I’ve been following your blog for a while now and finally got the courage to go ahead and give you a shout out from
Houston Texas! Just wanted to mention keep up the good job!

Here is my web blog … vpn special coupon code 2024

Avatar
Vxgojn

how to buy zithromax – order azithromycin 250mg generic ciplox 500mg uk

Avatar
Ozenyg

stromectol cost – eryc pill cefaclor 500mg tablet

Avatar
Vpsqjj

order ventolin 4mg online – generic allegra 120mg theophylline 400 mg pills

Avatar
परिपक्व अश्लील देखें

child porn

Avatar
Adufsh

brand desloratadine – generic aristocort 10mg order albuterol online cheap

Avatar
Xombgo

medrol 4 mg for sale – montelukast 10mg over the counter order azelastine 10 ml nasal spray

Avatar
Jbawlx

how to buy micronase – pioglitazone cheap order forxiga for sale

Avatar
Mkkfol

prandin 1mg drug – buy jardiance generic buy jardiance medication

Avatar
Spqmlw

glycomet usa – januvia order online brand precose 50mg

Avatar
Itwneu

order rybelsus 14 mg for sale – glucovance buy generic desmopressin online

Avatar
Qtonmy

buy ketoconazole 200mg generic – buy generic nizoral buy sporanox 100mg generic

Avatar
Cfuuyh

buy famvir 500mg online cheap – order valaciclovir 1000mg generic order valcivir without prescription

Avatar
Ypkwxp

order digoxin 250mg online cheap – buy dipyridamole 25mg sale buy furosemide 100mg generic

Avatar
Ernesto

Greetings! Very useful advice in this particular
article! It’s the little changes that will make the most important changes.
Thanks a lot for sharing!

My website: Deneme Bonusu Veren Siteler

Avatar
Реферальная программа binance

Your article helped me a lot, is there any more related content? Thanks!

Avatar
Registrácia

Thank you for your sharing. I am worried that I lack creative ideas. It is your article that makes me full of hope. Thank you. But, I have a question, can you help me?

Avatar
starzbet

starzbet

Avatar
Tennbg

cialis soft tabs online nothing – caverta pills percy viagra oral jelly american

Avatar
Angel

Great beat ! I wish facebook vs eharmony to find love online apprentice whilst you amend your web
site, how could i subscribe for a blog website?
The account aided me a appropriate deal. I had been a little bit acquainted of this your broadcast
provided vivid clear idea

Avatar
b^onus de indicac~ao da binance

I don’t think the title of your article matches the content lol. Just kidding, mainly because I had some doubts after reading the article.

Laisser un commentaire