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 AuthToken and includes additional metadata and management features for API keys, such as naming, description, activation status, and usage tracking.
- Parameters:
key_id (UUIDField): Unique identifier for the API key. name (str): Human-readable name for the API key. description (str, optional): Optional description of the API key’s purpose. last_used_at (datetime, optional): Timestamp of the last usage of the API key. is_active (bool): Indicates whether the API key is currently active.
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 staff users. Attempting to create a key for a non-staff user will raise a SmarterBusinessRuleViolation.
The identifier property returns a masked version of the key digest for display purposes.
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.
- param digest:
Primary key: Digest
- type digest:
Unknown
- param token_key:
Token key
- type token_key:
Unknown
- param created:
Created
- type created:
Unknown
- param expiry:
Expiry
- type expiry:
Unknown
- param created_at:
Created at
- type created_at:
Unknown
- param updated_at:
Updated at
- type updated_at:
Unknown
- param name:
Name. Name in camelCase, e.g., ‘apiKey’, no special characters.
- type name:
Unknown
- param description:
Description. A brief description of this resource. Be verbose, but not too verbose.
- type description:
Unknown
- param version:
Version. Semantic version in the format MAJOR.MINOR.PATCH, e.g., ‘1.0.0’.
- type version:
Unknown
- param annotations:
Annotations. Key-value pairs for annotating this resource.
- type annotations:
Unknown
- param key_id:
Key id
- type key_id:
Unknown
- param last_used_at:
Last used at
- type last_used_at:
Unknown
- param is_active:
Is active
- type is_active:
Unknown
Relationship fields:
- param user:
User (related name:
auth_token_set)- type user:
ForeignKeytoUser- param authtoken_ptr:
Primary key: Authtoken ptr (related name:
smarterauthtoken)- type authtoken_ptr:
OneToOneFieldtoAuthToken- param user_profile:
User profile (related name:
smarterauthtoken)- type user_profile:
- param tags:
Tags. Tags for categorizing and organizing this resource. (related name:
smarterauthtoken)- type tags:
TaggableManagertoTag
Reverse relationships:
- param chatbotapikey:
All ChatBot API Keys of this API Key (related name of
api_key)- type chatbotapikey:
Reverse
ForeignKeyfromChatBotAPIKey
- exception DoesNotExist
Bases:
DoesNotExist- __init__(*args, **kwargs)
- add_note(object, /)
Exception.add_note(note) – add a note to the exception
- args
- silent_variable_failure = True
- with_traceback(object, /)
Exception.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(object, /)
Exception.add_note(note) – add a note to the exception
- args
- with_traceback(object, /)
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- exception NotUpdated
Bases:
NotUpdated- __init__(*args, **kwargs)
- add_note(object, /)
Exception.add_note(note) – add a note to the exception
- args
- with_traceback(object, /)
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- __init__(*args, **kwargs)
- async adelete(using=None, keep_parents=False)
- property amnesty_urls: list[str]
Returns a list of URLs that are exempt from certain checks.
This is a placeholder and should be overridden in subclasses.
- async arefresh_from_db(using=None, fields=None, from_queryset=None)
- async asave(*, force_insert=False, force_update=False, using=None, update_fields=None)
- authtoken_ptr
OneToOneFieldtoAuthTokenPrimary key: Authtoken ptr (related name:
smarterauthtoken)- Type:
Type
- authtoken_ptr_id
Internal field, use
authtoken_ptrinstead.
- cache_expiration = 60
- chatbotapikey_set
Reverse
ForeignKeyfromChatBotAPIKeyAll ChatBot API Keys of this API Key (related name of
api_key)- Type:
Type
- 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.
- 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)
- delete(using=None, keep_parents=False)
- description
-
Description. A brief description of this resource. Be verbose, but not too verbose.
- Type:
Type
- property elapsed_updated: int | None
Calculate the absolute time difference in seconds between a given datetime and the model’s
updated_attimestamp.This property is useful for determining how much time has elapsed since the model instance was last updated, or for comparing the
updated_atfield to any arbitrary datetime.Parameters:
dt (datetime, optional): The reference datetime to compare against
updated_at. - Ifdtis not provided, the current time is used. - Both naive and timezone-aware datetime objects are supported; the method will handle conversions as needed.
Returns:
int or None: The absolute difference in seconds between
updated_atanddt. ReturnsNoneifupdated_atis not set.
Example Usage:
obj = MyModel.objects.get(pk=1) # Time since last update seconds = obj.elapsed_updated print(f"Seconds since last update: {seconds}") # Compare to a specific datetime import datetime dt = datetime.datetime(2025, 12, 1, 12, 0, 0) diff = obj.elapsed_updated(dt) print(f"Seconds between updated_at and 2025-12-01 12:00:00: {diff}")
Note
Handles both naive and aware datetime objects, converting as necessary to ensure accurate calculation.
If
updated_atis not set (e.g., the object has not been saved), returnsNone.
Attention
If
dtis provided and is not adatetime.datetimeinstance, aTypeErrorwill be raised.Always ensure that
updated_atis set before relying on this property for calculations.
- expiry
-
Expiry
- Type:
Type
- classmethod find_hash(value)
Finds and returns the first substring in the given value that matches the hashed ID format.
- property formatted_class_name: str
Returns the class name formatted for logging.
- Returns:
The formatted class name as a string.
- Return type:
- 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:
- classmethod from_db(db, field_names, values)
- 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.
- classmethod get_cached_object(*args, invalidate=False, pk=None, name=None, user=None, user_profile=None, username=None, account=None, session_key=None, **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 (
Optional[int]) – The primary key of the model instance to retrieve.name (
Optional[str]) – The name of the model instance to retrieve.user (
Optional[User]) – The user associated with the model instance.user_profile (
Optional[UserProfile]) – The user profile associated with the model instance.account (
Optional[Account]) – The account associated with the model instance.invalidate (
Optional[bool]) – 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, user=None, name=None)[source]
Retrieve API keys with caching based on user profile and optional name filter using caching.
- Parameters:
invalidate (
Optional[bool]) – If True, invalidate the cache for this query.user_profile (
Optional[UserProfile]) – The user profile for which to retrieve API keys.user (
Optional[User]) – The user for which to retrieve API keys (used if user_profile is not provided).name (
Optional[str]) – Optional name filter to retrieve API keys with a specific name.
- Returns:
A queryset of SmarterAuthToken objects matching the criteria.
- Return type:
- 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)
Retrieves an object based on its record locator.
Example:
obj = MyModel.objects.create() print(obj.id) # e.g., 123 locator = obj.record_locator # e.g., "mymodel-rc2x" retrieved_obj = MyModel.get_object_by_locator(locator) print(type(retrieved_obj)) # Should be <class 'MyModel'> print(retrieved_obj) # Should be the same as obj
- Parameters:
locator (
str) – The record locator string to decode and search for.- Returns:
The model instance if found, otherwise None.
- Return type:
- 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.
- classmethod hash_regex()
Returns a regex pattern that matches the hashed ID format for this model anywhere in a string.
The hashed ID format is defined by the
HASH_PREFIXandHASH_SUFFIXclass attributes, with a base64-encoded string in between. This regex can be used to validate or extract hashed IDs from strings, including when embedded in URLs.- Returns:
A regex pattern for matching hashed IDs.
- Return type:
- property hashed_id: str
Returns a URL-friendly hashed version of the object’s ID for use in URLs and other contexts where an obscured, non-identifying, non-sequential identifier is preferred.
Encoding scheme: 1. Take the object’s ID and add a large constant (HASH_FLOOR) to ensure it’s not easily guessable. 2. Convert the resulting number to a string and encode it using URL-safe base64 encoding. 3. Remove any padding characters from the encoded string. 4. Add a prefix and suffix to the encoded string to create a recognizable format.
Example:
obj = MyModel.objects.create() print(obj.id) # e.g., 123 print(obj.hashed_id) # e.g., "rc2x"
- Returns:
Hashed ID string (URL-safe, no padding)
- Return type:
- classmethod id_from_hashed_id(hashed_id)
Decodes a hashed ID back to the original object ID.
decoding scheme: 1. Validate that the hashed ID starts with the expected prefix and ends with the expected suffix. 2. Remove the prefix and suffix to isolate the base64-encoded string. 3. Add padding if necessary to make the length of the encoded string a multiple of 4. 4. Decode the base64 string to get the original number as a string. 5. 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
- is_active
-
Is active
- Type:
Type
- last_used_at
-
Last used at
- Type:
Type
- 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.
- objects: MetaDataWithOwnershipModelManager = <smarter.lib.drf.models.SmarterAuthTokenManager object>
- property pk
- prepare_database_save(field)
- property ready: bool
Indicates whether the object is ready for use. This is a placeholder that should be overridden in subclasses.
- Returns:
True if ready, False otherwise.
- Return type:
- property record_locator: str
Returns a short, URL-friendly record locator derived from the object’s ID.
Example:
obj = MyModel.objects.create(name="Example") print(obj.id) # e.g., 123 print(obj.record_locator) # e.g., "chatbot-rc2x"
- Returns:
Record locator string (URL-safe, no padding)
- Return type:
- 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.
- save(*args, **kwargs)[source]
Save the current instance. Override this in a subclass if you want to control the saving process.
The ‘force_insert’ and ‘force_update’ parameters can be used to insist that the “save” must be an SQL insert or update (or equivalent for non-SQL backends), respectively. Normally, they should not be set.
- 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.
- 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 = <taggit.managers._TaggableManager object>
- property tags_list: list[str]
Return the tags as a list of strings. We assume that @cached_property is more efficient at fetch that @cache_results, all things considered equal, which provides a marginal boost to instances. Meanwhile, the @cache_results is persisted to the Django cache, and thus outlives this instance. Thus, best of both worlds.
- 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.
- 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_profile
-
User profile (related name:
smarterauthtoken)- Type:
Type
- user_profile_id
Internal field, use
user_profileinstead.
- validate()
Validate the model.
- validate_constraints(exclude=None)
- validate_unique(exclude=None)
Check unique constraints on the model and raise ValidationError if any failed.