From 21e536b3939e4ee17f5efe65dc2138c6ee499689 Mon Sep 17 00:00:00 2001 From: Francis Date: Wed, 22 Jul 2020 04:05:34 +0200 Subject: [PATCH] create user on login --- oauth/views.py | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/oauth/views.py b/oauth/views.py index 6106c31..b380a03 100644 --- a/oauth/views.py +++ b/oauth/views.py @@ -1,8 +1,11 @@ import logging -from django.shortcuts import redirect -from django.http.request import HttpRequest import requests +from django.contrib.auth import login +from django.http.request import HttpRequest +from django.shortcuts import redirect + +from users.models import CustomUser USER_API_URI = 'https://adams.ugent.be/oauth/api/current_user/' ACCESS_TOKEN_URI = 'https://adams.ugent.be/oauth/oauth2/token/' @@ -13,6 +16,7 @@ CLIENT_SECRET = 'blargh' logger = logging.getLogger(__file__) + class OAuthException(Exception): pass @@ -39,7 +43,9 @@ def register_callback(req: HttpRequest): raise OAuthException(f'username and id are expected values: {user}') else: logger.debug(f'Succesfully authenticated user: {user["username"]} with id: {user["id"]}') - pass + validated_user = validate_user(user['zeus_id'], user['username']) + login(req, validated_user) + redirect('/') else: raise OAuthException(f'Status code not 200, response: {response.json()}') except OAuthException as e: @@ -48,6 +54,15 @@ def register_callback(req: HttpRequest): return register('') +def validate_user(zeus_id, username) -> CustomUser: + user = CustomUser.objects.get(zeus_id=zeus_id) + if user is None: + return CustomUser.objects.create_user(zeus_id, username) + user.username = username + user.save() + return user + + def user_info(access_token): r = requests.get(USER_API_URI, headers={'Authorization': f'Bearer {access_token}'}) return r.json()