Skip to content

Instantly share code, notes, and snippets.

@gtindo
Created December 17, 2019 23:02
Show Gist options
  • Save gtindo/9d8c22c8374832e6b4a158a521db8ae4 to your computer and use it in GitHub Desktop.
Save gtindo/9d8c22c8374832e6b4a158a521db8ae4 to your computer and use it in GitHub Desktop.
#1 - Blog
{% extends 'custom_auth/base.html' %}
{% block title %} Authentication page {% endblock %}
{% block content %}
<form method="post" action="{% url 'custom_auth:auth_view' %}">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="valider" />
</form>
{% endblock %}
from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.models import User
from django.contrib.auth.hashers import check_password
class CustomModelBackend(ModelBackend):
def authenticate(self, request, email=None, password=None, **kwargs):
if email is None or password is None:
return
try:
user = User.objects.get(email=email)
except User.DoesNotExist:
return
else:
if check_password(password, user.password) and self.user_can_authenticate(user):
return user
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{% block title %} {% endblock %}</title>
</head>
<body>
<div>
{% if messages %}
<ul class="messages">
{% for message in messages %}
<li {% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
</div>
{% block content %}
{% endblock %}
</body>
</html>
from django.contrib.auth import authenticate, login
from django import forms
class AuthForm(forms.Form):
email = forms.CharField(max_length=255, required=True, widget=forms.TextInput)
password = forms.CharField(max_length=255, required=True, widget=forms.PasswordInput)
def check_and_authenticate(self, request):
"""
Cette methode recurpere les donnees du dictionnaire cleaned_data, et authentifie l'utilisateur
Elle retourne True si l'utilisateur existe et False sinon
:param request: Contexte de la requete en cours
:return: `bool`
"""
user = authenticate(
request, email=self.cleaned_data["email"], password=self.cleaned_data["password"]
)
if user is not None:
login(request, user)
return True
return False
AUTHENTICATION_BACKENDS = [
'django.contrib.auth.backends.ModelBackend',
'custom_auth.backend.CustomModelBackend'
]
{% extends 'custom_auth/base.html' %}
{% block title %} Your are authenticated {% endblock %}
{% block content %}
<p>
Your are authenticated
</p>
{% endblock %}
from django.urls import path
from .views import AuthView, success_view
app_name = "custom_auth"
urlpatterns = [
path("auth/", AuthView.as_view(), name="auth_view"),
path("success/", success_view, name="success_view")
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment