Models

DRF knox authtoken model and manager.

smarter.lib.drf.models.LAST_USED_RESOLUTION = datetime.timedelta(seconds=60)

How precisely an api key’s last_used_at is kept.

Every authenticated request uses its key, so last_used_at is written at most once per this interval per key, not on every request.

class smarter.lib.drf.models.SmarterAuthToken(*args, **kwargs)[source]

Bases: AuthToken, MetaDataWithOwnershipModel

Represents a Smarter API Key used for authenticating and authorizing access to the Smarter platform.

This model extends Knox’s AuthToken and includes additional metadata and management features for API keys, such as naming, description, activation status, and usage tracking.

Fields:

  • key_id: The API key’s unique, public identifier.

  • name: The API key’s human-readable name, in snake_case.

  • description: An optional description of the API key’s purpose.

  • last_used_at: When the API key was last used, to within LAST_USED_RESOLUTION.

  • is_active: Whether the API key can be used for authentication.

  • tags: A list of tag names.

Usage Example:

# Creating an API key for a staff user
user = User.objects.get(username="admin")
token, key = SmarterAuthToken.objects.create(
    user=user,
    name="Production Key",
    description="Key for production API access"
)

# Activating or deactivating the key
token.activate()
token.deactivate()

# Toggling active status
token.toggle_active()

# Tracking usage
token.accessed()

Note

  • API keys can only be created for an account’s administrators: a superuser, a staff user, or a user whose profile in the key’s account has is_account_admin. Attempting to create a key for anyone else will raise a SmarterBusinessRuleViolation.

  • The identifier property returns a masked version of the key digest for display purposes.

  • Names are stored in snake_case, as every SAM manifest name is, so that get and describe report the same name. save() converts any other name.

Warning

  • Ensure that API keys are managed securely. Deactivated keys cannot be used for authentication.

Related Models:

  • User: The owner of the API key.

  • MetaDataModel: Provides created/modified timestamps and SAM metadata.

Parameters:
  • digest (Unknown) – Primary key: Digest

  • token_key (Unknown) – Token key

  • created (Unknown) – Created

  • expiry (Unknown) – Expiry

  • created_at (Unknown) – Created at

  • updated_at (Unknown) – Updated at

  • name (Unknown) – Name. Name in camelCase, e.g., ‘apiKey’, no special characters.

  • description (Unknown) – Description. A brief description of this resource. Be verbose, but not too verbose.

  • version (Unknown) – Version. Semantic version in the format MAJOR.MINOR.PATCH, e.g., ‘1.0.0’.

  • key_id (Unknown) – Key id

  • last_used_at (Unknown) – Last used at

  • is_active (Unknown) – Is active

  • tags (Unknown) – Tags

Relationship fields:

Parameters:
  • user (Unknown) – User (related name: auth_token_set)

  • authtoken_ptr (Unknown) – Primary key: Authtoken ptr (related name: smarterauthtoken)

  • user_profile (Unknown) – User profile (related name: smarterauthtoken)

Reverse relationships:

Parameters:

llmclientapikey (Unknown) – All LLMClient API Keys of this API Key (related name of api_key)

exception DoesNotExist

Bases: DoesNotExist

exception MultipleObjectsReturned

Bases: MultipleObjectsReturned

exception NotUpdated

Bases: NotUpdated

accessed()[source]

Update the last used time, and save, if it is older than LAST_USED_RESOLUTION.

Return type:

None

activate()[source]

Activate the API key, and save it.

authtoken_ptr

OneToOneField to AuthToken

Primary key: Authtoken ptr (related name: smarterauthtoken)

Type:

Type

authtoken_ptr_id

Internal field, use authtoken_ptr instead.

clone(new_name=None, new_version=None, user_profile=None)[source]

Create a new API key with this key’s metadata.

A clone is a new key: the manager creates its own token, digest and key_id, which MetaDataWithOwnershipModel.clone() would otherwise copy from this key.

Parameters:
  • new_name (str | None) – The name of the new key. Defaults to this key’s name, suffixed with “_clone”.

  • new_version (str | None) – The version of the new key. Defaults to this key’s version.

  • user_profile (UserProfile | None) – The owner of the new key. Defaults to this key’s owner.

Return type:

SmarterAuthToken

Returns:

The new key.

created_at

DateTimeField

Created at

Timestamp indicating when the model instance was created.

This field is automatically set to the current date and time when the instance is first created. It is indexed in the database for efficient querying.

Type:

Type

deactivate()[source]

Deactivate the API key, and save it.

description

TextField

Description. A brief description of this resource. Be verbose, but not too verbose.

Type:

Type

classmethod get_cached_objects(invalidate=False, user_profile=None, taggit=True, *, user=None, name=None, **kwargs)[source]

Return the API keys of a user profile’s user, optionally only those with a name, from the cache.

The results are cached by cached_auth_tokens(), and invalidated whenever an API key is saved or deleted (see smarter.lib.drf.receivers).

Parameters:
  • invalidate (bool | None) – If True, drop the cached result for this user profile and name first.

  • user_profile (UserProfile | None) – The user profile whose user’s API keys are returned.

  • taggit (bool) – Accepted for the base class’s signature, and ignored.

  • user (User | None) – The user whose API keys are returned, used if user_profile is not given.

  • name (str | None) – If given, only the API keys with this name are returned.

  • kwargs – Accepted for compatibility with the base class, and ignored.

Return type:

QuerySet[SmarterAuthToken]

Returns:

A queryset of the matching API keys, or every API key if neither user_profile nor user is given.

classmethod get_object_by_locator(locator)[source]

Return the SmarterAuthToken that a locator from record_locator identifies.

Parameters:

locator (str) – The record locator.

Return type:

SmarterAuthToken | None

Returns:

The API key, or None if the locator is malformed or no key has its key_id.

property hashed_id: str

Return the token’s public identifier.

See id.

property id: str

Return the token’s public identifier, its key_id, as a string.

A knox AuthToken has no integer id: its primary key is its digest. The api, the urls and the web console identify a token by its key_id instead.

property identifier: str

Return the token’s digest, masked for logging.

is_active

BooleanField

Is active

Type:

Type

key_id

UUIDField

Key id

Type:

Type

last_used_at

DateTimeField

Last used at

Type:

Type

last_used_is_stale(now)[source]

Return whether last_used_at is older than LAST_USED_RESOLUTION.

Parameters:

now (datetime) – The current, timezone-aware time.

Return type:

bool

Returns:

True if the key was never used, or was last used longer ago than the resolution.

llmclientapikey_set

Reverse ForeignKey from LLMClientAPIKey

All LLMClient API Keys of this API Key (related name of api_key)

Type:

Type

property manifest_url: str | None

Return the URL of the token’s manifest detail page, which identifies the token by its key_id.

Example:

self.manifest_url  # '/authtoken/d55cfbe5-89ec-4c11-90b9-3e9ec4bbbd85/'
name

CharField

Name. Name in camelCase, e.g., ‘apiKey’, no special characters.

Type:

Type

objects: MetaDataWithOwnershipModelManager = <smarter.lib.drf.models.SmarterAuthTokenManager object>
property record_locator: str

Return the record locator, which is derived from key_id.

The primary key of a knox AuthToken is a digest string, not an integer id, so the TimestampedModel hashed_id-based record locator cannot be used.

Returns:

The locator, e.g. smarterauthtoken-d55cfbe5-89ec-4c11-90b9-3e9ec4bbbd85.

save(*args, **kwargs)[source]

Save the API key, setting created if unset and converting name to snake_case.

Parameters:
  • args – Passed to Django’s save().

  • kwargs – Passed to Django’s save().

Raises:

SmarterBusinessRuleViolation – If the key’s owner doesn’t administer their account.

tags

JSONField

Tags

Type:

Type

property tags_list: list[str]

Return the tag names.

tags is a JSONField list here, not a taggit manager.

Returns:

The tag names, or an empty list if tags is not a list.

toggle_active()[source]

Toggle the API key’s active status, and save it.

updated_at

DateTimeField

Updated at

Timestamp indicating when the model instance was last updated.

This field is automatically updated to the current date and time whenever the instance is saved. It is indexed in the database for efficient querying.

Type:

Type

user_profile

ForeignKey to UserProfile

User profile (related name: smarterauthtoken)

Type:

Type

user_profile_id

Internal field, use user_profile instead.

validate_token(token)[source]

Return whether a token is this API key’s token, which is stored only as its digest.

Parameters:

token (str) – The plain token.

Return type:

bool

Returns:

True if the token’s key and hash match this key’s token_key and digest.

version

CharField

Version. Semantic version in the format MAJOR.MINOR.PATCH, e.g., ‘1.0.0’.

Type:

Type

class smarter.lib.drf.models.SmarterAuthTokenManager(*args, **kwargs)[source]

Bases: MetaDataWithOwnershipModelManager

Manager of API keys, which creates them as knox’s AuthTokenManager does.

It is derived from Smarter’s MetaDataWithOwnershipModelManager, for Smarter’s permission-based querying, and adds a create() that generates the token as knox does.

create(user, expiry=None, prefix=None, name=None, description=None, is_active=True, **kwargs)[source]

Create and save a new API key for a user.

Only the token’s digest is stored; the token itself is returned once, here.

Parameters:
  • user (User) – The user who owns the key; must be staff.

  • expiry – How long the key is valid, as a timedelta, or None for no expiry.

  • prefix – An optional prefix for the token string.

  • name (str | None) – The key’s name.

  • description (str | None) – The key’s description.

  • is_active (bool) – Whether the key is active.

  • kwargs – More model fields.

Return type:

tuple[SmarterAuthToken, str]

Returns:

A tuple of the saved key and the plain token.

Raises:
  • SmarterBusinessRuleViolation – If the user is not staff.

  • SmarterValueError – If name is None.

smarter.lib.drf.models.cached_auth_tokens(user_profile_id, name)[source]

Return the API keys of a user profile’s user, optionally only those with a name.

An API key belongs to a user, so every profile of the user sees the same keys. invalidate_cached_auth_tokens() drops the results of each of them.

Parameters:
  • user_profile_id (int) – The id of the user profile, part of the cache key.

  • name (str | None) – The name of the API keys, or None for all of them, part of the cache key.

Return type:

QuerySet[SmarterAuthToken]

Returns:

A queryset of the matching API keys.

smarter.lib.drf.models.invalidate_cached_auth_tokens(user_id, names)[source]

Drop the cached API keys of every profile of a user, for all names and for each of names.

Parameters:
  • user_id (int) – The id of the user whose API keys changed.

  • names (Iterable[str | None]) – The names to drop, e.g. a key’s new and old name. None and blank names are skipped.

Return type:

None