|
| 1 | +import bcrypt |
| 2 | +import secrets |
| 3 | +import requests |
| 4 | +import random |
| 5 | +import base62 |
| 6 | + |
| 7 | +from pydantic import ValidationError |
| 8 | + |
| 9 | +from urllib.parse import urlencode |
| 10 | + |
| 11 | +from flask import Blueprint, request, abort, session, current_app, redirect |
| 12 | +from http import HTTPStatus |
| 13 | + |
| 14 | +from app.schemas.login_schema import LoginSchema, FenixOAuthSchema, FenixStudentSchema |
| 15 | +from app.schemas.member_schema import MemberSchema |
| 16 | + |
| 17 | +from app.repositories.member_repository import MemberRepository |
| 18 | + |
| 19 | + |
| 20 | +def create_auth_bp(member_repo: MemberRepository): |
| 21 | + bp = Blueprint("auth", __name__) |
| 22 | + |
| 23 | + @bp.route("/login", methods=["POST"]) |
| 24 | + def login(): |
| 25 | + login_data = LoginSchema(**request.json()) |
| 26 | + |
| 27 | + if (member := member_repo.get_member_by_username(login_data.username)) is None: |
| 28 | + abort(HTTPStatus.UNAUTHORIZED) |
| 29 | + |
| 30 | + if member.password is None: # fenix authenticated users must login through Fenix |
| 31 | + abort(HTTPStatus.UNAUTHORIZED) |
| 32 | + |
| 33 | + if not bcrypt.checkpw(login_data.password.encode("utf-8"), member.password.encode("utf-8")): |
| 34 | + abort(HTTPStatus.UNAUTHORIZED) |
| 35 | + |
| 36 | + session.clear() |
| 37 | + |
| 38 | + session["username"] = member.username |
| 39 | + return {"message": f"Welcome {member.username}!"} |
| 40 | + |
| 41 | + @bp.route("/logout", methods=["GET"]) |
| 42 | + def logout(): |
| 43 | + session.clear() |
| 44 | + return {"message": "Logged out sucessfully"} |
| 45 | + |
| 46 | + @bp.route("/fenix-auth") |
| 47 | + def fenix_auth(): |
| 48 | + if ( |
| 49 | + current_app.config.get("CLIENT_ID", "") == "" |
| 50 | + or current_app.config.get("CLIENT_SECRET", "") == "" |
| 51 | + or current_app.config.get("FENIX_REDIRECT_URL") == "" |
| 52 | + ): |
| 53 | + abort(HTTPStatus.NOT_IMPLEMENTED) |
| 54 | + |
| 55 | + state = secrets.token_hex(16) |
| 56 | + |
| 57 | + session.clear() |
| 58 | + session["state"] = state |
| 59 | + params = { |
| 60 | + "client_id": current_app.config.get("CLIENT_ID"), |
| 61 | + "redirect_uri": current_app.config.get("FENIX_REDIRECT_URL"), |
| 62 | + "state": state, |
| 63 | + } |
| 64 | + return redirect( |
| 65 | + "https://fenix.tecnico.ulisboa.pt/oauth/userdialog?" + urlencode(params) |
| 66 | + ) |
| 67 | + |
| 68 | + @bp.route("/fenix-auth-callback") |
| 69 | + def fenix_auth_callback(): |
| 70 | + try: |
| 71 | + oauth_data = FenixOAuthSchema(**request.args) |
| 72 | + except ValidationError: |
| 73 | + # this fails on invalid state parameters |
| 74 | + abort(HTTPStatus.UNAUTHORIZED) |
| 75 | + |
| 76 | + if oauth_data.state is None or oauth_data.state != session.get("state", ""): |
| 77 | + abort(HTTPStatus.UNAUTHORIZED) |
| 78 | + |
| 79 | + if oauth_data.error is not None: |
| 80 | + abort(HTTPStatus.BAD_GATEWAY, {"error": oauth_data.error}) |
| 81 | + |
| 82 | + params = { |
| 83 | + "client_id": current_app.config.get("CLIENT_ID"), |
| 84 | + "client_secret": current_app.config.get("CLIENT_SECRET"), |
| 85 | + "redirect_uri": current_app.config.get("FENIX_REDIRECT_URL"), |
| 86 | + "code": oauth_data.code, |
| 87 | + "grant_type": "authorization_code", |
| 88 | + } |
| 89 | + |
| 90 | + if ( |
| 91 | + access_token := __fetch_access_token( |
| 92 | + "https://fenix.tecnico.ulisboa.pt/oauth/access_token?" |
| 93 | + + urlencode(params) |
| 94 | + ) |
| 95 | + ) is None: |
| 96 | + abort(HTTPStatus.BAD_GATEWAY) |
| 97 | + |
| 98 | + if (user_data := __get_user_info(access_token)) is None: |
| 99 | + abort(HTTPStatus.BAD_GATEWAY) |
| 100 | + |
| 101 | + session.clear() |
| 102 | + if (member := member_repo.get_member_by_ist_id(user_data.username)) is None: |
| 103 | + # attempt to create a user with a random username |
| 104 | + while True: |
| 105 | + while True: |
| 106 | + # generate a random username |
| 107 | + username = base62.encodebytes(random.randbytes(8)).lower() |
| 108 | + if member_repo.get_member_by_username(username) is None: |
| 109 | + break |
| 110 | + |
| 111 | + try: |
| 112 | + pass |
| 113 | + # member = member_service.create_user(Member(MemberSchema(**user_data))) |
| 114 | + except Exception as e: |
| 115 | + print(e) |
| 116 | + # TODO replace with conflict exception |
| 117 | + continue |
| 118 | + break |
| 119 | + |
| 120 | + session["username"] = member.username |
| 121 | + return {"message": "Registered"} |
| 122 | + |
| 123 | + return bp |
| 124 | + |
| 125 | + |
| 126 | +def __fetch_access_token(url: str) -> str | None: |
| 127 | + r = requests.post(url) |
| 128 | + try: |
| 129 | + r.raise_for_status() |
| 130 | + except requests.HTTPError as e: |
| 131 | + current_app.logger.info(f"Failed requesting access token: {e}") |
| 132 | + return None |
| 133 | + |
| 134 | + if r.status_code != 200: |
| 135 | + current_app.logger.info( |
| 136 | + f"Failed requesting access token with non 200 response. Status code: {r.status_code}\nMessage: {r.connection}" |
| 137 | + ) |
| 138 | + return None |
| 139 | + |
| 140 | + access_token: str |
| 141 | + try: |
| 142 | + access_token = r.json()["access_token"] |
| 143 | + except Exception as e: |
| 144 | + current_app.logger.info(f"Failed requesting access token: {e}") |
| 145 | + return None |
| 146 | + |
| 147 | + return access_token |
| 148 | + |
| 149 | + |
| 150 | +def __get_user_info( |
| 151 | + access_token: str, |
| 152 | +) -> FenixStudentSchema | None: |
| 153 | + r = requests.get( |
| 154 | + "https://fenix.tecnico.ulisboa.pt/api/fenix/v1/person?" |
| 155 | + + urlencode({"access_token": access_token}) |
| 156 | + ) |
| 157 | + try: |
| 158 | + r.raise_for_status() |
| 159 | + except requests.HTTPError as e: |
| 160 | + current_app.logger.info(f"Failed requesting user info: {e}") |
| 161 | + return None |
| 162 | + |
| 163 | + if r.status_code != 200: |
| 164 | + current_app.logger.info( |
| 165 | + f"Failed requesting user info with non 200 status code. Status Code: {r.status_code}\nMessage: {r.content}" |
| 166 | + ) |
| 167 | + return None |
| 168 | + |
| 169 | + try: |
| 170 | + user_data = FenixStudentSchema(**r.json()) |
| 171 | + except Exception as e: |
| 172 | + current_app.logger.info(f"Failed requesting user info: {e}") |
| 173 | + return None |
| 174 | + |
| 175 | + return user_data |
0 commit comments