maeser.user_manager module#

User management module for authentication and authorization.

This module provides classes and utilities for managing users, including authentication methods, database operations, and request tracking.

class maeser.user_manager.BaseAuthenticator(*args, **kwargs)[source]#

Bases: ABC

Base class for authenticators.

abstract authenticate(*args, **kwargs) tuple | None[source]#

Authenticate a user.

Parameters:
  • *args – Positional arguments for authentication.

  • **kwargs – Keyword arguments for authentication.

Returns:

A tuple containing the user’s username, real name, and user group if authentication is successful; otherwise None.

Return type:

(tuple | None)

abstract fetch_user(ident: str) User | None[source]#

Fetch a user from the authenticator.

Parameters:

ident (str) – The identifier of the user to fetch.

Returns:

The fetched user object or None if not found.

ENSURE THAT YOU SET max_requests TO THE CORRECT VALUE FOR THE USER!

Return type:

(User | None)

abstract property style: LoginStyle#

The login style for the authenticator.

Type:

LoginStyle

class maeser.user_manager.GithubAuthenticator(client_id: str, client_secret: str, auth_callback_uri: str, timeout: int = 10, max_requests: int = 10)[source]#

Bases: BaseAuthenticator

Handles authentication with GitHub OAuth.

Parameters:
  • client_id (str) – The GitHub client ID.

  • client_secret (str) – The GitHub client secret.

  • auth_callback_uri (str) – The callback URI for GitHub authentication.

  • timeout (int) – The time before authentication fails. Defaults to 10.

  • max_requests (int) – The maximum number of requests to the authenticator. Defaults to 10.

authenticate(request_args: dict, oauth_state: str) tuple | None[source]#

Authenticate a user with GitHub OAuth.

requests_args should contain the following arguments:

  • code”: The authorization code.

  • state”: The OAuth state. This needs to be the same as oauth_state for authentication to pass.

The data returned after a successful authentication is as follows:

  • ident: The user ID (same as ident passed into the function).

  • display_name: The display name of the user, as determined by the LDAP authenticator.

  • user_group The group the user belongs to, as determined by the LDAP authenticator.

Parameters:
  • request_args (dict) – The request arguments containing the authorization code and state.

  • oauth_state (str) – The state value used to prevent CSRF attacks.

Returns:

A tuple containing the user’s username, real name, and user group if authentication is successful; otherwise None.

Return type:

(tuple | None)

fetch_user(ident: str) User | None[source]#

Fetch a user from the GitHub API.

Parameters:

ident (str) – The username of the user to fetch.

Returns:

The fetched user object or None if the user is not found.

Return type:

(User | None)

get_auth_info() Tuple[str, str][source]#

Get the GitHub authorization information.

Returns:

A tuple containing the OAuth state and provider URL.

Return type:

tuple

property style: LoginStyle#

The LoginStyle for GitHub (LoginStyle('github', 'maeser.github_authorize', direct_submit=True)).

Type:

LoginStyle

class maeser.user_manager.LDAPAuthenticator(name: str, ldap_server_urls: list, ldap_base_dn: str, attribute_name: str, search_filter: str, object_class: str, attributes: list, ca_cert_path: str = '/etc/ssl/certs', connection_timeout: int = 5)[source]#

Bases: BaseAuthenticator

Handles authentication with an LDAP server.

Parameters:
  • name (str) – A human-readable identifier for this authenticator instance.

  • ldap_server_urls (list) – List of LDAP server URLs to connect to (e.g., [”ldap://example.com”, “ldaps://secure.example.com”]).

  • ldap_base_dn (str) – The base Distinguished Name (DN) used as the search root in LDAP queries.

  • attribute_name (str) – The LDAP attribute used to match the username (e.g., “uid”, “cn”).

  • search_filter (str) – An LDAP search filter string, which may include placeholders for dynamic values (e.g., “(uid={username})”).

  • object_class (str) – The LDAP objectClass to filter entries (e.g., “inetOrgPerson”).

  • attributes (list) – List of LDAP attributes to retrieve from search results.

  • ca_cert_path (str, optional) – Path to the directory or file containing trusted Certificate Authority (CA) certificates for LDAPS connections. Defaults to ‘/etc/ssl/certs’.

  • connection_timeout (int, optional) – Timeout in seconds for establishing an LDAP connection. Defaults to 5.

authenticate(ident: str, password: str) tuple | None[source]#

Authenticate a user with LDAP authentication.

The data returned after a successful authentication is as follows:

  • ident: The user ID (same as ident passed into the function).

  • display_name: The display name of the user, as determined by the LDAP authenticator.

  • user_group The group the user belongs to, as determined by the LDAP authenticator.

Parameters:
  • ident (str) – The user ID.

  • password (str) – The user’s password.

Returns:

A tuple containing the user’s username, real name, and user group if authentication is successful; otherwise None.

Return type:

(tuple | None)

fetch_user(ident: str) User | None[source]#

Fetch user information from LDAP and return a User object. This method performs an anonymous bind and searches for the user. No authentication is preformed using this method.

Parameters:

ident (str) – The user’s identifier.

Returns:

The User object if found; None otherwise.

Return type:

(User | None)

property next_ldap_server: ldap3.Server | None#

The next available LDAP server, returned in a round-robin fashion.

property style#

The LoginStyle for an LDAP server (LoginStyle('envelope-fill', 'maeser.login', direct_submit=False)).

class maeser.user_manager.LoginStyle(icon: str, login_submit: str, direct_submit: bool = False)[source]#

Bases: object

Configures the style of the login form for an authenticator.

If needed, custom html for the authenticator form (i.e. a username and password input) can be assigned to the form_html property (as long as direct_submit is set to False). Only assign label and input elements to this property.

Parameters:
  • icon (str) – The icon for the login form.

  • login_submit (str) – The Flask route to assign to the form submission. Not a url, but a controller name for flask.url_for(). i.e. ‘maeser.github_authorize’ or ‘localauth’.

  • direct_submit (bool, optional) – Whether selecting the login option directly submits to the authenticator or selecting the login option should expose a form to fill out before submission. Defaults to False.

property form_html: str#

The html for the authenticator form. This is only used if direct_submit is set to False.

Only assign label and input elements to this property.

When a LoginStyle object is initialized, form_html is set to the following by default:

<label for=”username” class=”form-label”>Username</label> <input type=”text” id=”username” name=”username” class=”form-input” required> <label for=”password” class=”form-label”>Password</label> <input type=”password” id=”password” name=”password” class=”form-input” required>

Type:

str

class maeser.user_manager.User(ident: str, blacklisted: bool = False, admin: bool = False, realname: str = 'Student', usergroup: str = "b'guest'", authmethod: str = 'invalid', requests_left: int = 10, max_requests: int = 10, aka: list[str] = [])[source]#

Bases: object

Provides default implementations for the methods that Flask-Login expects user objects to have.

Parameters:
  • ident (str) – The user’s identifier.

  • blacklisted (bool, optional) – Whether the user is blacklisted. Defaults to False.

  • admin (bool, optional) – Whether the user is an admin. Defaults to False.

  • realname (str, optional) – The user’s real name. Defaults to ‘Student’.

  • usergroup (str, optional) – The user’s group. Defaults to ‘b’guest’’.

  • authmethod (str, optional) – The authentication method. Defaults to ‘invalid’.

  • requests_left (int, optional) – The number of requests left. Defaults to 10.

  • max_requests (int, optional) – The maximum number of requests. Defaults to 10.

  • aka (list[str], optional) – A list of alternate names. Defaults to an empty list.

property full_id_name: str#

The user’s full identifier name including authentication method, formatted as authenticator.user_id.

Type:

str

get_id() str[source]#

Return the user’s full identifier name including authentication method, formatted as authenticator.user_id.

Returns:

the user’s full ID.

Return type:

str

property is_anonymous: bool#

Always False, as anonymous users are not supported.

Type:

bool

property is_authenticated: bool#

True if the user is authenticated; False if otherwise.

Type:

bool

property json: dict[str, Any]#

The json representation of the user.

Type:

dict[str, Any]

property requests_remaining: int#

The number of requests remaining for the user.

class maeser.user_manager.UserManager(db_file_path: str, max_requests: int = 10, rate_limit_interval: int = 180)[source]#

Bases: object

Manages user operations including authentication, database interactions, and request tracking.

Parameters:
  • db_file_path (str) – The file path to the SQLite database.

  • max_requests (int, optional) – The maximum number of requests a user can have. Defaults to 10.

  • rate_limit_interval (int, optional) – The interval at which user message requests should be refreshed, in seconds. defaults to 180.

authenticate(auth_method: str, *args: Any, **kwargs: Any) User | None[source]#

Authenticates a user using the specified authentication method.

Parameters:
  • auth_method (str) – The authentication method to use.

  • *args – Positional arguments for the authentication method.

  • **kwargs – Keyword arguments for the authentication method.

Returns:

The authenticated user object, or None if authentication fails.

Return type:

(User | None)

Raises:

ValueError – If the provided auth_method is not registered to the user manager.

check_user_auth(auth_method: str) bool[source]#

Checks if a user authenticator is registered in the user manager.

Parameters:

auth_method (str) – The name of the authenticator.

Returns:

True if the authenticator is registered in the user manager; False otherwise.

Return type:

bool

clean_cache() int[source]#

Cleans the cache/user database by removing non-banned and non-admin users.

Returns:

The number of users removed from the cache/database.

Return type:

int

property db_connection: Connection#

The connection to the SQLite database.

Raises:

sqlite3.OperationalError – If the database cannot be opened.

Type:

sqlite3.Connection

decrease_requests(auth_method: str, user_id: str, dec_by: int = 1)[source]#

Decreases the number of requests remaining for a user.

Parameters:
  • auth_method (str) – The authentication method used.

  • user_id (str) – The identifier of the user.

  • dec_by (int, optional) – The amount to decrease the requests by. Defaults to 1.

Raises:

ValueError – If the provided auth_method is not registered to the user manager.

fetch_user(auth_method: str, ident: str) bool[source]#

Fetches a user from the authentication source and add them to the user database without modifying their admin or banned status.

Parameters:
  • auth_method (str) – The authentication method.

  • ident (str) – The user’s identifier.

Returns:

True if the user was successfully fetched and added to the database; False otherwise.

Return type:

bool

Raises:

ValueError – If the provided auth_method is not registered to the user manager.

get_requests_remaining(auth_method: str, user_id: str) int | None[source]#

Gets the number of requests remaining for a user.

Parameters:
  • auth_method (str) – The authentication method used.

  • user_id (str) – The identifier of the user.

Returns:

The number of requests remaining, or None if the user is not found.

Return type:

(int | None)

Raises:

ValueError – If the provided auth_method is not registered to the user manager.

get_user(auth_method: str, ident: str) User | None[source]#

Retrieve a user from the database.

Note: The authenticator name must be alphanumeric.

Parameters:
  • auth_method (str) – The authentication method used.

  • ident (str) – The unique identifier of the user.

Returns:

The user object, or None if not found.

Return type:

User

Raises:

ValueError – If the authenticator name is not alphanumeric.

increase_requests(auth_method: str, user_id: str, inc_by: int = 1)[source]#

Increases the number of requests remaining for a user.

Parameters:
  • auth_method (str) – The authentication method used.

  • user_id (str) – The identifier of the user.

  • inc_by (int, optional) – The amount to increase the requests by. Defaults to 1.

Raises:

ValueError – If the provided auth_method is not registered to the user manager.

list_cleanables() list[str][source]#

Lists non-banned and non-admin users in the cache/database.

Returns:

A list of user identifiers in the format “auth_method:user_id”.

Return type:

list[str]

list_users(auth_filter: str | None = None, admin_filter: str | None = None, banned_filter: str | None = None) list[User][source]#

Lists all users in the database, optionally filtered by authentication method, admin status, and banned status.

Parameters:
  • auth_filter (str | None, optional) – The authentication method to list users for. If None or ‘all’, lists users from all authentication methods.

  • admin_filter (str | None, optional) – Filter users by admin status. Can be ‘all’, ‘admin’, or ‘non-admin’. Defaults to None.

  • banned_filter (str | None, optional) – Filter users by banned status. Can be ‘all’, ‘banned’, or ‘non-banned’. Defaults to None.

Returns:

A list of user objects.

Return type:

list[User]

Raises:

ValueError – If the provided auth_method is invalid or if admin_filter or banned_filter have invalid values.

refresh_requests(inc_by: int = 1)[source]#

Refreshes the number of requests for all users by the given amount.

Parameters:

inc_by (int, optional) – The amount to increase the requests by. Defaults to 1.

register_authenticator(name: str, authenticator: BaseAuthenticator)[source]#

Registers a new authentication method.

Parameters:
  • name (str) – The shorthand name of the authentication method. Must only contain letters.

  • authenticator (BaseAuthenticator) – The authenticator object.

Raises:

ValueError – If the provided name is invalid or the authenticator is already registered.

remove_user_from_cache(auth_method: str, ident: str, force_remove: bool = False) bool[source]#

Removes a user from the cache.

Parameters:
  • auth_method (str) – The authentication method used.

  • ident (str) – The identifier of the user.

Returns:

True if the user was removed, False otherwise.

Return type:

bool

Raises:

ValueError – If the provided auth_method is not registered to the user manager and force_remove is set to False.

update_admin_status(auth_method: str, ident: str, is_admin: bool)[source]#

Updates the admin status of a user.

Parameters:
  • auth_method (str) – The authentication method used.

  • ident (str) – The identifier of the user.

  • is_admin (bool) – Whether the user should be an admin or not.

Raises:

ValueError – If the provided auth_method is not registered to the user manager.

update_banned_status(auth_method: str, ident: str, is_banned: bool)[source]#

Updates the banned status of a user.

Parameters:
  • auth_method (str) – The authentication method used.

  • ident (str) – The identifier of the user.

  • is_banned (bool) – Whether the user should be banned or not.

Raises:

ValueError – If the provided auth_method is not registered to the user manager.