Add custom login view to replace of django.auth

This commit is contained in:
Santiago Lamora 2019-10-29 10:58:54 +01:00
parent 750d5cc465
commit 77ee7987a2
3 changed files with 45 additions and 3 deletions

33
musician/forms.py Normal file
View File

@ -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

View File

@ -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'),
]

View File

@ -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()}