# pylint: disable=W0613
"""Account UserProfile model."""
import os
import uuid
from typing import Any, Optional, Sequence, TypeVar, overload
from urllib.parse import urljoin
from cache_results import cache_results
# django stuff
from django.conf import settings
from django.contrib.auth.models import User
from django.db import models
from django.db.models import Manager, QuerySet
from django.db.models.expressions import Combinable
from django.db.models.query import Prefetch
from django.templatetags.static import static
from django.utils import translation
# our stuff
from smarter.apps.account.profile_selection import selected_user_profile_id
from smarter.apps.account.signals import new_user_created
from smarter.common.conf import smarter_settings
from smarter.common.exceptions import SmarterValueError
from smarter.common.utils import mask_email
from smarter.lib import logging
from smarter.lib.django.models import MetaDataModel
from smarter.lib.django.validators import SmarterValidator
from smarter.lib.django.waffle import SmarterWaffleSwitches
from .account import Account
from .account_contact import AccountContact
HERE = os.path.abspath(os.path.dirname(__file__))
_GenericTypeVar = TypeVar("_GenericTypeVar", bound="models.Model")
"""
Generic Manager Type variable bound to any Django Model, so that it.
its associated Manager can be type hinted to return the correct model type.
Used for type hinting in the custom queryset and manager to ensure methods
return the correct model type.
.. seealso::
- django-stubs: Custom QuerySets <https://github.com/typeddjango/django-stubs>_
"""
logger = logging.getSmarterLogger(__name__, any_switches=[SmarterWaffleSwitches.ACCOUNT_LOGGING])
DEFAULT_PROFILE_IMAGE = "images/avatars/default-profile.svg"
"""The static file shown for a user who has neither uploaded a profile image nor received one via oauth."""
def profile_image_upload_to(instance: "UserProfile", filename: str) -> str:
"""
Return the storage path of an uploaded profile image.
The file is renamed to a random uuid, keeping only its extension, so that the
public url of the image reveals nothing about the user or the original file,
and a new upload never collides with, or is cached as, an earlier one.
:param instance: The UserProfile that the image belongs to.
:type instance: UserProfile
:param filename: The name of the uploaded file.
:type filename: str
:returns: The path within the default storage, e.g. ``account/profile_images/<uuid>.png``.
:rtype: str
"""
extension = os.path.splitext(filename)[1].lower()
return f"account/profile_images/{uuid.uuid4().hex}{extension}"
[docs]
class SmarterBaseQuerySetWithPermissions(QuerySet[_GenericTypeVar]):
"""
Custom queryset for permission-based resource filtering by user profile.
This queryset adds permission-aware filtering for resources owned by a specific user profile.
.. seealso::
- Django: Creating a manager with QuerySet methods <https://docs.djangoproject.com/en/6.0/topics/db/managers/#creating-a-manager-with-queryset-methods>_
- django-stubs: Custom QuerySets <https://github.com/typeddjango/django-stubs>_
"""
[docs]
def with_read_permission_for(self, user: User) -> "SmarterBaseQuerySetWithPermissions[_GenericTypeVar]":
"""
A pipeline for filtering a queryset of this resource based on the permissions of the authenticated user in the given request.
Return a queryset of this resource if the user has permission to read it,
or an empty queryset if not.
:param user: :class:`django.contrib.auth.models.User`
The user to check.
:param queryset: Optional[:class:`django.db.models.QuerySet`]
An optional queryset to filter. If not provided, the method will default to filtering all instances
:returns: :class:`django.db.models.QuerySet`
A queryset of this resource if the user has permission to read it, or an empty queryset
if not.
"""
logger.debug(
"called for user: %s",
user,
)
if user.is_superuser:
logger.debug(
"user is superuser, returning all resources.",
)
return self.all()
return self.none()
[docs]
def with_ownership_permission_for(self, user: User) -> "SmarterBaseQuerySetWithPermissions[_GenericTypeVar]":
"""
Returns a queryset of resources that the authenticated user in the given request has full management (ownership) permission for.
Only users with staff or superuser status are permitted to manage resources.
:param user: :class:`django.contrib.auth.models.User`
The user to check.
:returns: :class:`django.db.models.QuerySet`
A queryset of this resource if the user has permission to fully manage it, or an empty queryset if not.
"""
logger.debug(
"called for user: %s",
user,
)
if not isinstance(user, User):
logger.debug(
"user is not an instance of User: %s",
user,
)
return self.none()
if user.is_superuser:
logger.debug(
"user is superuser, returning all resources.",
)
return self.all()
return self.none()
[docs]
class SmarterBaseModelManager(Manager[_GenericTypeVar]):
"""
Custom manager for MetaDataWithOwnershipModel that returns a.
SmarterBaseQuerySetWithPermissions to enable permission-based filtering by
user_profile.
"""
# --------------------------------------------------------------------------
# Override base Manager methods to return SmarterBaseQuerySetWithPermissions
# to ensure all queries go through the permission-aware queryset.
# --------------------------------------------------------------------------
[docs]
def get_queryset(self) -> SmarterBaseQuerySetWithPermissions[_GenericTypeVar]:
"""Returns a SmarterBaseQuerySetWithPermissions for the model."""
return SmarterBaseQuerySetWithPermissions(self.model, using=self._db)
[docs]
def filter(self, *args, **kwargs) -> SmarterBaseQuerySetWithPermissions[_GenericTypeVar]:
"""Returns a SmarterBaseQuerySetWithPermissions with the applied filter."""
return self.get_queryset().filter(*args, **kwargs)
[docs]
def exclude(self, *args, **kwargs) -> SmarterBaseQuerySetWithPermissions[_GenericTypeVar]:
"""Returns a SmarterBaseQuerySetWithPermissions with the applied exclusion."""
return self.get_queryset().exclude(*args, **kwargs)
[docs]
def none(self) -> SmarterBaseQuerySetWithPermissions[_GenericTypeVar]:
"""Returns an empty SmarterBaseQuerySetWithPermissions."""
return self.get_queryset().none()
[docs]
def complex_filter(self, filter_obj) -> SmarterBaseQuerySetWithPermissions[_GenericTypeVar]:
"""Returns a SmarterBaseQuerySetWithPermissions with the applied complex filter."""
return self.get_queryset().complex_filter(filter_obj)
# pylint: disable=W0622
[docs]
def union(self, *other_qs, all=False) -> SmarterBaseQuerySetWithPermissions[_GenericTypeVar]:
"""Returns a SmarterBaseQuerySetWithPermissions representing the union of querysets."""
return self.get_queryset().union(*other_qs, all=all)
[docs]
def intersection(self, *other_qs) -> SmarterBaseQuerySetWithPermissions[_GenericTypeVar]:
"""Returns a SmarterBaseQuerySetWithPermissions representing the intersection of querysets."""
return self.get_queryset().intersection(*other_qs)
[docs]
def difference(self, *other_qs) -> SmarterBaseQuerySetWithPermissions[_GenericTypeVar]:
"""Returns a SmarterBaseQuerySetWithPermissions representing the difference of querysets."""
return self.get_queryset().difference(*other_qs)
[docs]
def select_for_update(
self, nowait: bool = False, skip_locked: bool = False, of: Sequence[str] = (), no_key: bool = False
) -> SmarterBaseQuerySetWithPermissions[_GenericTypeVar]:
"""Returns a SmarterBaseQuerySetWithPermissions with select_for_update applied."""
return self.get_queryset().select_for_update(nowait=nowait, skip_locked=skip_locked, of=of, no_key=no_key)
@overload
def select_related(self, clear: None, /) -> SmarterBaseQuerySetWithPermissions[_GenericTypeVar]: ...
@overload
def select_related(self, *fields: str) -> SmarterBaseQuerySetWithPermissions[_GenericTypeVar]: ...
@overload
def prefetch_related(self, clear: None, /) -> SmarterBaseQuerySetWithPermissions[_GenericTypeVar]: ...
@overload
def prefetch_related(self, *lookups: str | Prefetch) -> SmarterBaseQuerySetWithPermissions[_GenericTypeVar]: ...
[docs]
def annotate(self, *args: Any, **kwargs: Any) -> SmarterBaseQuerySetWithPermissions[_GenericTypeVar]:
"""Returns a SmarterBaseQuerySetWithPermissions with annotate applied."""
return self.get_queryset().annotate(*args, **kwargs)
[docs]
def alias(self, *args: Any, **kwargs: Any) -> SmarterBaseQuerySetWithPermissions[_GenericTypeVar]:
"""Returns a SmarterBaseQuerySetWithPermissions with alias applied."""
return self.get_queryset().alias(*args, **kwargs)
[docs]
def order_by(self, *field_names: str | Combinable) -> SmarterBaseQuerySetWithPermissions[_GenericTypeVar]:
"""Returns a SmarterBaseQuerySetWithPermissions with order_by applied."""
return self.get_queryset().order_by(*field_names)
[docs]
def distinct(self, *field_names: str) -> SmarterBaseQuerySetWithPermissions[_GenericTypeVar]:
"""Returns a SmarterBaseQuerySetWithPermissions with distinct applied."""
return self.get_queryset().distinct(*field_names)
# --------------------------------------------------------------------------
# Custom permission-based queryset methods for filtering by user_profile
# read and ownership permissions.
# --------------------------------------------------------------------------
[docs]
def with_read_permission_for(self, user: User) -> SmarterBaseQuerySetWithPermissions[_GenericTypeVar]:
"""
A custom Smarter pipeline for filtering any MetaDataWithOwnership queryset based on the Smarter permissions scheme for the authenticated user in the given request.
Returns a queryset of the resource if the user has permission to read it,
or an empty queryset if not.
Permission logic:
- If the user is not authenticated, they have no access.
- If the user is a superuser, they have access to all resources.
- If the user is a regular authenticated user, they have access to resources that are:
- Owned by their UserProfile, OR
- Owned by their Account admin UserProfile, OR
- Owned by the Smarter admin UserProfile.
:param user: :class:`django.contrib.auth.models.User`
The user to check.
:param queryset: Optional[:class:`django.db.models.QuerySet`]
An optional queryset to filter. If not provided, the method will default to filtering all instances
:returns: :class:`django.db.models.QuerySet`
A queryset of this resource if the user has permission to read it, or an empty queryset
if not.
"""
logger.debug(
"called for user: %s",
user,
)
return self.get_queryset().with_read_permission_for(user)
[docs]
def with_ownership_permission_for(self, user: User) -> SmarterBaseQuerySetWithPermissions[_GenericTypeVar]:
"""
Returns a queryset of resources that the authenticated user in the given request has full management (ownership) permission for.
Permission logic:
- If the user is not authenticated, they have no access.
- If the user is a superuser, they have ownership permission for all resources.
- If the user is a staff user, they have ownership permission for resources that are:
- Owned by their UserProfile, OR
- Owned by any UserProfile within their Account.
- If the user is a regular authenticated user, they have ownership permission only for resources they own.
:param user: :class:`django.contrib.auth.models.User`
The user to check.
:returns: :class:`django.db.models.QuerySet`
A queryset of this resource if the user has permission to fully manage it, or an empty queryset if not.
"""
logger.debug(
"called for user: %s",
user,
)
return self.get_queryset().with_ownership_permission_for(user)
def active_language() -> str:
"""
Return the active language, as a code of ``settings.LANGUAGES``.
During a request, this is the language that Django's ``LocaleMiddleware`` chose for the web
console: the language cookie's, or else the best match for the browser's ``Accept-Language``
header. A console sign-up stores it as the new :attr:`UserProfile.language`. Outside a request,
or for a language that isn't in ``settings.LANGUAGES``, it is ``settings.LANGUAGE_CODE``.
:returns: The language code, e.g. ``en``, ``es`` or ``pt-br``.
"""
try:
return translation.get_supported_language_variant(translation.get_language() or settings.LANGUAGE_CODE)
except LookupError:
return settings.LANGUAGE_CODE
[docs]
def user_administers_account(user: object, user_profile: Optional["UserProfile"]) -> bool:
"""
Whether a user administers an account: manages every resource in it.
A superuser administers every account. A user with ``User.is_staff`` administers each account they belong to,
which is how an account's administrator has been marked, and which also opens the Django admin site, and no
other: staff of one account have no say in another, so their own profile in the account is required, as for
anyone else. A user whose own profile in the account has ``is_account_admin`` administers that account only,
and opens nothing else: the role for a department's administrator in an organization of several accounts
(ADR-036).
:param user: The user, e.g. a request's. None, or an anonymous user, administers nothing.
:param user_profile: The user's profile in the account, if any. None, or a profile of another user, makes
anyone but a superuser administer nothing.
:returns: True if the user may manage every resource of the account.
"""
if user is None:
return False
# "is True", so that only a real flag counts, never e.g. a test double's automatic attribute.
if getattr(user, "is_superuser", False) is True:
return True
if user_profile is None:
return False
user_pk = getattr(user, "pk", None)
if user_pk is None:
return False
if user_profile.user_id != user_pk: # type: ignore[attr-defined]
return False
if getattr(user, "is_staff", False) is True:
return True
retval = bool(user_profile.is_account_admin)
return retval
[docs]
class UserProfile(MetaDataModel):
"""
UserProfile model for associating Django users with Smarter accounts.
Establishes a link between a Django User and an Account, enabling centralized management of billing, identity, and resource ownership.
:param user: ForeignKey to :class:`django.contrib.auth.models.User`. The user associated with this profile.
:param account: ForeignKey to :class:`Account`. The related Smarter account.
:param profile_image_url: URLField. The profile image that the oauth provider supplied at login.
:param profile_image: ImageField. The profile image that the user uploaded. Takes precedence over ``profile_image_url``.
:param is_test: Boolean. Indicates if this profile is for testing purposes.
:param welcomed_at: DateTimeField. When the user closed the web console's welcome dialog, or ``None`` if they
haven't seen it yet. See :mod:`smarter.apps.dashboard.views.views.api.welcome`.
:param language: CharField. The user's preferred language, a code of ``settings.LANGUAGES``, e.g. ``es``.
Defaults to English. The emails that the user is sent, such as the welcome email, are written in it. A
console sign-up stores the language of the sign-up request (see :func:`active_language`).
.. important::
The combination of `user` and `account` must be unique. Duplicate profiles for the same user and account are not allowed.
**Example usage**::
from smarter.apps.account.models import UserProfile
profile = UserProfile.objects.create(user=user, account=account)
profile.add_to_account_contacts(is_primary=True)
"""
# pylint: disable=missing-class-docstring
class Meta:
constraints = [
models.UniqueConstraint(fields=["user", "account"], name="account_userprofile_unique"),
]
objects: SmarterBaseModelManager = SmarterBaseModelManager()
# Add more fields here as needed
user = models.ForeignKey(
User,
on_delete=models.CASCADE,
related_name="user_profile",
)
account = models.ForeignKey(Account, on_delete=models.CASCADE, related_name="user_profiles")
profile_image_url = models.URLField(
blank=True, null=True, help_text="URL to the user's profile image, provided via oauth."
)
profile_image = models.ImageField(
upload_to=profile_image_upload_to,
blank=True,
null=True,
help_text="The user's own profile image, uploaded in the web console. Takes precedence over profile_image_url.",
)
is_test = models.BooleanField(
default=False, help_text="Indicates if this profile is used for unit testing purposes."
)
is_account_admin = models.BooleanField(
default=False,
help_text=(
"Whether the user administers this account, and only this one: they manage every resource in it. "
"Unlike User.is_staff, it gives no access to the Django admin site, and no rights in the user's other accounts."
),
)
welcomed_at = models.DateTimeField(
blank=True,
null=True,
help_text="When the user first closed the web console's welcome dialog. Empty until they have seen it.",
)
show_welcome_at_startup = models.BooleanField(
default=False,
help_text=(
"Whether the web console's welcome dialog opens by itself each time the user signs in: "
"its Show at startup box. Unticked, it opens by itself only until the user first closes it."
),
)
language = models.CharField(
max_length=10,
choices=settings.LANGUAGES,
default=settings.LANGUAGE_CODE,
help_text="The user's preferred language, in which they are sent emails, e.g. the welcome email.",
)
console_language = models.CharField(
max_length=10,
choices=settings.LANGUAGES,
blank=True,
default="",
help_text=(
"The language that the user chose in the web console's language menu, which the console restores "
"when the browser has no language cookie, e.g. on another device. Empty until they choose one."
),
)
@property
def administers_account(self) -> bool:
"""
Whether this profile's user administers its account: manages every resource in it.
See :func:`user_administers_account`.
:returns: True if the user may manage every resource of this profile's account.
"""
retval = user_administers_account(self.user, self)
return retval
@property
def avatar_url(self) -> str:
"""
Return the url of the image that represents this user in the web console.
In order of precedence: the image that the user uploaded, the image that
the oauth provider (Google, GitHub, LinkedIn) supplied at login, and the
default profile image.
An uploaded image's ``url`` is absolute under S3, but a relative path
under FileSystemStorage (no AWS configured), which is joined onto
``smarter_settings.environment_url``.
:returns: An absolute url, or the static url of the default profile image.
:rtype: str
**Example usage**::
<img src="{{ user_profile.avatar_url }}" />
"""
if self.profile_image:
url = self.profile_image.url
if SmarterValidator.is_valid_url(url):
return url
return urljoin(smarter_settings.environment_url, url)
if self.profile_image_url:
return self.profile_image_url
return static(DEFAULT_PROFILE_IMAGE)
@property
def cached_user(self) -> User:
"""
Retrieve the associated User instance with caching.
This significantly reduces the number of database queries when accessing
the user from the user profile.
:returns: User
The associated User instance.
**Example usage**::
user = profile.cached_user
if user:
print(user.email)
"""
if not UserProfile.user.is_cached(self): # type: ignore[attr-defined]
# pylint: disable=import-outside-toplevel
from smarter.apps.account.utils import get_cached_user_for_user_id
self.user = get_cached_user_for_user_id(user_id=self.user_id) # type: ignore[attr-defined]
return self.user
@property
def cached_account(self) -> Account:
"""
Retrieve the associated Account instance with caching.
This significantly reduces the number of database queries
when accessing the account from the user profile.
:returns: Account
The associated Account instance.
**Example usage**::
account = user_profile.cached_account
if account:
print(account.company_name)
"""
if not UserProfile.account.is_cached(self): # type: ignore[attr-defined]
self.account = Account.get_cached_object(pk=self.account_id) # type: ignore[attr-defined]
return self.account
[docs]
def save(self, *args, **kwargs):
"""
Save the UserProfile instance and ensure account contacts are updated.
This method validates that both `user` and `account` are set, saves the profile, and, if newly created,
adds the user to the account's contact list. It also emits a signal for new user creation.
:param args: Positional arguments passed to the parent save method.
:param kwargs: Keyword arguments passed to the parent save method.
.. note::
On first save, ensures at least one primary contact exists for the account.
**Example usage**::
profile.save()
"""
logger.debug(
"called for UserProfile with user: %s and account: %s",
self.user,
self.account,
)
is_new = self.pk is None
if self.user is None or self.account is None:
raise SmarterValueError("User and Account cannot be null")
super().save(*args, **kwargs)
if is_new:
# ensure that at least one person is on the account contact list
is_primary = AccountContact.objects.filter(account=self.account, is_primary=True).count() == 0
self.add_to_account_contacts(is_primary=is_primary)
new_user_created.send(sender=self.__class__, user_profile=self)
else:
orig = UserProfile.objects.get(pk=self.pk)
if orig.account != self.account or orig.user != self.user:
raise SmarterValueError("Cannot change the account or user of an existing UserProfile")
[docs]
@classmethod
def admin_for_account(cls, account: Account) -> User:
"""
Return the designated user for the given account.
This method finds the first administrator of the account, by ``is_account_admin`` or ``User.is_staff``. If
there is none, it returns the first available user. If the account has no users, it creates an administrator
of the account's own, with :func:`~smarter.apps.account.utils.get_cached_admin_user_for_account`, and never
adds the platform's admin to it.
:param account: Instance of :class:`Account`. The account for which to find the designated user.
:returns: :class:`django.contrib.auth.models.User`
The designated user for the account.
.. attention::
If no staff or regular users exist for the account, an admin user is automatically created. You must set the password manually.
.. error::
Logs an error if no admin or user is found for the account.
**Example usage**::
user = UserProfile.admin_for_account(account)
.. seealso::
:class:`UserProfile`
"""
@cache_results(cls.cache_expiration)
def _get_admin_for_account(account_id: int, class_name: str) -> Optional[User]:
# the account's administrators: by UserProfile.is_account_admin, or by User.is_staff.
admins = cls.objects.filter(account_id=account_id).filter(
models.Q(is_account_admin=True) | models.Q(user__is_staff=True)
)
first_admin = admins.order_by("user__id").first()
if first_admin is not None:
return first_admin.user
logger.error(
"No admin found for account %s",
account,
)
users = cls.objects.filter(account_id=account_id).order_by("user__id")
first_user = users.first()
if first_user is not None:
return first_user.user
logger.error(
"No user for account %s",
account,
)
# an account without members gets an administrator of its own, never the platform's admin, who would
# otherwise belong to every such account.
# pylint: disable=C0415
from smarter.apps.account.utils import get_cached_admin_user_for_account
admin_user = get_cached_admin_user_for_account(account=account) # type: ignore[arg-type]
logger.warning(
"Created an administrator for account %s.",
account,
)
return admin_user
return _get_admin_for_account(account_id=account.id, class_name=UserProfile.__name__) # type: ignore[return-value]
[docs]
@classmethod
def get_selected_object(cls, user_id: Optional[int]) -> Optional["UserProfile"]:
"""
Return the UserProfile that the user chose in the web console's user menu, if any.
A user with more than one UserProfile can choose which one the console acts as, with the user
menu's **Change Profile** item, which stores its id in the session. For the length of a request,
the id is in :data:`~smarter.apps.account.profile_selection.selected_user_profile_id`. See
:mod:`smarter.apps.account.profile_selection`.
:param user_id: The primary key of the user whose profile is being resolved.
:type user_id: Optional[int]
:returns: The chosen UserProfile, or ``None`` if the request has no choice, the user is another
user, or the chosen profile no longer exists.
:rtype: Optional[UserProfile]
**Example usage**::
user_profile = UserProfile.get_selected_object(request.user.pk) or newest_user_profile
"""
profile_id = selected_user_profile_id.get()
if not profile_id or not user_id:
return None
try:
user_profile = cls.get_cached_object(pk=profile_id)
except cls.DoesNotExist:
logger.debug(
"the chosen UserProfile %s no longer exists",
profile_id,
)
return None
if user_profile.user_id != user_id: # type: ignore[attr-defined]
return None
return user_profile
[docs]
@classmethod
def get_cached_object(
cls,
*args,
invalidate: Optional[bool] = False,
pk: Optional[int] = None,
name: Optional[str] = None,
user: Optional[User] = None,
username: Optional[str] = None,
account: Optional[Account] = None,
**kwargs,
) -> "UserProfile":
"""
Retrieve a model instance by primary key or name, using caching to optimize performance.
This method is selectively overridden in models that inherit from MetaDataModel to provide class-specific
function parameters.
Given a ``user`` (or ``username``) and no ``account``, it returns the profile that the user chose in
the web console's user menu, for this request (see :meth:`get_selected_object`), else the user's
newest profile.
Example usage:
.. code-block:: python
# Retrieve by primary key
instance = MyModel.get_cached_object(pk=1)
# Retrieve by name
instance = MyModel.get_cached_object(name="exampleName")
:param pk: The primary key of the model instance to retrieve.
:param name: The name of the model instance to retrieve.
:returns: The model instance if found, otherwise None.
:rtype: Optional["UserProfile"]
"""
# the cached functions take ids, not model instances: an argument is part of the cache key,
# and a key must be built from plain values.
@cache_results(cls.cache_expiration)
def _get_object_by_user_and_account(
user_id: Optional[int], account_id: Optional[int], class_name: str = cls.__name__
) -> "UserProfile":
logger.debug(
"called with pk: %s, name: %s, user_id: %s, username: %s, account_id: %s, invalidate: %s",
pk,
name,
user_id,
username,
account_id,
invalidate,
)
try:
retval = (
UserProfile.objects.prefetch_related("tags")
.select_related("user", "account")
.get(user_id=user_id, account_id=account_id)
)
logger.debug(
"fetched %s for user_id: %s and account_id: %s",
cls.__name__,
user_id,
account_id,
)
_ = retval.user
_ = retval.account
return retval
except UserProfile.DoesNotExist as e:
logger.debug(
"no %s found for user_id: %s, account_id: %s",
UserProfile.__name__,
user_id,
account_id,
)
raise UserProfile.DoesNotExist(f"No UserProfile found for user {user} and account {account}") from e
@cache_results(cls.cache_expiration)
def _get_object_by_user(user_id: Optional[int], class_name: str = cls.__name__) -> "UserProfile":
try:
retval = (
UserProfile.objects.prefetch_related("tags").select_related("user", "account").get(user_id=user_id)
)
logger.debug(
"fetched %s for user_id: %s",
cls.__name__,
user_id,
)
_ = retval.user
_ = retval.account
return retval
except UserProfile.DoesNotExist as e:
logger.debug(
"no %s found for user_id: %s",
UserProfile.__name__,
user_id,
)
raise UserProfile.DoesNotExist(f"No UserProfile found for user {user} and account {account}") from e
except UserProfile.MultipleObjectsReturned as e:
retval = (
UserProfile.objects.prefetch_related("tags")
.select_related("user", "account")
.filter(user_id=user_id)
.order_by("-pk")
.first()
)
# A user has one UserProfile per account, so this is expected:
# without an account, the newest profile is the user's default.
logger.debug(
"user_id %s has more than one UserProfile. Defaulting to the newest: %s",
user_id,
retval,
)
if not retval:
raise UserProfile.DoesNotExist(
f"No UserProfile found for user {user} and account {account} after MultipleObjectsReturned exception."
) from e
return retval
@cache_results(cls.cache_expiration)
def _get_object_by_account(
account_id: Optional[int], class_name: str = cls.__name__
) -> Optional["UserProfile"]:
admin_user = None
try:
# account is the instance whose id is account_id: the caller passes account.pk.
admin_user = UserProfile.admin_for_account(account) # type: ignore[arg-type]
retval = (
UserProfile.objects.prefetch_related("tags")
.select_related("user", "account")
.get(account_id=account_id, user=admin_user)
)
logger.debug(
"fetched %s for account admin %s",
UserProfile.__name__,
retval,
)
_ = retval.user
_ = retval.account
return retval
except UserProfile.DoesNotExist:
logger.debug(
"no %s found for account admin %s",
UserProfile.__name__,
admin_user,
)
return None
except UserProfile.MultipleObjectsReturned:
logger.error(
"Multiple UserProfiles found for account_id %s. Defaulting to first result.",
account_id,
)
return (
UserProfile.objects.prefetch_related("tags")
.select_related("user", "account")
.filter(account_id=account_id)
.first()
)
if username and not user:
try:
user = User.objects.get(username=username)
logger.debug(
"fetched user by username: %s",
username,
)
except User.DoesNotExist as e:
logger.error(
"No user found with username %s.",
username,
)
raise User.DoesNotExist(f"No user found with username {username}") from e
user_id = user.pk if user else None
account_id = account.pk if account else None
# an argument that wasn't given is None: its lookup never cached anything, so there is nothing to invalidate.
if invalidate:
_get_object_by_user_and_account.invalidate(
user_id=user_id, account_id=account_id, class_name=UserProfile.__name__
)
_get_object_by_user.invalidate(user_id=user_id, class_name=UserProfile.__name__)
_get_object_by_account.invalidate(account_id=account_id, class_name=UserProfile.__name__)
if user or account:
# None when only an account is given, and it has no admin profile. Callers test the
# result, although the signature says UserProfile.
retval: Optional[UserProfile]
if user and account:
retval = _get_object_by_user_and_account(user_id, account_id, UserProfile.__name__)
elif user:
# the profile that the user chose in the user menu, else their newest one.
retval = cls.get_selected_object(user_id) or _get_object_by_user(
user_id=user_id, class_name=UserProfile.__name__
)
else:
retval = _get_object_by_account(account_id=account_id, class_name=UserProfile.__name__)
return retval # type: ignore[return-value]
return super().get_cached_object(*args, invalidate=invalidate, pk=pk, name=name, **kwargs) # type: ignore[return-value]
[docs]
@classmethod
def get_cached_objects(
cls, invalidate: Optional[bool] = False, user: Optional[User] = None, **kwargs
) -> QuerySet["UserProfile"]:
"""
Retrieve a queryset of UserProfile instances associated with the given user, using caching to optimize performance.
:param invalidate: Boolean. If True, invalidates the cache for the user's profiles before retrieving.
:param user: Optional[User]. If provided, retrieves profiles associated with this user. If not provided, retrieves all profiles.
:returns: QuerySet[UserProfile]. A queryset of UserProfile instances associated with the
given user, or all profiles if no user is specified.
:rtype: QuerySet[UserProfile]
"""
@cache_results(cls.cache_expiration)
def _get_objects_by_user(user_id: int, class_name: str = cls.__name__) -> QuerySet["UserProfile"]:
logger.debug(
"called with invalidate: %s, user: %s, kwargs: %s",
invalidate,
user,
kwargs,
)
retval = UserProfile.objects.prefetch_related("tags").select_related("user", "account").filter(user=user)
logger.debug(
"fetched %s objects for user_id: %s. count: %s",
cls.__name__,
user_id,
len(retval),
)
return retval
if isinstance(user, User):
if invalidate:
_get_objects_by_user.invalidate(user_id=user.id, class_name=UserProfile.__name__) # type: ignore[call-arg]
return _get_objects_by_user(user_id=user.id, class_name=UserProfile.__name__) # type: ignore[return-value]
return super().get_cached_objects() # type: ignore[return-value]
def __str__(self) -> str:
"""
The profile's string form, e.g. ``pk=42 ****Corp-j****@example.com``.
It is written to logs, so the company name and the user's email are masked with
:meth:`~smarter.common.mixins.helper_mixin.SmarterHelperMixin.mask_string` and
:func:`~smarter.common.utils.mask_email`.
The pk identifies the row.
"""
user_identifier = "NoUser"
company_name = "NoAccount"
try:
if self.user and self.user.email:
user_identifier = mask_email(self.user.email)
elif self.user:
user_identifier = self.user.username
else:
user_identifier = "NoUser"
if self.account:
company_name = self.mask_string(self.account.company_name or "")
except User.DoesNotExist:
pass
except Account.DoesNotExist:
pass
return f"pk={self.pk} {company_name}-{user_identifier}"
def __repr__(self) -> str:
return f"<{self.__class__.__name__} pk={self.pk} user_id={self.user_id} account_id={self.account_id}>" # type: ignore[attr-defined]
__all__ = ["UserProfile", "SmarterBaseModelManager", "SmarterBaseQuerySetWithPermissions", "user_administers_account"]