diff options
| author | John Nduli | 2024-10-18 15:06:35 +0300 |
|---|---|---|
| committer | Frederick Muriuki Muriithi | 2024-10-18 09:28:40 -0500 |
| commit | 27531c0a1350097ca36a555b8546bc282948de04 (patch) | |
| tree | b209f28f6da28fc0384ddfe1145cfe413f2bf8e3 | |
| parent | 1aeb61f50567e2400c3cc1a18eeef1e59bdc68ac (diff) | |
| download | genenetwork3-27531c0a1350097ca36a555b8546bc282948de04.tar.gz | |
refactor: move definition of auth errs and remove auth cli utils
| -rw-r--r-- | example-run-dev.sh | 8 | ||||
| -rw-r--r-- | gn3/api/metadata.py | 3 | ||||
| -rw-r--r-- | gn3/app.py | 2 | ||||
| -rw-r--r-- | gn3/auth/__init__.py | 3 | ||||
| -rw-r--r-- | gn3/auth/authorisation/__init__.py | 2 | ||||
| -rw-r--r-- | gn3/auth/authorisation/errors.py | 42 | ||||
| -rw-r--r-- | gn3/case_attributes.py | 2 | ||||
| -rw-r--r-- | gn3/errors.py | 4 | ||||
| -rw-r--r-- | gn3/settings.py | 2 | ||||
| -rw-r--r-- | main.py | 98 |
10 files changed, 6 insertions, 160 deletions
diff --git a/example-run-dev.sh b/example-run-dev.sh index a0c5d61..959411f 100644 --- a/example-run-dev.sh +++ b/example-run-dev.sh @@ -3,7 +3,6 @@ ## Copy to run-dev.sh and update the appropriate environment variables. export SQL_URI="${SQL_URI:+${SQL_URI}}" -export AUTH_DB="${AUTH_DB:+${AUTH_DB}}" export FLASK_DEBUG=1 export FLASK_APP="main.py" export AUTHLIB_INSECURE_TRANSPORT=true @@ -20,12 +19,5 @@ then exit 1; fi -if [ -z "${AUTH_DB}" ] -then - echo "ERROR: You need to specify the 'AUTH_DB' environment variable"; - exit 1; -fi - - # flask run --port=8080 flask ${CMD_ARGS[@]} diff --git a/gn3/api/metadata.py b/gn3/api/metadata.py index 6329c69..59c25d3 100644 --- a/gn3/api/metadata.py +++ b/gn3/api/metadata.py @@ -9,7 +9,8 @@ from flask import Blueprint from flask import request from flask import current_app -from gn3.auth.authorisation.errors import AuthorisationError + +from gn3.oauth2.errors import AuthorisationError from gn3.db.datasets import (retrieve_metadata, save_metadata, get_history) diff --git a/gn3/app.py b/gn3/app.py index c8f0c5a..e9a2bbe 100644 --- a/gn3/app.py +++ b/gn3/app.py @@ -26,7 +26,6 @@ from gn3.api.search import search from gn3.api.metadata import metadata from gn3.api.sampledata import sampledata from gn3.api.llm import gnqa -from gn3.auth import oauth2 from gn3.case_attributes import caseattr @@ -76,7 +75,6 @@ def create_app(config: Union[Dict, str, None] = None) -> Flask: app.register_blueprint(search, url_prefix="/api/search") app.register_blueprint(metadata, url_prefix="/api/metadata") app.register_blueprint(sampledata, url_prefix="/api/sampledata") - app.register_blueprint(oauth2, url_prefix="/api/oauth2") app.register_blueprint(caseattr, url_prefix="/api/case-attribute") app.register_blueprint(gnqa, url_prefix="/api/llm") diff --git a/gn3/auth/__init__.py b/gn3/auth/__init__.py index cd65e9b..d9caec9 100644 --- a/gn3/auth/__init__.py +++ b/gn3/auth/__init__.py @@ -1,4 +1 @@ """Top-Level `Auth` module""" -from . import authorisation - -from .views import oauth2 diff --git a/gn3/auth/authorisation/__init__.py b/gn3/auth/authorisation/__init__.py deleted file mode 100644 index abd2747..0000000 --- a/gn3/auth/authorisation/__init__.py +++ /dev/null @@ -1,2 +0,0 @@ -"""The authorisation module.""" -from .checks import authorised_p diff --git a/gn3/auth/authorisation/errors.py b/gn3/auth/authorisation/errors.py deleted file mode 100644 index 3bc7a04..0000000 --- a/gn3/auth/authorisation/errors.py +++ /dev/null @@ -1,42 +0,0 @@ -"""Authorisation exceptions""" - -class AuthorisationError(Exception): - """ - Top-level exception for the `gn3.auth.authorisation` package. - - All exceptions in this package should inherit from this class. - """ - error_code: int = 400 - -class ForbiddenAccess(AuthorisationError): - """Raised for forbidden access.""" - error_code: int = 403 - -class UserRegistrationError(AuthorisationError): - """Raised whenever a user registration fails""" - -class NotFoundError(AuthorisationError): - """Raised whenever we try fetching (a/an) object(s) that do(es) not exist.""" - error_code: int = 404 - -class InvalidData(AuthorisationError): - """ - Exception if user requests invalid data - """ - error_code: int = 400 - -class InconsistencyError(AuthorisationError): - """ - Exception raised due to data inconsistencies - """ - error_code: int = 500 - -class PasswordError(AuthorisationError): - """ - Raise in case of an error with passwords. - """ - -class UsernameError(AuthorisationError): - """ - Raise in case of an error with a user's name. - """ diff --git a/gn3/case_attributes.py b/gn3/case_attributes.py index efc82e9..9baff1e 100644 --- a/gn3/case_attributes.py +++ b/gn3/case_attributes.py @@ -27,7 +27,7 @@ from gn3.commands import run_cmd from gn3.db_utils import Connection, database_connection from gn3.oauth2.authorisation import require_token -from gn3.auth.authorisation.errors import AuthorisationError +from gn3.oauth2.errors import AuthorisationError caseattr = Blueprint("case-attribute", __name__) diff --git a/gn3/errors.py b/gn3/errors.py index cd795e8..46483db 100644 --- a/gn3/errors.py +++ b/gn3/errors.py @@ -16,7 +16,7 @@ from authlib.oauth2.rfc6749.errors import OAuth2Error from flask import Flask, jsonify, Response, current_app from gn3.oauth2 import errors as oautherrors -from gn3.auth.authorisation.errors import AuthorisationError +from gn3.oauth2.errors import AuthorisationError from gn3.llms.errors import LLMError def add_trace(exc: Exception, jsonmsg: dict) -> dict: @@ -60,7 +60,7 @@ def handle_authorisation_error(exc: AuthorisationError): return jsonify(add_trace(exc, { "error": type(exc).__name__, "error_description": " :: ".join(exc.args) - })), exc.error_code + })), 500 def handle_oauth2_errors(exc: OAuth2Error): diff --git a/gn3/settings.py b/gn3/settings.py index 04aa129..439d88c 100644 --- a/gn3/settings.py +++ b/gn3/settings.py @@ -85,8 +85,6 @@ MULTIPROCESSOR_PROCS = 6 # Number of processes to spawn AUTH_SERVER_URL = "https://auth.genenetwork.org" AUTH_MIGRATIONS = "migrations/auth" -AUTH_DB = os.environ.get( - "AUTH_DB", f"{os.environ.get('HOME')}/genenetwork/gn3_files/db/auth.db") OAUTH2_SCOPE = ( "profile", "group", "role", "resource", "user", "masquerade", "introspect") diff --git a/main.py b/main.py index 879b344..ccbd14f 100644 --- a/main.py +++ b/main.py @@ -1,105 +1,9 @@ """Main entry point for project""" -import sys -import uuid -import json -from math import ceil -from datetime import datetime - -import click from gn3.app import create_app -from gn3.auth.authorisation.users import hash_password - -from gn3.auth import db app = create_app() -##### BEGIN: CLI Commands ##### - -def __init_dev_users__(): - """Initialise dev users. Get's used in more than one place""" - dev_users_query = "INSERT INTO users VALUES (:user_id, :email, :name)" - dev_users_passwd = "INSERT INTO user_credentials VALUES (:user_id, :hash)" - dev_users = ({ - "user_id": "0ad1917c-57da-46dc-b79e-c81c91e5b928", - "email": "test@development.user", - "name": "Test Development User", - "password": "testpasswd"},) - - with db.connection(app.config["AUTH_DB"]) as conn, db.cursor(conn) as cursor: - cursor.executemany(dev_users_query, dev_users) - cursor.executemany(dev_users_passwd, ( - {**usr, "hash": hash_password(usr["password"])} - for usr in dev_users)) - -@app.cli.command() -def init_dev_users(): - """ - Initialise development users for OAuth2 sessions. - - **NOTE**: You really should not run this in production/staging - """ - __init_dev_users__() - -@app.cli.command() -def init_dev_clients(): - """ - Initialise a development client for OAuth2 sessions. - - **NOTE**: You really should not run this in production/staging - """ - __init_dev_users__() - dev_clients_query = ( - "INSERT INTO oauth2_clients VALUES (" - ":client_id, :client_secret, :client_id_issued_at, " - ":client_secret_expires_at, :client_metadata, :user_id" - ")") - dev_clients = ({ - "client_id": "0bbfca82-d73f-4bd4-a140-5ae7abb4a64d", - "client_secret": "yadabadaboo", - "client_id_issued_at": ceil(datetime.now().timestamp()), - "client_secret_expires_at": 0, - "client_metadata": json.dumps({ - "client_name": "GN2 Dev Server", - "token_endpoint_auth_method": [ - "client_secret_post", "client_secret_basic"], - "client_type": "confidential", - "grant_types": ["password", "authorization_code", "refresh_token"], - "default_redirect_uri": "http://localhost:5033/oauth2/code", - "redirect_uris": ["http://localhost:5033/oauth2/code", - "http://localhost:5033/oauth2/token"], - "response_type": ["code", "token"], - "scope": ["profile", "group", "role", "resource", "register-client", - "user", "masquerade", "migrate-data", "introspect"] - }), - "user_id": "0ad1917c-57da-46dc-b79e-c81c91e5b928"},) - - with db.connection(app.config["AUTH_DB"]) as conn, db.cursor(conn) as cursor: - cursor.executemany(dev_clients_query, dev_clients) - - -@app.cli.command() -@click.argument("user_id", type=click.UUID) -def assign_system_admin(user_id: uuid.UUID): - """Assign user with ID `user_id` administrator role.""" - dburi = app.config["AUTH_DB"] - with db.connection(dburi) as conn, db.cursor(conn) as cursor: - cursor.execute("SELECT * FROM users WHERE user_id=?", - (str(user_id),)) - row = cursor.fetchone() - if row: - cursor.execute( - "SELECT * FROM roles WHERE role_name='system-administrator'") - admin_role = cursor.fetchone() - cursor.execute("INSERT INTO user_roles VALUES (?,?)", - (str(user_id), admin_role["role_id"])) - return 0 - print(f"ERROR: Could not find user with ID {user_id}", - file=sys.stderr) - sys.exit(1) - -##### END: CLI Commands ##### - -if __name__ == '__main__': +if __name__ == "__main__": print("Starting app...") app.run() |
