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
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()