From 77ee7987a28d31301abd89dc48b831641d1f9663 Mon Sep 17 00:00:00 2001 From: Santiago Lamora Date: Tue, 29 Oct 2019 10:58:54 +0100 Subject: [PATCH] Add custom login view to replace of django.auth --- musician/forms.py | 33 +++++++++++++++++++++++++++++++++ musician/urls.py | 4 +--- musician/views.py | 11 +++++++++++ 3 files changed, 45 insertions(+), 3 deletions(-) create mode 100644 musician/forms.py diff --git a/musician/forms.py b/musician/forms.py new file mode 100644 index 0000000..e344049 --- /dev/null +++ b/musician/forms.py @@ -0,0 +1,33 @@ +import urllib.parse + +import requests +from django.contrib.auth.forms import AuthenticationForm + +from . import api + + +def authenticate(username, password): + url = api.build_absolute_uri('token-auth') + r = requests.post( + url, + data={"username": username, "password": password}, + ) + + token = r.json().get("token", None) + return token + + +class LoginForm(AuthenticationForm): + + def clean(self): + username = self.cleaned_data.get('username') + password = self.cleaned_data.get('password') + + if username is not None and password: + self.token = authenticate(username, password) + if self.token is None: + raise self.get_invalid_login_error() + else: + return self.token + + return self.cleaned_data diff --git a/musician/urls.py b/musician/urls.py index 10cbdf4..b8a6765 100644 --- a/musician/urls.py +++ b/musician/urls.py @@ -4,7 +4,6 @@ URL routes definition. Describe the paths where the views are accesible. """ -from django.contrib.auth import views as auth_views from django.urls import path from . import views @@ -13,8 +12,7 @@ from . import views app_name = 'musician' urlpatterns = [ - path('auth/login/', auth_views.LoginView.as_view(template_name='auth/login.html', - extra_context={'version': '0.1'}), name='login'), + path('auth/login/', views.LoginView.as_view(), name='login'), # path('auth/logout/', views.LogoutView.as_view(), name='logout'), path('dashboard/', views.DashboardView.as_view(), name='dashboard'), ] diff --git a/musician/views.py b/musician/views.py index 1102473..7e0568f 100644 --- a/musician/views.py +++ b/musician/views.py @@ -1,9 +1,20 @@ from django.contrib.auth.mixins import LoginRequiredMixin from django.shortcuts import render +from django.urls import reverse_lazy from django.views.generic.base import TemplateView +from django.views.generic.edit import FormView +from . import api, get_version +from .forms import LoginForm from .mixins import CustomContextMixin class DashboardView(CustomContextMixin, TemplateView): ## TODO LoginRequiredMixin template_name = "musician/dashboard.html" + + +class LoginView(FormView): + template_name = 'auth/login.html' + form_class = LoginForm + success_url = reverse_lazy('musician:dashboard') + extra_context = {'version': get_version()}