create user on login

This commit is contained in:
Francis 2020-07-22 04:05:34 +02:00
parent 74cdbc76e5
commit 21e536b393
No known key found for this signature in database
GPG key ID: 071BEA4C2B10077C

View file

@ -1,8 +1,11 @@
import logging import logging
from django.shortcuts import redirect
from django.http.request import HttpRequest
import requests 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/' USER_API_URI = 'https://adams.ugent.be/oauth/api/current_user/'
ACCESS_TOKEN_URI = 'https://adams.ugent.be/oauth/oauth2/token/' ACCESS_TOKEN_URI = 'https://adams.ugent.be/oauth/oauth2/token/'
@ -13,6 +16,7 @@ CLIENT_SECRET = 'blargh'
logger = logging.getLogger(__file__) logger = logging.getLogger(__file__)
class OAuthException(Exception): class OAuthException(Exception):
pass pass
@ -39,7 +43,9 @@ def register_callback(req: HttpRequest):
raise OAuthException(f'username and id are expected values: {user}') raise OAuthException(f'username and id are expected values: {user}')
else: else:
logger.debug(f'Succesfully authenticated user: {user["username"]} with id: {user["id"]}') 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: else:
raise OAuthException(f'Status code not 200, response: {response.json()}') raise OAuthException(f'Status code not 200, response: {response.json()}')
except OAuthException as e: except OAuthException as e:
@ -48,6 +54,15 @@ def register_callback(req: HttpRequest):
return register('') 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): def user_info(access_token):
r = requests.get(USER_API_URI, headers={'Authorization': f'Bearer {access_token}'}) r = requests.get(USER_API_URI, headers={'Authorization': f'Bearer {access_token}'})
return r.json() return r.json()