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_atis kept.Every authenticated request uses its key, so
last_used_atis written at most once per this interval per key, not on every request.
- class smarter.lib.drf.models.SmarterAuthToken(*args, **kwargs)[source]
Bases:
AuthToken,MetaDataWithOwnershipModelRepresents a Smarter API Key used for authenticating and authorizing access to the Smarter platform.
This model extends Knox’s
AuthTokenand 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 withinLAST_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 aSmarterBusinessRuleViolation.The
identifierproperty 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
getanddescribereport 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:
- authtoken_ptr
OneToOneFieldtoAuthTokenPrimary key: Authtoken ptr (related name:
smarterauthtoken)- Type:
Type
- authtoken_ptr_id
Internal field, use
authtoken_ptrinstead.
- 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:
- Return type:
- Returns:
The new key.
- created_at
-
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
- description
-
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 (seesmarter.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 ifuser_profileis 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_profilenoruseris given.
- classmethod get_object_by_locator(locator)[source]
Return the SmarterAuthToken that a locator from
record_locatoridentifies.- Parameters:
locator (
str) – The record locator.- Return type:
- Returns:
The API key, or None if the locator is malformed or no key has its
key_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.
- is_active
-
Is active
- Type:
Type
- last_used_at
-
Last used at
- Type:
Type
- last_used_is_stale(now)[source]
Return whether
last_used_atis older thanLAST_USED_RESOLUTION.
- llmclientapikey_set
Reverse
ForeignKeyfromLLMClientAPIKeyAll 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/'
- 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
createdif unset and convertingnameto 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.
- property tags_list: list[str]
Return the tag names.
tagsis a JSONField list here, not a taggit manager.- Returns:
The tag names, or an empty list if
tagsis not a list.
- updated_at
-
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
-
User profile (related name:
smarterauthtoken)- Type:
Type
- user_profile_id
Internal field, use
user_profileinstead.
- class smarter.lib.drf.models.SmarterAuthTokenManager(*args, **kwargs)[source]
Bases:
MetaDataWithOwnershipModelManagerManager of API keys, which creates them as knox’s
AuthTokenManagerdoes.It is derived from Smarter’s
MetaDataWithOwnershipModelManager, for Smarter’s permission-based querying, and adds acreate()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:
- Return type:
- Returns:
A tuple of the saved key and the plain token.
- Raises:
SmarterBusinessRuleViolation – If the user is not staff.
SmarterValueError – If
nameis 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:
- Return type:
- Returns:
A queryset of the matching API keys.