2020-07-22 03:48:22 +02:00
|
|
|
import logging
|
|
|
|
|
|
|
|
import requests
|
2020-07-22 04:32:25 +02:00
|
|
|
from django.conf import settings
|
2020-07-22 04:05:34 +02:00
|
|
|
from django.contrib.auth import login
|
|
|
|
from django.http.request import HttpRequest
|
|
|
|
from django.shortcuts import redirect
|
|
|
|
|
|
|
|
from users.models import CustomUser
|
2020-07-22 03:48:22 +02:00
|
|
|
|
|
|
|
logger = logging.getLogger(__file__)
|
|
|
|
|
2020-07-22 04:05:34 +02:00
|
|
|
|
2020-07-22 03:48:22 +02:00
|
|
|
class OAuthException(Exception):
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
|
|
def register(_):
|
|
|
|
RESPONSE_TYPE = 'code'
|
2020-07-22 04:32:25 +02:00
|
|
|
return redirect(f'{settings.OAUTH["AUTHORIZE_URI"]}?'
|
|
|
|
f'response_type={RESPONSE_TYPE}&'
|
|
|
|
f'client_id={settings.OAUTH["CLIENT_ID"]}&'
|
|
|
|
f'redirect_uri={settings.OAUTH["REDIRECT_URI"]}')
|
2020-07-22 03:48:22 +02:00
|
|
|
|
|
|
|
|
|
|
|
def register_callback(req: HttpRequest):
|
|
|
|
code = req.GET['code']
|
2020-07-22 04:32:25 +02:00
|
|
|
response = requests.post(settings.OAUTH["AUTHORIZE_URI"],
|
|
|
|
data={'code': code,
|
|
|
|
'grant_type': 'authorization_code',
|
|
|
|
'client_id': settings.OAUTH["CLIENT_ID"],
|
|
|
|
'client_secret': settings.OAUTH["CLIENT_SECRET"],
|
|
|
|
'redirect_uri': settings.OAUTH["REDIRECT_URI"]})
|
2020-07-22 03:48:22 +02:00
|
|
|
try:
|
|
|
|
if response.status_code == 200:
|
|
|
|
json: dict = response.json()
|
|
|
|
# TODO: maybe later do something with the refresh token.
|
|
|
|
user: dict = user_info(json['access_token'])
|
|
|
|
if 'username' not in user.keys() or 'id' not in user.keys():
|
|
|
|
raise OAuthException(f'username and id are expected values: {user}')
|
|
|
|
else:
|
|
|
|
logger.debug(f'Succesfully authenticated user: {user["username"]} with id: {user["id"]}')
|
2020-07-22 04:28:01 +02:00
|
|
|
validated_user = validate_user(user['id'], user['username'])
|
2020-07-22 04:05:34 +02:00
|
|
|
login(req, validated_user)
|
|
|
|
redirect('/')
|
2020-07-22 03:48:22 +02:00
|
|
|
else:
|
|
|
|
raise OAuthException(f'Status code not 200, response: {response.json()}')
|
|
|
|
except OAuthException as e:
|
|
|
|
logger.error(e)
|
|
|
|
|
|
|
|
return register('')
|
|
|
|
|
|
|
|
|
2020-07-22 04:05:34 +02:00
|
|
|
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
|
|
|
|
|
|
|
|
|
2020-07-22 03:48:22 +02:00
|
|
|
def user_info(access_token):
|
2020-07-22 04:32:25 +02:00
|
|
|
r = requests.get(settings.OAUTH["USER_API_URI"], headers={'Authorization': f'Bearer {access_token}'})
|
2020-07-22 03:48:22 +02:00
|
|
|
return r.json()
|