User

Smarter API User Manifest handler.

smarter.apps.account.manifest.brokers.user.LOGGED_FIELDS = ('username', 'email', 'first_name', 'last_name', 'is_active', 'is_staff', 'is_superuser', 'last_login', 'date_joined')

The User fields that log messages may show. Not password, the password’s hash.

(
    'username',
    'email',
    'first_name',
    'last_name',
    'is_active',
    'is_staff',
    'is_superuser',
    'last_login',
    'date_joined',
)
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[User, User]

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 data or its 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 broker from a manifest, a manifest file, or the Django ORM.

A manifest takes precedence over a file path. With neither, the broker is initialized from the ORM instance named name and owned by the user profile, if there is one.

Parameters:
  • request – The request, or None. It may also be passed positionally in args.

  • args – Positional arguments, among which the request, user, account, user profile and manifest are found by their types.

  • name – The resource’s name.

  • kind – The resource’s SAM kind, e.g. Guardrail.

  • api_version – The manifest’s api version.

  • manifest – The manifest, as a Pydantic model or as a dict, e.g. from parse_manifest().

  • file_path – The path of a manifest file, read when no manifest is passed.

  • url – Accepted, for compatibility, but not used.

  • kwargs – user, account and user_profile, and the rest, which are passed on to SmarterRequestMixin.

Raises:
  • SmarterValueError – If the kind, name or manifest is invalid.

  • SAMBrokerError – If the manifest’s kind is not the broker’s kind.

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

  • smarter.apps.account.models.AccountContact

  • smarter.apps.account.models.User

  • smarter.apps.account.models.Account

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.

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

apply_memberships(brokered_user, memberships)[source]

Create each of the user’s listed memberships that is missing, and update the others.

A membership that the list omits is left as it is: deleting a profile deletes every resource that it owns.

Parameters:
Raises:

SAMBrokerErrorNotFound – if a listed account doesn’t exist.

Return type:

None

apply_own_account_profile(brokered_user)[source]

Create or update the user’s profile in the account of whoever applies the manifest, which has no spec.accounts.

Parameters:

brokered_user (User) – The user, saved.

Return type:

None

apply_user_fields(brokered_user)[source]

Copy the manifest’s spec.config onto the user, and set their password if passwordSecret names a Secret.

Fields that a manifest may not change, e.g. username and is_superuser, are left as they are.

Parameters:

brokered_user (User) – The user, not yet saved.

Return type:

None

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)

See also

  • smarter.apps.account.models.UserProfile

Setter accepts:

UserProfile

cache_invalidations()[source]

Invalidate any relevant caches for the brokered user.

Invalidates the cached UserProfile of the brokered user in each account they belong to, which with spec.accounts need not include the current account.

Return type:

None

check_authority_over_memberships(command)[source]

Refuse spec.accounts that list an account which the applier doesn’t administer, unless a superuser applies it.

Parameters:

command (SmarterJournalCliCommands) – The command, for the error.

Raises:

SAMUserBrokerError – if a listed account isn’t one that the applier administers.

Return type:

None

check_authority_over_user(command)[source]

Refuse a User manifest that reaches beyond the applier’s own account, unless a superuser applies it.

A user is found by username across the whole platform. So an account administrator could otherwise change a user of another account, e.g. their email, or deactivate them. And isStaff sets User.is_staff, which opens the Django admin site and administers every account the user belongs to, so an administrator of one account, through UserProfile.is_account_admin, could otherwise make themselves staff.

passwordSecret sets the user’s password, so only a superuser may use it: an account’s administrator could otherwise take over a user who also belongs to other accounts, e.g. a company’s chief executive.

Parameters:

command (SmarterJournalCliCommands) – The command, for the error.

Raises:

SAMUserBrokerError – if an existing user doesn’t belong to the applier’s account, a user who isn’t staff would change a user’s is_staff, or anyone but a superuser sets passwordSecret.

Return type:

None

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.

dependencies()[source]

Return brokers for the resources that this User owns.

Deleting a User also deletes every resource that it owns, so they must be deleted, or moved to another owner, first.

Returns:

A broker for each resource that the User owns.

Return type:

List[AbstractBroker | SAMDependencyReference]

classmethod dependents(instance)[source]

Return the resources that a User owns.

Deleting a User also deletes every resource that it owns, so they must be deleted, or moved to another owner, first.

Parameters:

instance (User) – The User.

Returns:

The resources of each kind that the User owns. Its plugins have their own kinds.

Return type:

List[Tuple[str | None, Iterable[Model]]]

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.

deployable: ClassVar[bool] = True

True when the broker implements deploy().

The cli api’s resources command reports it as each kind’s Deployable, and the smarter cli offers deploy and undeploy commands for those kinds. A broker that sets it must override deploy(); undeploy() may still raise SAMBrokerErrorNotImplemented, as CustomDomain’s and LLMHostCompute’s do.

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:

dict[str, Any] | None

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 client’s manifest data.

Warning

If the manifest data or its 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[str, Any]

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

memberships_for_manifest()[source]

The brokered user’s memberships, for describe: every one, but only for a superuser.

Anyone else sees the user as a member of the current account only, without spec.accounts, so that a user’s other accounts aren’t shown to the administrators of one of them.

Return type:

list[SAMUserAccountMembership] | None

Returns:

The memberships, or None.

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

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

Attention

this is not implemented for the Smarter API User manifest.

Raises:

SAMBrokerErrorNotImplemented Always raised to indicate that the prompt 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.

classmethod references(instance)[source]

Return the resources that a User uses: none.

Parameters:

instance (User) – The User.

Returns:

An empty list.

Return type:

List[Tuple[str | None, Iterable[Model]]]

set_password_from_secret(brokered_user, secret_name)[source]

Set the user’s password to the value of the Secret that passwordSecret names.

The Secret is found by name as other references are, nearest first, from the applier’s profile. Its value is never logged.

Parameters:
  • brokered_user (User) – The user, not yet saved.

  • secret_name (str) – The Secret’s name.

Raises:

SAMBrokerErrorNotFound – if no Secret of that name may be read, or it has no value.

Return type:

None

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

The label of this error, used in its string form.