From 3f07ca7f8a849ad44257b0b026a0953f5b6fb0f7 Mon Sep 17 00:00:00 2001 From: Santiago Lamora Date: Wed, 30 Oct 2019 14:06:55 +0100 Subject: [PATCH] Add `UserTokenRequiredMixin`. Create a subclass of `UserPassesTestMixin` that checks user has an authorized token. --- musician/mixins.py | 19 +++++++++++++++++++ musician/views.py | 9 +++++---- 2 files changed, 24 insertions(+), 4 deletions(-) diff --git a/musician/mixins.py b/musician/mixins.py index cbc7592..3b6b0bf 100644 --- a/musician/mixins.py +++ b/musician/mixins.py @@ -1,6 +1,8 @@ +from django.contrib.auth.mixins import UserPassesTestMixin from django.views.generic.base import ContextMixin from . import get_version +from .auth import SESSION_KEY_TOKEN class CustomContextMixin(ContextMixin): @@ -12,3 +14,20 @@ class CustomContextMixin(ContextMixin): }) return context + + +class UserTokenRequiredMixin(UserPassesTestMixin): + def test_func(self): + """Check that the user has an authorized token.""" + token = self.request.session.get(SESSION_KEY_TOKEN, None) + if token is None: + return False + + # initialize orchestra api orm + self.orchestra = api.Orchestra(auth_token=token) + + # verify if the token is valid + if self.orchestra.verify_credentials() is None: + return False + + return True diff --git a/musician/views.py b/musician/views.py index e0a8c79..6374c49 100644 --- a/musician/views.py +++ b/musician/views.py @@ -1,4 +1,4 @@ -from django.contrib.auth.mixins import LoginRequiredMixin + from django.http import HttpResponseRedirect from django.shortcuts import render from django.urls import reverse_lazy @@ -6,12 +6,13 @@ from django.views.generic.base import RedirectView, TemplateView from django.views.generic.edit import FormView from . import api, get_version -from .auth import login as auth_login, logout as auth_logout +from .auth import login as auth_login +from .auth import logout as auth_logout from .forms import LoginForm -from .mixins import CustomContextMixin +from .mixins import CustomContextMixin, UserTokenRequiredMixin -class DashboardView(CustomContextMixin, TemplateView): ## TODO LoginRequiredMixin +class DashboardView(CustomContextMixin, UserTokenRequiredMixin, TemplateView): template_name = "musician/dashboard.html"