ba-thesis/app/authentication/views.py

71 lines
2.3 KiB
Python

from urllib.parse import urlencode
from uuid import uuid4
from django.shortcuts import render
from django.conf import settings
from django.urls import reverse
from django.core.exceptions import PermissionDenied
from django.http import HttpResponseBadRequest
import withings.api
def register_init(request):
if request.user.is_authenticated:
raise PermissionDenied('You are already registered and logged in.')
# Generate a unique token and save it for later
spoof_protection_token = str(uuid4())
request.session['spoof_protection_token'] = spoof_protection_token
auth_url_base = 'https://account.withings.com/oauth2_user/authorize2'
auth_url_params = {
'response_type': 'code',
'client_id': settings.WITHINGS_CONFIG['CLIENT_ID'],
'scope': 'user.metrics,user.activity',
'redirect_uri': request.build_absolute_uri(reverse('register-continue')),
'state': spoof_protection_token
}
auth_url = f"{auth_url_base}?{urlencode(auth_url_params)}"
context = {
"auth_url": auth_url
}
return render(request, 'authentication/register-init.html', context)
def register_continue(request):
# Parse GET request parameters
authorization_code = request.GET.get('code')
authorization_state = request.GET.get('state')
if not authorization_code:
return HttpResponseBadRequest()
if not authorization_state:
return HttpResponseBadRequest()
if not request.session.get('spoof_protection_token', None) == authorization_state:
return HttpResponseBadRequest()
# Fetch access and refresh tokens and save them to session storage
redirect_uri = request.build_absolute_uri(reverse('register-continue'))
# DEBUG use an API mock
response_data = withings.api.mock_fetch_withings_tokens(authorization_code, redirect_uri)
if response_data['status'] != 0:
return HttpResponseBadRequest()
withings.api.save_tokens_to_session(request, response_data)
# TODO add user registration form
# TODO once user registration form is valid, make gotify API calls
# TODO once gotify is set up, create and save database objects
context = {}
return render(request, 'authentication/register-continue.html', context)
def register_finalize(request):
# TODO implement
return render(request, 'authentication/register-finalize.html')