Commit 4a511930 authored by Alex's avatar Alex
Browse files

Added route decorator for Flask (using sessions)

parent b963dcac
from .client import Materials
from .courses import Course
from .resources import Resource
from .flask_utils import using_materials, materials_login, init_app, set_redirect_url
\ No newline at end of file
from functools import wraps
from typing import Optional
from flask import abort, request, session, redirect, url_for
from .client import Materials
IMPERIAL_DOC_MATERIALS_APP_NAME = ""
IMPERIAL_DOC_MATERIALS_URL_PREFIX = ""
IMPERIAL_DOC_MATERIALS_REDIRECT_URL = ""
IMPERIAL_DOC_MATERIALS_SECRET_KEY = ""
SESSION_KEY_NAME = f'{IMPERIAL_DOC_MATERIALS_APP_NAME}-imperial_doc_materials_client'
def init_app(app):
global IMPERIAL_DOC_MATERIALS_SECRET_KEY
global IMPERIAL_DOC_MATERIALS_APP_NAME
global IMPERIAL_DOC_MATERIALS_URL_PREFIX
try:
IMPERIAL_DOC_MATERIALS_SECRET_KEY = app.config["SECRET_KEY"]
except KeyError:
raise "Please set the SECRET_KEY for your app's config.py"
try:
IMPERIAL_DOC_MATERIALS_APP_NAME = app.config["APP_NAME"]
except KeyError:
raise "Please set the APP_NAME in your app's config.py"
try:
IMPERIAL_DOC_MATERIALS_URL_PREFIX = app.config["URL_PREFIX"]
except KeyError:
raise "Please set the URL_PREFIX in your app's config.py"
def set_redirect_url(redirect_url: str):
global IMPERIAL_DOC_MATERIALS_REDIRECT_URL
IMPERIAL_DOC_MATERIALS_REDIRECT_URL = redirect_url
def using_materials(f):
"""
Decorator for a Flask route that provides access to the Materials client object
assuming the user is logged in.
"""
# TODO add a token decorator
@wraps(f)
def session_decorator(*args, **kws):
if not session.get(SESSION_KEY_NAME):
if IMPERIAL_DOC_MATERIALS_REDIRECT_URL:
return redirect(IMPERIAL_DOC_MATERIALS_URL_PREFIX + str(url_for(IMPERIAL_DOC_MATERIALS_REDIRECT_URL, next=request.url)))
else:
abort(401)
materials_client = None
try:
materials_client = Materials.from_dict(session[SESSION_KEY_NAME])
except:
if IMPERIAL_DOC_MATERIALS_REDIRECT_URL:
return redirect(IMPERIAL_DOC_MATERIALS_URL_PREFIX + str(url_for(IMPERIAL_DOC_MATERIALS_REDIRECT_URL, next=request.url)))
else:
abort(401)
return f(materials_client, *args, **kws)
return session_decorator
def materials_login(username: str, password: str) -> Optional[Materials]:
"""
Login into the Materials API with the given username and password.
"""
try:
materials_client = Materials.create_client(username, password)
# TODO check whether to use session or token?
session[SESSION_KEY_NAME] = materials_client.get_as_dict()
session.modified = True
return materials_client
except:
return None
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment