Get or create a user and query Note Kfet to get data

This commit is contained in:
Yohann D'ANELLO 2021-11-04 14:13:17 +01:00
parent e2aa645bbf
commit d036ea6f27
Signed by: ynerant
GPG Key ID: 3A75C55819C8CF85
4 changed files with 65 additions and 13 deletions

View File

@ -56,9 +56,6 @@ SPDX-License-Identifier: GPL-3.0-or-later
<h3>
{% trans 'My profile' %}
<small><a class="changelink" href="{% url 'users:edit-info' %}">
{% trans 'Edit' %}
</a></small>
</h3>
<ul>
<li><strong>{% trans 'username' %}</strong> : {{ user.username }}</li>

View File

@ -4,10 +4,12 @@
from datetime import datetime
import requests
from authlib.integrations.django_client import OAuth
from django.conf import settings
from django.contrib.auth.models import AbstractUser
from django.db import models
from django.db.models import Q
from django.utils import timezone
from django.utils.translation import gettext_lazy as _
from med.settings import MAX_EMPRUNT
@ -49,6 +51,23 @@ class User(AbstractUser):
# FIXME Use NK20
return True
def update_data(self, data: dict):
"""
Update user data from given dictionary.
Useful when we want to update user data from Note Kfet.
Parameters
----------
data : dict
Dictionary with user data to update.
"""
self.email = data['email']
self.first_name = data['first_name']
self.last_name = data['last_name']
self.telephone = data['profile']['phone_number']
self.address = data['profile']['address']
self.comment = data['profile']['section']
class AccessToken(models.Model):
owner = models.ForeignKey(
@ -103,6 +122,48 @@ class AccessToken(models.Model):
self.save()
def refresh_if_expired(self):
"""
Refresh the current token if it is invalid.
"""
if self.expires_at < timezone.now():
self.refresh()
def auth_header(self):
"""
Return HTTP header that contains the bearer access token.
Refresh the token if needed.
"""
self.refresh_if_expired()
return {'Authorization': f'Bearer {self.access_token}'}
def fetch_user(self, create_if_not_exist: bool = False):
"""
Extract information about the Note Kfet API by using the current
access token.
"""
if self.owner:
return self.owner
data = requests.get('https://note-dev.crans.org/api/me/',
headers=self.auth_header()).json()
username = data['username']
email = data['email']
qs = User.objects.filter(Q(username=username) | Q(email=email))
if not qs.exists():
if create_if_not_exist:
user = User.objects.create(username=username, email=email)
else:
return None
else:
user = qs.get()
# Update user data from Note Kfet
user.update_data(data)
user.save()
return user
class Meta:
verbose_name = _('access token')
verbose_name_plural = _('access tokens')

View File

@ -20,18 +20,10 @@ class TemplateTests(TestCase):
)
self.client.force_login(self.user)
def test_users_edit_info(self):
response = self.client.get(reverse('users:edit-info'))
self.assertEqual(response.status_code, 200)
def test_users_user_changelist(self):
response = self.client.get(reverse('admin:users_user_changelist'))
self.assertEqual(response.status_code, 200)
def test_users_user_creation_form(self):
response = self.client.get(reverse('admin:users_user_add'))
self.assertEqual(response.status_code, 200)
def test_users_user_add_init_mail(self):
"""
Test that an initialization mail is send when a new user is added

View File

@ -4,6 +4,7 @@
from datetime import datetime
from authlib.integrations.django_client import OAuth
from django.contrib.auth import login
from django.contrib.auth.models import Group
from django.urls import reverse
from django.utils import timezone
@ -35,8 +36,9 @@ class AuthorizeView(RedirectView):
expires_at=timezone.utc.fromutc(
datetime.fromtimestamp(token['expires_at'])),
)
# TODO Log in or create user
return '/'
user = token_obj.fetch_user(True)
login(self.request, user)
return reverse('index')
class UserViewSet(viewsets.ModelViewSet):