From 5abdcd56db16913e1b0dc0980e2cff7d45e3d9b7 Mon Sep 17 00:00:00 2001 From: Santiago Lamora Date: Tue, 10 Dec 2019 13:04:04 +0100 Subject: [PATCH] Include profile context var for loggued users. --- musician/api.py | 12 +++++++++--- musician/mixins.py | 12 ++++++++++++ musician/templates/musician/base.html | 2 +- musician/views.py | 2 -- 4 files changed, 22 insertions(+), 6 deletions(-) diff --git a/musician/api.py b/musician/api.py index d712a24..55a2b73 100644 --- a/musician/api.py +++ b/musician/api.py @@ -4,6 +4,9 @@ import urllib.parse from django.conf import settings from django.urls.exceptions import NoReverseMatch +from .models import UserAccount + + DOMAINS_PATH = 'domains/' TOKEN_PATH = '/api-token-auth/' @@ -75,9 +78,12 @@ class Orchestra(object): _, output = self.request("GET", pattern_name) return output - def retreve_profile(self): - _, output = self.request("GET", 'my-account') - return output + def retrieve_profile(self): + status, output = self.request("GET", 'my-account') + if status >= 400: + raise PermissionError("Cannot retrieve profile of an anonymous user.") + return UserAccount.new_from_json(output[0]) + def verify_credentials(self): """ diff --git a/musician/mixins.py b/musician/mixins.py index 1785d98..5c65f47 100644 --- a/musician/mixins.py +++ b/musician/mixins.py @@ -46,6 +46,11 @@ class ExtendedPaginationMixin: class UserTokenRequiredMixin(UserPassesTestMixin): + """ + Checks that the request has a token that authenticates him/her. + If the user is logged adds context variable 'profile' with its information. + """ + def test_func(self): """Check that the user has an authorized token.""" token = self.request.session.get(SESSION_KEY_TOKEN, None) @@ -60,3 +65,10 @@ class UserTokenRequiredMixin(UserPassesTestMixin): return False return True + + def get_context_data(self, **kwargs): + context = super().get_context_data(**kwargs) + context.update({ + 'profile': self.orchestra.retrieve_profile(), + }) + return context diff --git a/musician/templates/musician/base.html b/musician/templates/musician/base.html index 2839aee..e2c5537 100644 --- a/musician/templates/musician/base.html +++ b/musician/templates/musician/base.html @@ -59,7 +59,7 @@