uf.auth#

Authentication and authorization for uf.

Provides authentication backends, session management, and role-based access control for uf applications.

Functions

get_global_api_key_manager()

Get the global API key manager.

get_global_auth_backend()

Get the global authentication backend.

get_global_session_manager()

Get the global session manager.

require_auth(backend[, roles, permissions])

Decorator to require authentication for a function.

set_global_api_key_manager(manager)

Set the global API key manager.

set_global_auth_backend(backend)

Set the global authentication backend.

set_global_session_manager(manager)

Set the global session manager.

Classes

ApiKey(key, name[, permissions, expires_at])

API key for programmatic access.

ApiKeyManager([key_prefix])

Manage API keys for programmatic access.

AuthBackend()

Base authentication backend.

DictAuthBackend()

Simple in-memory dictionary-based authentication.

PasswordHasher()

Password hashing utilities.

SessionManager(secret_key[, session_timeout])

Manage user sessions.

User(username, password_hash[, roles, ...])

User account information.

class uf.auth.ApiKey(key, name, permissions=None, expires_at=None)[source]#

Bases: object

API key for programmatic access.

key#

The API key string

name#

Descriptive name

permissions#

List of allowed permissions

created_at#

When key was created

expires_at#

Optional expiration

is_active#

Whether key is active

has_permission(permission)[source]#

Check if key has permission.

Return type:

bool

is_expired()[source]#

Check if key is expired.

Return type:

bool

class uf.auth.ApiKeyManager(key_prefix='sk_')[source]#

Bases: object

Manage API keys for programmatic access.

Example

>>> api_keys = ApiKeyManager()
>>> key = api_keys.create_key('mobile_app', permissions=['read'])
>>> print(f"Your API key: {key.key}")
>>> # Later, validate
>>> if api_keys.validate_key(key.key, 'read'):
...     # Allow access
create_key(name, permissions=None, expires_in_days=None)[source]#

Create a new API key.

Parameters:
  • name (str) – Descriptive name for the key

  • permissions (Optional[list[str]]) – List of allowed permissions

  • expires_in_days (Optional[int]) – Optional expiration in days

Return type:

ApiKey

Returns:

Created ApiKey object

list_keys()[source]#

List all API keys.

Return type:

list[ApiKey]

Returns:

List of ApiKey objects

revoke_key(key)[source]#

Revoke an API key.

Parameters:

key (str) – API key string

Return type:

bool

Returns:

True if revoked

validate_key(key, permission=None)[source]#

Validate an API key.

Parameters:
  • key (str) – API key string

  • permission (Optional[str]) – Optional permission to check

Return type:

bool

Returns:

True if valid

class uf.auth.AuthBackend[source]#

Bases: object

Base authentication backend.

Subclass this to create custom authentication backends.

authenticate(username, password)[source]#

Authenticate a user.

Parameters:
  • username (str) – Username

  • password (str) – Password

Return type:

Optional[User]

Returns:

User object if authenticated, None otherwise

create_user(username, password, roles=None, permissions=None, **metadata)[source]#

Create a new user.

Parameters:
  • username (str) – Username

  • password (str) – Plain text password

  • roles (Optional[list[str]]) – List of roles

  • permissions (Optional[list[str]]) – List of permissions

  • **metadata – Additional user metadata

Return type:

User

Returns:

Created User object

delete_user(username)[source]#

Delete a user.

Parameters:

username (str) – Username

Return type:

bool

Returns:

True if deleted successfully

get_user(username)[source]#

Get a user by username.

Parameters:

username (str) – Username

Return type:

Optional[User]

Returns:

User object or None

update_user(username, **updates)[source]#

Update user information.

Parameters:
  • username (str) – Username

  • **updates – Fields to update

Return type:

bool

Returns:

True if updated successfully

class uf.auth.DictAuthBackend[source]#

Bases: AuthBackend

Simple in-memory dictionary-based authentication.

Suitable for development and simple applications.

Example

>>> backend = DictAuthBackend()
>>> backend.create_user('admin', 'secret', roles=['admin'])
>>> user = backend.authenticate('admin', 'secret')
authenticate(username, password)[source]#

Authenticate a user.

Return type:

Optional[User]

create_user(username, password, roles=None, permissions=None, **metadata)[source]#

Create a new user.

Return type:

User

delete_user(username)[source]#

Delete a user.

Return type:

bool

classmethod from_dict(users_data)[source]#

Create backend from dictionary.

Parameters:

users_data (dict) – Dictionary mapping usernames to user info

Return type:

DictAuthBackend

Example

>>> backend = DictAuthBackend.from_dict({
...     'admin': {'password': 'secret', 'roles': ['admin']},
...     'user': {'password': 'pass', 'roles': ['user']},
... })
get_user(username)[source]#

Get a user by username.

Return type:

Optional[User]

update_user(username, **updates)[source]#

Update user information.

Return type:

bool

class uf.auth.PasswordHasher[source]#

Bases: object

Password hashing utilities.

Uses PBKDF2-HMAC-SHA256 for secure password hashing.

static hash_password(password, salt=None)[source]#

Hash a password.

Parameters:
  • password (str) – Plain text password

  • salt (Optional[str]) – Optional salt (generated if not provided)

Returns:

salt$hash

Return type:

str

static verify_password(password, password_hash)[source]#

Verify a password against its hash.

Parameters:
  • password (str) – Plain text password

  • password_hash (str) – Hash string from hash_password()

Return type:

bool

Returns:

True if password matches

class uf.auth.SessionManager(secret_key, session_timeout=3600)[source]#

Bases: object

Manage user sessions.

Example

>>> sessions = SessionManager(secret_key='my-secret')
>>> session_id = sessions.create_session('admin')
>>> user = sessions.get_session(session_id)
cleanup_expired()[source]#

Remove expired sessions.

Return type:

int

Returns:

Number of sessions removed

create_session(username, data=None)[source]#

Create a new session.

Parameters:
  • username (str) – Username for session

  • data (Optional[dict]) – Optional session data

Return type:

str

Returns:

Session ID

delete_session(session_id)[source]#

Delete a session.

Parameters:

session_id (str) – Session ID

Return type:

bool

Returns:

True if deleted

get_session(session_id)[source]#

Get session data.

Parameters:

session_id (str) – Session ID

Return type:

Optional[dict]

Returns:

Session data or None if expired/invalid

class uf.auth.User(username, password_hash, roles=<factory>, permissions=<factory>, metadata=<factory>, created_at=<factory>, is_active=True)[source]#

Bases: object

User account information.

username#

Unique username

password_hash#

Hashed password

roles#

List of role names

permissions#

List of permission strings

metadata#

Additional user metadata

created_at#

When user was created

is_active#

Whether account is active

has_all_roles(roles)[source]#

Check if user has all of the given roles.

Return type:

bool

has_any_role(roles)[source]#

Check if user has any of the given roles.

Return type:

bool

has_permission(permission)[source]#

Check if user has a permission.

Return type:

bool

has_role(role)[source]#

Check if user has a role.

Return type:

bool

uf.auth.get_global_api_key_manager()[source]#

Get the global API key manager.

Return type:

Optional[ApiKeyManager]

uf.auth.get_global_auth_backend()[source]#

Get the global authentication backend.

Return type:

Optional[AuthBackend]

uf.auth.get_global_session_manager()[source]#

Get the global session manager.

Return type:

Optional[SessionManager]

uf.auth.require_auth(backend, roles=None, permissions=None)[source]#

Decorator to require authentication for a function.

Parameters:
Returns:

Decorator function

Example

>>> backend = DictAuthBackend.from_dict({
...     'admin': {'password': 'secret', 'roles': ['admin']}
... })
>>> @require_auth(backend, roles=['admin'])
... def delete_all():
...     pass
uf.auth.set_global_api_key_manager(manager)[source]#

Set the global API key manager.

Return type:

None

uf.auth.set_global_auth_backend(backend)[source]#

Set the global authentication backend.

Return type:

None

uf.auth.set_global_session_manager(manager)[source]#

Set the global session manager.

Return type:

None