SmarterAuthToken Django ORM
- 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- __init__(*args, **kwargs)
- add_note(note, /)
Add a note to the exception
- args
- silent_variable_failure = True
- with_traceback(tb, /)
Set self.__traceback__ to tb and return self.
- HASH_FLOOR = 1000000
- HASH_PREFIX = 'r'
- HASH_SUFFIX = 'x'
- exception MultipleObjectsReturned
Bases:
MultipleObjectsReturned- __init__(*args, **kwargs)
- add_note(note, /)
Add a note to the exception
- args
- with_traceback(tb, /)
Set self.__traceback__ to tb and return self.
- exception NotUpdated
Bases:
NotUpdated- __init__(*args, **kwargs)
- add_note(note, /)
Add a note to the exception
- args
- with_traceback(tb, /)
Set self.__traceback__ to tb and return self.
- __init__(*args, **kwargs)
- accessed()[source]
Update the last used time, and save, if it is older than
LAST_USED_RESOLUTION.- Return type:
- activate()[source]
Activate the API key, and save it.
- async adelete(using=None, keep_parents=False)
- property annotations: dict[str, str]
a map of string keys to string values, as in Kubernetes.
Assigning to it validates the new annotations, and the next
save()makes the stored annotations exactly these, adding, changing and removing rows ofsmarter.lib.annotation.models.Annotation. Assignment accepts a map, or the list of one-key maps of older manifests, and converts scalar values to strings.Example:
llmclient.annotations = {**llmclient.annotations, "acme.com/crm-account-id": "A-10042"} llmclient.save()
- async arefresh_from_db(using=None, fields=None, from_queryset=None)
- async asave(*, force_insert=False, force_update=False, using=None, update_fields=None)
- authorize()
Check that no budget forbids charges to this resource.
Call it before spending on it.
It is not called when the resource is looked up, or checked for readiness, so that a resource whose budget is exceeded can still be viewed and managed.
- Raises:
SmarterBudgetExceeded – if a budget’s resource lock forbids charges to it.
- Return type:
- authtoken_ptr
OneToOneFieldtoAuthTokenPrimary key: Authtoken ptr (related name:
smarterauthtoken)- Type:
Type
- authtoken_ptr_id
Internal field, use
authtoken_ptrinstead.
- bool_environment_variable(var_name, default=False)
Retrieves a boolean value from an environment variable.
This method checks the specified environment variable and returns its value as a boolean. It recognizes common truthy values such as “true”, “1”, “yes”, and “on”. If the variable is not set or cannot be interpreted as a boolean, it returns the provided default value.
- cache_expiration: ClassVar[int] = 60
Seconds that
get_cached_object()caches a row, fromsmarter_settings.subsystem_cache_expiration.
- classmethod check(**kwargs)
- clean()
Hook for doing any extra model-wide validation after clean() has been called on every field by self.clean_fields. Any ValidationError raised by this method will not be associated with a particular field; it will have a special-case association with the field defined by NON_FIELD_ERRORS.
- clean_fields(exclude=None)
Clean all fields and raise a ValidationError containing a dict of all validation errors if any occur.
- 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
-
Created
- Type:
Type
- 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
- data_to_dict(data)
Converts data to a dictionary, handling different types of input.
This method accepts either a dictionary or a string. If a string is provided, it will attempt to parse it as JSON first, and if that fails, as YAML. If parsing fails or the data type is unsupported, a SmarterValueError is raised.
- date_error_message(lookup_type, field_name, unique_for)
- deactivate()[source]
Deactivate the API key, and save it.
- delete(using=None, keep_parents=False)
- description
-
Description. A brief description of this resource. Be verbose, but not too verbose.
- Type:
Type
- deserves_amnesty(slug)
Determines if a given URL deserves amnesty based on the amnesty URLs list.
This excuses certain endpoints (like health checks) from select middleware checks.
- dict_is_contained_in(dict1, dict2)
Checks if one dictionary is contained within another.
This method determines if all key-value pairs in dict1 are present in dict2.
- dict_is_subset(small, big)
Checks if one dictionary is a subset of another.
This method determines if all key-value pairs in the small dictionary are present in the big dictionary. It returns True if the small dictionary is a subset of the big dictionary, and False otherwise.
- digest
-
Primary key: Digest
- Type:
Type
- property elapsed_updated: int | None
The number of whole seconds since the model’s
updated_attimestamp.It is a property, so it always compares
updated_atwith the current time: thedtparameter can’t be passed, and is always None. A naiveupdated_atis compared with the naive current time, and an aware one with the current UTC time.Example
obj = MyModel.objects.get(pk=1) seconds = obj.elapsed_updated print(f"Seconds since last update: {seconds}")
- Returns:
The absolute difference in seconds between
updated_atand now, or None ifupdated_atis not set, e.g. because the object has not been saved.
- expiry
-
Expiry
- Type:
Type
- classmethod find_hash(value)
Finds and returns the first url path segment in the given value that is a hashed ID.
A segment counts only if it matches
hash_regex()and also decodes to an id, so a path segment that merely looks like one, e.g.rex, is skipped. Pass a url’s path, not the whole url: a host name is never a hashed ID.Example:
MyModel.find_hash("/workbench/llm-clients/rMTAwMDAyNwx/prompt/") # "rMTAwMDAyNwx" MyModel.find_hash("/api/v1/llm-clients/repo-ex/prompt/") # None
- formatted_class_name = '\x1b[1;31mSmarterAuthToken\x1b[0m'
- formatted_json(json_obj)
Formats a JSON object as a pretty-printed string with ANSI color codes for logging.
- property formatted_state_not_ready: str
Returns the not-ready state formatted for logging.
- Returns:
The formatted not-ready state as a string.
- Return type:
- property formatted_state_ready: str
Returns the readiness state formatted for logging.
- Returns:
The formatted readiness state as a string.
- Return type:
- formatted_text(text, color_code='\x1b[1;31m')
Formats text with ANSI color codes for logging.
- formatted_text_blue(text)
Formats text in bold dark blue for logging.
- formatted_text_green(text)
Formats text in bright green for logging.
- formatted_text_red(text)
Formats text in dark red for logging.
- classmethod from_db(db, field_names, values, **kwargs)
Load a row, and remember its name, so that
save()can tell a rename.- Parameters:
field_names (
Collection[str]) – The loaded fields’ names.values (
Collection[Any]) – The loaded fields’ values.kwargs (
Any) – Passed on to Django’s, e.g. thefetch_modethat Django’s type stubs already declare.
- Return type:
- Returns:
The instance.
- full_clean(exclude=None, validate_unique=True, validate_constraints=True)
Call clean_fields(), clean(), validate_unique(), and validate_constraints() on the model. Raise a ValidationError for any errors that occur.
- generate_fernet_encryption_key()
Generates a Fernet encryption key.
This method creates a new Fernet encryption key, which can be used for secure encryption and decryption of data. The generated key is returned as a URL-safe base64-encoded string.
- Returns:
A new Fernet encryption key.
- Return type:
- classmethod get_cached_object(*args, invalidate=False, pk=None, name=None, user=None, user_profile=None, username=None, account=None, session_key=None, taggit=True, **kwargs)
Retrieve a model instance using caching to optimize performance.
Examples of retrieval patterns:
# By primary key instance = MyModel.get_cached_object(pk=123) # By name and user profile instance = MyModel.get_cached_object(name="Resource Name", user_profile=user_profile) # By name and account instance = MyModel.get_cached_object(name="Resource Name", account=account)
- Parameters:
pk (
int|None) – The primary key of the model instance to retrieve.name (
str|None) – The name of the model instance to retrieve.user (
User|None) – The user associated with the model instance.user_profile (
UserProfile|None) – The user profile associated with the model instance.account (
Account|None) – The account associated with the model instance.invalidate (
bool|None) – Whether to invalidate the cache for this retrieval.
- Returns:
The model instance if found, otherwise raises
DoesNotExist.- Return 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.
- get_constraints()
- get_deferred_fields()
Return a set containing names of deferred fields for this instance.
- get_next_by_created(*, field=<django.db.models.DateTimeField: created>, is_next=True, **kwargs)
Finds next instance based on
created. Seeget_next_by_FOO()for more information.
- 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.
- get_previous_by_created(*, field=<django.db.models.DateTimeField: created>, is_next=False, **kwargs)
Finds previous instance based on
created. Seeget_previous_by_FOO()for more information.
- get_readonly_csv_file(file_path)
Reads a CSV file and returns its contents as a list of dictionaries, one per row.
The file is opened read-only, so reading it never modifies it.
- get_readonly_yaml_file(file_path)
Reads a YAML file and returns its contents as a dictionary.
The file is opened read-only, so reading it never modifies it.
- classmethod hash_regex()
Returns a regex pattern that matches a hashed ID that is a whole url path segment.
The hashed ID format is defined by the
HASH_PREFIXandHASH_SUFFIXclass attributes, with a base64-encoded string in between. A match must start at the beginning of the string or after a/, and end at the end of the string or before a/. Without these boundaries, the pattern would match inside ordinary words, e.g.repo-exin the host namerepo-explorer.Example:
pattern = MyModel.hash_regex() pattern.search("/workbench/llm-clients/rMTAwMDAyNwx/prompt/") # matches rMTAwMDAyNwx pattern.search("http://repo-explorer.example.com/") # None
- Return type:
- Returns:
A regex pattern for matching hashed IDs.
- property health_check_urls: list[str]
Returns a list of URL paths that are considered health check endpoints.
- 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.
- classmethod id_from_hashed_id(hashed_id)
Decodes a hashed ID back to the original object ID.
Decoding scheme:
Validate that the hashed ID starts with the expected prefix and ends with the expected suffix.
Remove the prefix and suffix to isolate the base64-encoded string.
Add padding if necessary to make the length of the encoded string a multiple of 4.
Decode the base64 string to get the original number as a string.
Convert the decoded string to an integer and subtract the HASH_FLOOR to get the original ID.
Example:
my_record = MyModel.objects.create() print(my_record.id) # e.g., 123 hashed_id = my_record.hashed_id # e.g., "rc2x" original_id = MyModel.id_from_hashed_id(hashed_id) print(original_id) # Should print the original ID (e.g., 123)
- property identifier: str
Return the token’s digest, masked for logging.
- classmethod invalidate_cached_name(name)
Drop the cached copy of the row that had
name.get_cached_object()withinvalidate=Truedrops it, then looks the name up again. That lookup fails when no row has the name any more, e.g. after a rename, or when several rows share it, e.g. the profiles of one user in several accounts. Either way the cached copy is already gone, so the failure is ignored.
- is_active
-
Is active
- Type:
Type
- property is_billable_resource: bool
Indicates whether the model instance is considered a billable resource.
This property can be overridden in subclasses to specify which models are billable. By default, it returns False, indicating that the base TimestampedModel is not billable.
- Returns:
True if the instance is billable, False otherwise.
- key_id
-
Key id
- 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/'
- mask_string(string='', mask_char='*', mask_length=4, string_length=8)
Masks a string for secure logging.
This utility function masks all but the last unmasked_chars characters of the input string, replacing them with asterisks. It is useful for logging sensitive information like API keys or passwords.
- name
-
Name. Name in camelCase, e.g., ‘apiKey’, no special characters.
- Type:
Type
- objects: MetaDataWithOwnershipModelManager = <smarter.lib.drf.models.SmarterAuthTokenManager object>
- property pk
- prepare_database_save(field)
- property ready: bool
Returns True if the resource is ready for use, False otherwise.
A resource is considered ready if it has been fully initialized and is in a usable state. This property can be overridden in subclasses to implement custom readiness checks.
- Returns:
True if the resource is ready, False otherwise.
- Return type:
- 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.
- recursive_sort_dict(data)
Recursively sorts a dictionary by its keys.
This method takes a dictionary and returns a new dictionary with all keys sorted in ascending order. If any values are also dictionaries, they will be sorted recursively as well.
- refresh_from_db(using=None, fields=None, from_queryset=None)
Reload field values from the database.
By default, the reloading happens from the database this instance was loaded from, or by the read router if this instance wasn’t loaded from any database. The using parameter will override the default.
Fields can be used to specify which fields to reload. The fields should be an iterable of field attnames. If fields is None, then all non-deferred fields are reloaded.
When accessing deferred fields of an instance, the deferred loading of the field will call this method.
- remove_annotation(key)
Remove one annotation of a saved resource, immediately.
Does nothing if it doesn’t exist.
- rename(new_name)
Rename the model instance with a new name.
The instance is validated and saved.
- Parameters:
new_name (
str) – The new name for the instance.- Return type:
- Returns:
The updated instance of MetaDataModel with the new name.
- classmethod restrict_readable(queryset, user)
Hide rows that a user may not read, although their owner would let them.
SmarterQuerySetWithPermissions.with_read_permission_for()calls it last, after it has found the rows of the user’s own account and of the Smarter account. Most kinds hide nothing, and return the queryset as it is. A kind with rows for some users only overrides it, e.g.smarter.apps.llmclient.models.LLMClient.restrict_readable(), which hides an LLMClient that only the platform’s staff may use.- Parameters:
queryset (
SmarterQuerySetWithPermissions[Any]) – The rows that the user’s account and the Smarter account let them read.user (
User) – The user.
- Return type:
- Returns:
The rows that the user may read.
- property rfc1034_compliant_name: str | None
Returns a URL-friendly name for the llmclient.
This property returns an RFC 1034-compliant name for the llmclient, suitable for use in URLs and DNS labels.
Example:
self.name = 'Example LLMClient 1' self.rfc1034_compliant_name # 'example-llmclient-1'
- Returns:
The RFC 1034-compliant name, or None if
self.nameis not set.
- rfc1034_compliant_str(name)
Converts a string to an RFC 1034 compliant format.
This method takes a string and converts it to a format that complies with RFC 1034, which is commonly used for domain names. It replaces invalid characters with hyphens and ensures the resulting string is lowercase.
- rfc1034_compliant_to_snake(name)
Converts an RFC 1034 compliant string to snake_case.
This method takes a string in RFC 1034 compliant format and converts it to snake_case. It replaces hyphens with underscores and ensures the resulting string is lowercase.
- 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.
- save_annotations()
Write annotations assigned since the last
save()to the database, without saving the resource’s other fields.- Return type:
- save_base(raw=False, force_insert=False, force_update=False, using=None, update_fields=None)
Handle the parts of saving which should be done only once per save, yet need to be done in raw saves, too. This includes some sanity checks and signal sending.
The ‘raw’ argument is telling save_base not to save any parent models and not to do any changes to the values before save. This is used by fixture loading.
- serializable_value(field_name)
Return the value of the field name for this instance. If the field is a foreign key, return the id value instead of the object. If there’s no Field object with this name on the model, return the model attribute’s value.
Used to serialize a field’s value (in the serializer, or form output, for example). Normally, you would just access the attribute directly and not use this method.
- set_annotation(key, value)
Add or change one annotation of a saved resource, immediately.
- Parameters:
- Raises:
SmarterAnnotationError – If the key or value is invalid.
- Return type:
- smarter_build_absolute_uri(request)
Attempts to get the absolute URI from a request object.
This utility function tries to retrieve the request URL from any valid child class of
django.http.HttpRequest. It is especially useful in unit tests or scenarios where the request object may not implementbuild_absolute_uri().- Parameters:
request (
HttpRequest) – The request object.- Returns:
The absolute request URL.
- Return type:
- Raises:
SmarterValueError – If the URI cannot be built from the request.
- smarterauthtoken
Reverse
OneToOneFieldfromSmarterAuthTokenThe API Key of this auth token (related name of
authtoken_ptr)- Type:
Type
- sorted_dict(data)
Returns a new dictionary with keys sorted.
- tags
-
Tags
- Type:
Type
- 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.
- to_camel_case(data, convert_values=False)
Converts a snake_case string to camelCase.
This method takes a string in snake_case format and converts it to camelCase. It is useful for standardizing naming conventions across different formats.
- Parameters:
data (
ConvertibleCaseT) – The snake_case string to convert.convert_values (
bool) – Whether to convert the values of dictionaries and lists recursively.
- Returns:
The converted string in camelCase.
- Return type:
ConvertibleCaseT
- to_json()
Serialize the model instance to a JSON-compatible dictionary.
This method uses the custom
SmarterJSONEncoderto ensure that all fields, including timestamps and any complex data types, are properly serialized.
- to_snake_case(data, convert_values=False)
Converts a camelCase or PascalCase string to snake_case.
This method takes a string in camelCase or PascalCase format and converts it to snake_case. It is useful for standardizing naming conventions across different formats.
- Parameters:
data (
ConvertibleCaseT) – The camelCase or PascalCase string to convert.convert_values (
bool) – Whether to convert the values of dictionaries and lists recursively.
- Returns:
The converted string in snake_case.
- Return type:
ConvertibleCaseT
- toggle_active()[source]
Toggle the API key’s active status, and save it.
- token_key
-
Token key
- Type:
Type
- property unformatted_class_name: str
Returns the raw class name without formatting.
- Returns:
The unformatted class name as a string.
- Return type:
This is useful for logging or serialization where the plain class name is needed.
- unique_error_message(model_class, unique_check)
- 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
ForeignKeytoUserUser (related name:
auth_token_set)- Type:
Type
- user_id
Internal field, use
userinstead.
- user_profile
-
User profile (related name:
smarterauthtoken)- Type:
Type
- user_profile_id
Internal field, use
user_profileinstead.
- validate()
Validate the model: its version, when set, must be a semantic version.
- Raises:
SmarterValueError – if the version is not
MAJOR.MINOR.PATCH.
- validate_constraints(exclude=None)
- validate_token(token)[source]
Return whether a token is this API key’s token, which is stored only as its digest.
- validate_unique(exclude=None)
Check unique constraints on the model and raise ValidationError if any failed.
- version
-
Version. Semantic version in the format MAJOR.MINOR.PATCH, e.g., ‘1.0.0’.
- Type:
Type
- classmethod with_annotation(key, value=None)
Return the resources of this model that have the annotation
key, withvalueif given.Example:
LLMClient.with_annotation("acme.com/crm-account-id", "A-10042")