add oauth basic

This commit is contained in:
Francis 2020-07-22 03:48:22 +02:00
parent d0ff75f2c6
commit 2d80216ddf
No known key found for this signature in database
GPG key ID: 071BEA4C2B10077C
5 changed files with 64 additions and 1 deletions

View file

@ -32,7 +32,8 @@ ALLOWED_HOSTS = []
OWN_APPS = [
'events',
'users'
'users',
'oauth',
]
INSTALLED_APPS = [

View file

@ -19,4 +19,5 @@ from django.urls import path, include
urlpatterns = [
path('events/', include('events.urls')),
path('admin/', admin.site.urls),
path('login/zeus/', include('oauth.urls')),
]

0
oauth/__init__.py Normal file
View file

8
oauth/urls.py Normal file
View file

@ -0,0 +1,8 @@
from django.urls import path
from . import views
urlpatterns = [
path('register', views.register),
path('authorized', views.register_callback),
]

53
oauth/views.py Normal file
View file

@ -0,0 +1,53 @@
import logging
from django.shortcuts import redirect
from django.http.request import HttpRequest
import requests
USER_API_URI = 'https://adams.ugent.be/oauth/api/current_user/'
ACCESS_TOKEN_URI = 'https://adams.ugent.be/oauth/oauth2/token/'
AUTHORIZE_URI = 'https://adams.ugent.be/oauth/oauth2/authorize/'
CLIENT_ID = 'tomtest'
CLIENT_SECRET = 'blargh'
logger = logging.getLogger(__file__)
class OAuthException(Exception):
pass
def register(_):
RESPONSE_TYPE = 'code'
REDIRECT_URI = 'http://localhost:8000/login/zeus/authorized'
return redirect(f'{AUTHORIZE_URI}?response_type={RESPONSE_TYPE}&client_id={CLIENT_ID}&redirect_uri={REDIRECT_URI}')
def register_callback(req: HttpRequest):
code = req.GET['code']
response = requests.post(ACCESS_TOKEN_URI, data={'code': code,
'grant_type': 'authorization_code',
'client_id': CLIENT_ID,
'client_secret': CLIENT_SECRET,
'redirect_uri': 'http://localhost:8000/login/zeus/authorized'})
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"]}')
pass
else:
raise OAuthException(f'Status code not 200, response: {response.json()}')
except OAuthException as e:
logger.error(e)
return register('')
def user_info(access_token):
r = requests.get(USER_API_URI, headers={'Authorization': f'Bearer {access_token}'})
return r.json()