Skip to content

Code documentation

rrudling edited this page Aug 19, 2021 · 3 revisions

Code Documentation

Prerequisite

  1. pip install authlib, authlib package must be installed.
  2. secrets.py must contain ApplicationID and ClientSecret (Ask the responsible for those information)
  3. Go to settings to implement the
# settings.py
...
INSTALLED_APPS += ('kth_login', ...)
...
AUTHLIB_OAUTH_CLIENTS = {
    'kth': {
        'client_id': APPLICATION_ID,
        'client_secret': CLIENT_SECRET,
        'api_base_url': 'https://login.ug.kth.se/adfs/oauth2/',
    }
}

Login

The login workflow will be describe in this section.

  1. To see if someone is logged in or not
def any_view(request):
    if request.user.is_authenticated():
        # A user is already in session/logged in.
    else:
        # A user is not logged in yet. Continue to step 2.
  1. To login in a user, verify the information given a user from the model django.contrib.auth.model (User) must be return otherwise it is returned None.
from django.urls import reverse
from django.contrib.auth import login
...
def any_view(request):
    ...
    ''' 
    The parameter must not be None
    @params request comes from the view parameter.
    @params user comes defined from bullet-point 2 below. Which needs to be a model from django.contrib.auth.model (User) 
    '''
    login(request, user)
    ...
  1. To authenticate a user with Authlib This is the step where we will need information given to us by KTH using OpenID.
# Using Authlib
from django.shortcuts import redirect
from django.urls import reverse
from authlib.integrations.django_client import OAuth


oauth = OAuth()
oauth.register(
    name='kth',
    server_metadata_url='https://.../.well-known/openid-configuration',
    client_kwargs={
        'scope': 'openid email username',
    },
    authorization_endpoint='https://.../authorize/',
    token_endpoint = 'https://.../token/',
    response_type = 'code',
)

def login(request):
    # redirect_uri = localhost:8080/.../callback
    redirect_uri = request.build_absolute_uri(reverse('this_string_comes_from_name_param_in_url.py'))
    return oauth.kth.authorize_redirect(request, redirect_uri)

def authorize(request):
    token = oauth.kth.authorize_access_token(request)
    user = oauth.kth.parse_id_token(request, token)
    request.session['user'] = user
    ...
    # AIS repo have a specific way of saving a user and uses the files from `lib/KTH_Catalog.py`
    # Steps above (2)
    ...
    return redirect('/')
Clone this wiki locally