User

Smarter API User Manifest handler

smarter.apps.account.manifest.brokers.user.MAX_RESULTS = 1000

Maximum number of results to return for list operations. This limit helps prevent performance issues and excessive data retrieval.

TODO: Make this configurable via smarter_settings.

class smarter.apps.account.manifest.brokers.user.SAMUserBroker(*args, **kwargs)[source]

Bases: AbstractBroker

Smarter API User Manifest Broker

This class manages the lifecycle of Smarter API User manifests, including loading, validating, parsing, and mapping them to Django ORM models and Pydantic models for serialization and deserialization.

Responsibilities:
  • Load and validate Smarter API YAML User manifests.

  • Parse manifests and initialize the corresponding Pydantic model (SAMUser).

  • Interact with Django ORM models representing user manifests.

  • Create, update, delete, and query Django ORM models.

  • Transform Django ORM models into Pydantic models for serialization/deserialization.

Example Usage:

broker = SAMUserBroker()
manifest = broker.manifest
if manifest:
    print(manifest.apiVersion, manifest.kind)

Warning

If the manifest loader or manifest metadata is missing, the manifest may not be initialized and None may be returned.

See also

  • SAMUser (Pydantic model)

  • Django ORM models: User, AccountContact, UserProfile

Todo

Make the maximum results for list operations configurable via smarter_settings.

property ORMMetaModelClass: Type[User]

Return the Django ORM meta model class for the broker.

Returns:

The Django ORM meta model class definition for the broker.

Return type:

Type[User]

property ORMModelClass: Type[User]

Return the model class associated with the Smarter API User.

Returns:

The User model class.

Example usage:

model_cls = broker.ORMModelClass
user_instance = model_cls.objects.get(username="example_user")

See also

  • smarter.apps.account.models.User

property SAMModelClass: Type[SAMUser]

Return the Pydantic model class for the broker.

Returns:

The Pydantic model class definition for the broker.

Return type:

Type[SAMUser]

property SerializerClass: Type[UserSerializer]

Return the serializer class associated with the Smarter API User.

Returns:

The UserSerializer class.

Example usage:

serializer_cls = broker.SerializerClass
serializer = serializer_cls(instance=user_instance)

See also

  • smarter.apps.account.serializers.UserSerializer

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

Initialize the SAMUserBroker instance.

This constructor initializes the broker by calling the parent class’s constructor, which will attempt to bootstrap the class instance with any combination of raw manifest data (in JSON or YAML format), a manifest loader, or existing Django ORM models. If a manifest loader is provided and its kind matches the expected kind for this broker, the manifest is initialized using the loader’s data.

This class can bootstrap itself in any of the following ways:

  • request.body (yaml or json string)

  • name + account (determined via authentication of the request object)

  • SAMLoader instance

  • manifest instance

  • filepath to a manifest file

If raw manifest data is provided, whether as a string or a dictionary, or a SAMLoader instance, the base class constructor will only goes as far as initializing the loader. The actual manifest model initialization is deferred to this constructor, which checks the loader’s kind.

Parameters:
  • args – Positional arguments passed to the parent constructor.

  • kwargs – Keyword arguments passed to the parent constructor.

Example:

broker = SAMUserBroker(loader=loader, plugin_meta=plugin_meta)
property account_contact: AccountContact | None

Retrieve the AccountContact associated with the current authenticated user and account.

Returns:

An AccountContact instance if found, otherwise None.

Note

  • This property returns None if the user is not set or not authenticated.

  • If no matching AccountContact exists for the user’s email and account, None is returned.

Example usage:

contact = broker.account_contact
if contact:
    print(contact.first_name, contact.last_name, contact.email)

See also

apply(request, *args, **kwargs)[source]

Apply the manifest data to the Django ORM User model and persist changes to the database.

Note

tags are handled separately because they are of type TaggableManager and require a different method to set them.

Parameters:
  • request (HttpRequest) – The Django HttpRequest object.

  • args – Additional positional arguments.

  • kwargs – Additional keyword arguments.

Return type:

SmarterJournaledJsonResponse

Returns:

A SmarterJournaledJsonResponse containing the updated user manifest.

Note

This method first calls super().apply() to ensure the manifest is loaded and validated before applying changes.

Attention

Fields in the manifest that are not editable (e.g., id, date_joined, last_login, username, is_superuser) are removed before saving to the ORM model.

Raises:

SAMUserBrokerError If the user instance is not set or is invalid

Example usage:

response = broker.apply(request)
print(response.data)

See also

property brokered_user: User | None

In order to disambiguate between the AccountMixin.user (the authenticated user making the request) and the User resource being brokered, we use the term “brokered_user”.

Retrieve the User model instance associated with the current broker.

Returns:

A User instance if found, otherwise None.

Note

  • This property returns None if the user is not set.

  • If no matching User exists for the broker’s username, None is returned.

Example usage:

user = broker.brokered_user
if user:
    print(user.first_name, user.last_name, user.email)

See also

  • smarter.apps.account.models.User

property brokered_user_profile: UserProfile | None

The UserProfile associated with the brokered user. This disambiguates between the AccountMixin.user_profile (the profile of the authenticated user making the request) and the UserProfile resource being brokered.

Retrieve the UserProfile model instance associated with the current brokered user.

Returns:

A UserProfile instance if found, otherwise None.

Note

  • This property returns None if the brokered user is not set.

  • If no matching UserProfile exists for the brokered user and account, None is returned.

Example usage:

profile = broker.brokered_user_profile
  if profile:
      print(profile.name, profile.description)
cache_invalidations()[source]

Invalidate any relevant caches for the brokered user. Invalidates the UserProfile cache for the brokered user and account.

Return type:

None

chat(request, *args, **kwargs)[source]

Attention

this is not implemented for the Smarter API User manifest.

Raises:

SAMBrokerErrorNotImplemented Always raised to indicate that the chat operation is not implemented for this manifest type.

Parameters:
  • request (HttpRequest) – The Django HttpRequest object.

  • args – Additional positional arguments.

  • kwargs – Additional keyword arguments.

Return type:

SmarterJournaledJsonResponse

Returns:

Never returns; always raises an exception.

delete(request, *args, **kwargs)[source]

Delete the Smarter API User manifest by removing the corresponding Django ORM User model instance.

Parameters:
  • request (HttpRequest) – The Django HttpRequest object.

  • args – Additional positional arguments.

  • kwargs – Additional keyword arguments, including the username to delete.

Return type:

SmarterJournaledJsonResponse

Returns:

A SmarterJournaledJsonResponse indicating the result of the delete operation.

Raises:

SAMBrokerErrorNotFound If the user with the specified username does not exist.

Raises:

SAMUserBrokerError If deletion fails for the user.

deploy(request, *args, **kwargs)[source]

Deploy the Smarter API User manifest by activating the corresponding Django ORM User model instance.

Parameters:
  • request (HttpRequest) – The Django HttpRequest object.

  • args – Additional positional arguments.

  • kwargs – Additional keyword arguments.

Raises:

SAMUserBrokerError If deployment fails for the user.

Return type:

SmarterJournaledJsonResponse

Returns:

A SmarterJournaledJsonResponse indicating the result of the deploy operation.

describe(request, *args, **kwargs)[source]

Describe the Smarter API User manifest by retrieving the corresponding Django ORM User model instance.

Parameters:
  • request (HttpRequest) – The Django HttpRequest object.

  • args – Additional positional arguments.

  • kwargs – Additional keyword arguments, including the username to describe.

Return type:

SmarterJournaledJsonResponse

Returns:

A SmarterJournaledJsonResponse containing the user manifest data.

Raises:

SAMBrokerErrorNotFound If the user with the specified username does not exist or is not associated with the account.

Raises:

SAMUserBrokerError If serialization fails for the user.

django_orm_to_manifest_dict()[source]

Convert a Django ORM User model instance into a dictionary formatted for Pydantic manifest consumption.

Return type:

Optional[dict[str, Any]]

Returns:

A dictionary representing the Smarter API User manifest, or None if the user is not set.

Note

Field names are automatically converted from snake_case to camelCase for compatibility with Pydantic models.

Raises:

SAMUserBrokerError if self.brokered_user is not set.

Example usage:

manifest_dict = broker.django_orm_to_manifest_dict()
if manifest_dict:
    print(manifest_dict["spec"]["config"]["email"])

See also

  • manifest_to_django_orm()

  • SAMUser

  • smarter.apps.account.models.User

  • smarter.lib.manifest.enum.SamKeys

  • smarter.lib.manifest.enumSAMMetadataKeys

  • smarter.lib.manifest.enumSAMUserSpecKeys

example_manifest(request, *args, **kwargs)[source]

Return the SAM User model associated with the Smarter API User manifest.

Return type:

SmarterJournaledJsonResponse

Returns:

a dict representing the SAM User model.

See also

property formatted_class_name: str

Return a formatted class name string for logging and diagnostics.

Returns:

A string representing the fully qualified class name, including the parent class.

Example usage:

logger.info(broker.formatted_class_name)
get(request, *args, **kwargs)[source]

Retrieve Smarter API User manifests as a list of serialized Pydantic models.

Parameters:
  • request (HttpRequest) – The Django HttpRequest object.

  • args – Additional positional arguments.

  • kwargs – Additional keyword arguments, including optional filter parameters.

Return type:

SmarterJournaledJsonResponse

Returns:

A SmarterJournaledJsonResponse containing a list of user manifests and metadata.

Note

If a username is provided in kwargs, only manifests for that user are returned; otherwise, all manifests for the account are listed.

Raises:

SAMUserBrokerError If serialization fails for any user

Example usage:

response = broker.get(request, name="alice")
print(response.data["spec"]["items"])

See also

  • smarter.apps.account.serializers.UserSerializer

  • django_orm_to_manifest_dict()

  • smarter.lib.manifest.response.SmarterJournaledJsonResponse

  • smarter.lib.manifest.enum.SamKeys

  • smarter.lib.manifest.enum.SAMMetadataKeys

  • smarter.lib.manifest.enum.SCLIResponseGet

  • smarter.lib.manifest.enum.SCLIResponseGetData

property kind: str

Return the manifest kind string for the Smarter API User.

Returns:

The manifest kind as a string (e.g., "User").

Example usage:

if broker.kind == "User":
    print("This broker handles User manifests.")
logs(request, *args, **kwargs)[source]

Retrieve logs related to the Smarter API User manifest.

Parameters:
  • request (HttpRequest) – The Django HttpRequest object.

  • args – Additional positional arguments.

  • kwargs – Additional keyword arguments.

Return type:

SmarterJournaledJsonResponse

Returns:

A SmarterJournaledJsonResponse containing log data.

property manifest: SAMUser | None

Get the manifest for the Smarter API User as a Pydantic model.

Returns:

A SAMUser Pydantic model instance representing the Smarter API User manifest, or None if not initialized.

Note

The top-level manifest model (SAMUser) must be explicitly initialized with manifest data, typically using **data from the manifest loader.

Warning

If the manifest loader or manifest metadata is missing, the manifest will not be initialized and None may be returned.

Example usage:

# Access the manifest property
manifest = broker.manifest
if manifest:
    print(manifest.apiVersion, manifest.kind)
manifest_to_django_orm()[source]

Convert the Smarter API User manifest (Pydantic model) into a dictionary suitable for Django ORM operations.

Return type:

dict

Returns:

A dictionary with keys and values formatted for Django ORM model assignment.

Note

Field names are automatically converted from camelCase to snake_case to match Django conventions.

Attention

The returned dictionary may include fields that are not editable in the Django ORM model. Ensure you filter out read-only fields before saving.

Example usage:

orm_data = broker.manifest_to_django_orm()
for key, value in orm_data.items():
    setattr(user, key, value)
user.save()

See also

property name: str | None

Get the name of the Smarter API Account.

Returns:

The name of the Smarter API Account, or None if not set.

Return type:

Optional[str]

property orm_instance: User | None

Return the Django ORM model instance for the broker.

Returns:

The Django ORM model instance for the broker.

Return type:

Optional[TimestampedModel]

orm_meta_instance_setter()[source]

Override the base method to initialize the ORM meta model instance for the broker.

Return type:

None

property ready: bool

Check if the broker is ready for operations.

This property determines whether the broker has been properly initialized and is ready to perform its functions. A broker is considered ready if it has a valid manifest loaded, either from raw data, a loader, or existing Django ORM models.

Returns:

True if the broker is ready, False otherwise.

Return type:

bool

undeploy(request, *args, **kwargs)[source]

Undeploy the Smarter API User manifest by deactivating the corresponding Django ORM User model instance.

Parameters:
  • request (HttpRequest) – The Django HttpRequest object.

  • args – Additional positional arguments.

  • kwargs – Additional keyword arguments.

Raises:

SAMUserBrokerError If undeployment fails for the user.

Return type:

SmarterJournaledJsonResponse

property username: str | None

Return the username of the current user, if available.

Returns:

The username as a string, or None if the user is not set.

Example usage:

username = broker.username
if username:
    print(f"Current user: {username}")

See also

  • smarter.apps.account.models.User

exception smarter.apps.account.manifest.brokers.user.SAMUserBrokerError(message=None, thing=None, command=None, stack_trace=None)[source]

Bases: SAMBrokerError

Base exception for Smarter API User Broker handling.

property get_formatted_err_message
smarter.apps.account.manifest.brokers.user.should_log(level)[source]

Check if logging should be done based on the waffle switch.