Source code for smarter.apps.account.utils

"""
Account Utilities.

This module provides foundational utilities for accessing, managing, and caching account and user data in the Smarter platform. It is the base model for all Django ORM operations in the project, and is designed for both performance and reliability.

Caching Overview
----------------

Two caching strategies are used:

- **LRU In-Memory Caching**:
  Fast, per-process caching for frequently accessed objects such as `User`, `Account`, and `UserProfile`.
  *Scope*: Only available within the current process; short-lived.

- **Redis-Based ORM Caching**:
  Persistent, cross-process caching for Django ORM objects.
  *Scope*: Shared across all processes; cache lifetime is controlled by expiration settings.
"""

import re
from typing import Optional, Union

from cache_results import cache_results
from django.contrib.auth.models import AnonymousUser
from django.db.models import Q
from django.templatetags.static import static
from typing_extensions import deprecated

from smarter.apps.account.models import (
    Account,
    User,
    UserProfile,
)
from smarter.apps.account.models.user_profile import DEFAULT_PROFILE_IMAGE
from smarter.common.conf import smarter_settings
from smarter.common.const import SMARTER_ACCOUNT_NUMBER
from smarter.common.exceptions import SmarterConfigurationError, SmarterValueError
from smarter.lib import logging
from smarter.lib.django.validators import SmarterValidator
from smarter.lib.django.waffle import SmarterWaffleSwitches

logger = logging.getSmarterLogger(
    __name__, any_switches=[SmarterWaffleSwitches.ACCOUNT_LOGGING, SmarterWaffleSwitches.CACHE_LOGGING]
)

LRU_CACHE_MAX_SIZE = 128
SMARTER_ACCOUNT_NUMBER_PATTERN = re.compile(SmarterValidator.SMARTER_ACCOUNT_NUMBER_REGEX)


# commonly fetched objects
# ----------------------------
# pylint: disable=W0613
class SmarterCachedObjects:
    """
    Lazy instantiations of cached objects for the smarter account.

    This is a
    much-simplified means of caching commonly used objects without having to
    actually decorate every function that fetches them.

    :raises SmarterConfigurationError: If the smarter account or admin user cannot be found.

    .. note::

           This class uses lazy loading to fetch and cache the smarter account
           and admin user only when accessed.
    """

    _smarter_admin_user_profile: Optional[UserProfile] = None
    _admin_user: Optional[User] = None

    def __init__(self):
        self.base_cache_key = f"{__name__}.{SmarterCachedObjects.__name__}[{id(self)}]"

    @property
    def smarter_account(self) -> Account:
        """
        Retrieve the smarter account instance.

        :returns: Account instance representing the smarter account.
        :raises SmarterConfigurationError: If the smarter account cannot be found.
        """
        retval = Account.get_cached_object(account_number=SMARTER_ACCOUNT_NUMBER)
        if not retval:
            raise SmarterConfigurationError(
                f"Smarter account with account number {SMARTER_ACCOUNT_NUMBER} does not exist."
            )
        return retval

    @property
    def smarter_admin(self) -> User:
        """
        Retrieve the smarter admin user instance.

        :returns: User instance representing the smarter admin.
        :raises SmarterConfigurationError: If the smarter admin user cannot be found.
        """
        return self.smarter_admin_user_profile.user

    @property
    def smarter_admin_user_profile(self) -> UserProfile:
        """
        Retrieve the UserProfile instance for the smarter admin user.

        Lazy loads and caches the UserProfile on first access.
        Subsequent accesses will return the cached UserProfile, with a
        periodic refresh from the database to ensure data consistency.

        :returns: UserProfile instance for the smarter admin user.
        :raises SmarterConfigurationError: If the UserProfile cannot be found.
        """

        @cache_results(cache_key=self.base_cache_key + ".smarter_admin_user_profile")
        def _requery_smarter_admin_user_profile(class_name=SmarterCachedObjects.__name__) -> None:
            if isinstance(self._smarter_admin_user_profile, UserProfile):
                logger.debug(
                    "re-queried %s",
                    self._smarter_admin_user_profile,
                )
                try:
                    self._smarter_admin_user_profile.refresh_from_db()
                except UserProfile.DoesNotExist:
                    self._smarter_admin_user_profile = None
                    _requery_smarter_admin_user_profile.invalidate(class_name=SmarterCachedObjects.__name__)

        if not self._smarter_admin_user_profile:
            try:
                user_profile = (
                    UserProfile.objects.filter(account=self.smarter_account).filter(user__is_superuser=True).first()
                )
                self._smarter_admin_user_profile = user_profile
                logger.debug(
                    "initialized %s",
                    user_profile,
                )
                return self._smarter_admin_user_profile  # type: ignore[return-value]
            except UserProfile.DoesNotExist as e:
                raise SmarterConfigurationError("No superuser user profile found for smarter account") from e

        _requery_smarter_admin_user_profile(class_name=SmarterCachedObjects.__name__)
        return self._smarter_admin_user_profile  # type: ignore[return-value]

    @property
    def admin_user(self) -> User:
        """
        Retrieve the admin user instance for the smarter account.

        Lazy
        loads and caches the user on first access. Subsequent accesses
        will return the cached user, with a periodic refresh from the
        database to ensure data consistency.

        :returns: User instance representing the admin user.
        :raises SmarterConfigurationError: If the admin user cannot be found.
        """

        @cache_results(cache_key=self.base_cache_key + ".admin_user")
        def _requery_admin_user(class_name=SmarterCachedObjects.__name__) -> None:
            if self._admin_user:
                self._admin_user.refresh_from_db()
            logger.debug(
                "re-queried %s",
                self._admin_user,
            )

        if not self._admin_user:
            try:
                self._admin_user = User.objects.get(
                    username=smarter_settings.platform_admin_username, is_superuser=True
                )
                logger.debug(
                    "initialized %s",
                    self._admin_user,
                )
                return self._admin_user
            except User.DoesNotExist as e:
                raise SmarterConfigurationError("No superuser found for smarter account") from e

        _requery_admin_user(class_name=SmarterCachedObjects.__name__)
        return self._admin_user  # type: ignore[return-value]


smarter_cached_objects = SmarterCachedObjects()
"""
Smarter_cached_objects = SmarterCachedObjects().

An instance of `SmarterCachedObjects` for accessing commonly used cached objects.
Functions as a singleton for the project.
"""


[docs] def get_cached_default_account(invalidate: bool = False) -> Account: """ Retrieve the default account instance, using caching for performance. :param invalidate: Boolean, optional. If True, invalidates the cache before fetching. :returns: The default Account instance. .. important:: The default account is determined by the ``is_default_account=True`` flag in the database. .. warning:: If no default account exists, an exception may be raised. **Example usage**:: # Get the default account default_account = get_cached_default_account() # Invalidate cache before fetching default_account = get_cached_default_account(invalidate=True) """ @cache_results(cache_key="smarter.apps.account.utils.get_cached_default_account") def _get_default_account() -> Account: try: return Account.objects.get(is_default_account=True) except Account.DoesNotExist as e: raise SmarterConfigurationError( "No default account found. Please ensure an account is marked as the default account." ) from e except Account.MultipleObjectsReturned as e: accounts = Account.objects.filter(is_default_account=True) accounts_list = [str(account) for account in accounts] raise SmarterConfigurationError( f"Multiple default accounts found: {', '.join(accounts_list)}. Please ensure only one account is marked as the default account." ) from e if invalidate: _get_default_account.invalidate() return _get_default_account()
[docs] def get_cached_account_for_user( invalidate: Optional[bool] = False, user: Optional[Union[User, AnonymousUser]] = None ) -> Account: """ Locate the Account associated with a given user, using caching for performance. The account is that of the UserProfile that the user chose in the web console's user menu, for this request (see :meth:`UserProfile.get_selected_object() <smarter.apps.account.models.UserProfile.get_selected_object>`), else the default account, if the user belongs to it, else the account of the user's first profile. :param user: User instance. The user whose account should be located. Any other user, such as an AnonymousUser, has no account. :param invalidate: Boolean, optional. If True, invalidates the cache before fetching. :returns: Account instance if found, otherwise None. .. warning:: If no account is found for the user, None is returned and a warning is logged. .. tip:: Use ``invalidate=True`` after updating user or account data to ensure cache consistency. **Example usage**:: # Locate account for a user account = get_cached_account_for_user(user) # Invalidate cache before fetching account = get_cached_account_for_user(user, invalidate=True) """ if not isinstance(user, User): logger.warning("invalid user type: %s", type(user)) raise Account.DoesNotExist() username = getattr(user, "username") if username == smarter_settings.platform_admin_username: return smarter_cached_objects.smarter_account user_id = getattr(user, "id", None) if not user_id: logger.warning("user has no ID: %s", user) raise Account.DoesNotExist() # the account of the profile that the user chose in the web console's user menu, if any. selected_user_profile = UserProfile.get_selected_object(user_id) if selected_user_profile: return selected_user_profile.cached_account @cache_results() def get_cached_account_for_user_by_id(user_id, class_name=UserProfile.__name__): """In-memory cache for user accounts.""" user_profiles = UserProfile.objects.filter(user_id=user_id) for user_profile in user_profiles: if not isinstance(user_profile, UserProfile): raise SmarterConfigurationError(f"Expected UserProfile instance, got {type(user_profile)}") if user_profile.account.is_default_account: logger.debug( "retrieving and caching default account %s for user %s", user_profile.cached_account, user, ) return user_profile.cached_account # If no default account is found, return the first account user_profile = user_profiles.first() if not user_profile: logger.warning("no UserProfile found for user ID %s", user_id) raise Account.DoesNotExist() account = user_profile.cached_account logger.debug( "retrieving and caching default account %s for user ID %s", account, user_id, ) return account if invalidate: get_cached_account_for_user_by_id.invalidate(user_id, class_name=UserProfile.__name__) return get_cached_account_for_user_by_id(user_id=user_id, class_name=UserProfile.__name__)
[docs] def get_cached_user_for_user_id(invalidate: Optional[bool] = False, user_id: Optional[int] = None) -> User: """ Retrieve a User instance by its primary key, using caching for performance. :param user_id: Integer. The primary key of the user to retrieve. :param invalidate: Boolean, optional. If True, invalidates the cache before fetching. :returns: User instance if found, otherwise None. .. warning:: If no user exists for the given ID, None is returned and an error is logged. .. tip:: Use ``invalidate=True`` after updating user data to ensure cache consistency. **Example usage**:: # Retrieve user by ID user = get_cached_user_for_user_id(user_id=123) # Invalidate cache before fetching user = get_cached_user_for_user_id(user_id=123, invalidate=True) """ @cache_results() def _get_user(user_id, class_name=User.__name__) -> Optional[User]: """In-memory cache for user objects.""" try: user = User.objects.get(id=user_id) logger.debug("retrieving and caching user %s", user) return user # type: ignore[return-value] except User.DoesNotExist as e: logger.error("user with ID %s does not exist", user_id) raise e if invalidate: _get_user.invalidate(user_id, class_name=User.__name__) return _get_user(user_id=user_id, class_name=User.__name__)
def get_cached_avatar_url(user_id: int, invalidate: Optional[bool] = False) -> str: """ Return the url of the image that represents a user in the web console, using caching for performance. The url is :attr:`UserProfile.avatar_url`: the image the user uploaded, else the one the oauth provider supplied, else the default profile image. A user with no UserProfile gets the default profile image. The UserProfile is the one that the user chose in the web console's user menu, for this request, else their newest. :param user_id: Integer. The primary key of the user. :param invalidate: Boolean, optional. If True, invalidates the cache before fetching. :returns: The image's url. .. tip:: Use ``invalidate=True`` after changing a user's profile image, so that the console shows it at once. **Example usage**:: url = get_cached_avatar_url(user_id=request.user.id) """ @cache_results() def _get_avatar_url(user_id: int, class_name: str = UserProfile.__name__) -> str: user_profile = UserProfile.objects.filter(user_id=user_id).order_by("-pk").first() if user_profile is None: return static(DEFAULT_PROFILE_IMAGE) return user_profile.avatar_url if invalidate: _get_avatar_url.invalidate(user_id, class_name=UserProfile.__name__) # the image of the profile that the user chose in the web console's user menu, if any. selected_user_profile = UserProfile.get_selected_object(user_id) if selected_user_profile: return selected_user_profile.avatar_url return _get_avatar_url(user_id, class_name=UserProfile.__name__)
[docs] def get_cached_user_for_username(invalidate: Optional[bool] = False, username: Optional[str] = None) -> User: """ Retrieve a User instance by its username, using caching for performance. :param username: String. The username of the user to retrieve. :param invalidate: Boolean, optional. If True, invalidates the cache before fetching. :returns: User instance if found, otherwise None. .. warning:: If no user exists for the given username, a User.DoesNotExist exception is raised and an error is logged. .. tip:: Use ``invalidate=True`` after updating user data to ensure cache consistency. **Example usage**:: # Retrieve user by username user = get_cached_user_for_username("johndoe") # Invalidate cache before fetching user = get_cached_user_for_username("johndoe", invalidate=True) """ @cache_results() def _in_memory_user_by_username(username, class_name=User.__name__) -> Optional[User]: """In-memory cache for user objects by username.""" try: user = User.objects.get(username=username) logger.debug("retrieving and caching user %s", user) return user # type: ignore[return-value] except User.DoesNotExist as e: logger.debug("user with username %s does not exist", username) raise e if invalidate: _in_memory_user_by_username.invalidate(username, class_name=User.__name__) if username == smarter_settings.platform_admin_username: return smarter_cached_objects.admin_user return _in_memory_user_by_username(username, class_name=User.__name__)
ACCOUNT_ADMIN_USERNAME_SUFFIX = "-admin" """The username of the admin user that :func:`get_cached_admin_user_for_account` creates is its account number plus this."""
[docs] def set_account_admin(user_profile: UserProfile, is_account_admin: bool = True) -> None: """ Make the profile's user the administrator of its account, and only of that account. It grants the role, ``UserProfile.is_account_admin``, and never takes it away: ``is_account_admin=False`` leaves the profile as it is. An account's administrator is never made a superuser, who may read every account. :param user_profile: The user's profile in the account. :param is_account_admin: Whether to make them its administrator. """ if not is_account_admin: return if user_profile.is_account_admin: return user_profile.is_account_admin = True user_profile.save()
[docs] def account_admin_username(account_number: str) -> str: """ The username of the admin user that :func:`get_cached_admin_user_for_account` creates for an account. :param account_number: The account's number, e.g. ``1234-5678-9012``. :returns: e.g. ``1234-5678-9012-admin``. """ retval = f"{account_number}{ACCOUNT_ADMIN_USERNAME_SUFFIX}" return retval
[docs] def delete_created_admin_user(account_number: str) -> bool: """ Delete the admin user that :func:`get_cached_admin_user_for_account` created for an account, once it has no profile. That user exists only for its account, and is a superuser. When the account is deleted, its profile goes with it, but the user would stay: a superuser that belongs to nothing. :param account_number: The deleted account's number. :returns: True if a user was deleted. """ username = account_admin_username(account_number) created_admin = User.objects.filter(username=username).first() if created_admin is None: return False if UserProfile.objects.filter(user=created_admin).exists(): return False created_admin.delete() logger.info( "deleted the admin user of account %s", account_number, ) return True
[docs] def get_cached_admin_user_for_account(account: Account, invalidate: Optional[bool] = False) -> User: """ Retrieve the admin user for a given account, creating one if necessary. :param account: Account instance. The account for which to retrieve the admin user. :param invalidate: Boolean, optional. If True, invalidates the cache before fetching. :returns: User instance representing the account admin. .. important:: If no admin user exists for the account, a new staff user and UserProfile will be created automatically. .. warning:: If the account is missing or misconfigured, an exception is raised. .. tip:: Use ``invalidate=True`` after updating admin user data to ensure cache consistency. **Example usage**:: # Retrieve the admin user for an account admin_user = get_cached_admin_user_for_account(account=account) # Invalidate cache before fetching admin_user = get_cached_admin_user_for_account(invalidate=True, account=account) """ if not isinstance(account, Account): raise User.DoesNotExist("Invalid account provided") @cache_results() def _admin_user_for_account_number(account_number: str, class_name=User.__name__) -> User: # reinstantiate the account try: account = Account.objects.get(account_number=account_number) except Account.DoesNotExist as e: logger.error( "account with number %s does not exist", account_number, ) raise e user_profile = ( UserProfile.objects.filter(account=account) .filter(Q(user__is_staff=True) | Q(user__is_superuser=True) | Q(is_account_admin=True)) .select_related("user", "account") .order_by("pk") .first() ) if user_profile: logger.debug("found and cached admin UserProfile %s for account %s", user_profile, account) return user_profile.cached_user # type: ignore[return-value] else: logger.warning("no admin user found for account %s. Creating new admin user.", account) # an account whose every profile is a test profile is a test account, e.g. the end-to-end tests' # throwaway account. Its admin is a test profile too, so that its contact's welcome email is sent # quietly, rather than to <account>-admin@<root domain>, and the test teardown deletes it. account_profiles = UserProfile.objects.filter(account=account) has_profiles = account_profiles.exists() has_real_profiles = account_profiles.filter(is_test=False).exists() is_test_account = has_profiles and not has_real_profiles username = account_admin_username(str(account.account_number)) # the administrator of this account only: UserProfile.is_account_admin. Never a superuser or a # staff user, who would administer, or read, other accounts too. new_user = User.objects.create( username=username, email=f"{username}@{smarter_settings.platform_root_domain}", is_staff=False, is_superuser=False, is_active=True, ) user_profile = UserProfile.objects.create( name=username, user=new_user, account=account, is_test=is_test_account, is_account_admin=True ) return user_profile.user # type: ignore[return-value] account_number = str(account.account_number) if invalidate: _admin_user_for_account_number.invalidate(account_number=account_number, class_name=User.__name__) return _admin_user_for_account_number(account_number=account_number, class_name=User.__name__)
[docs] @deprecated( "This function is deprecated and may be removed in a future release. Please use smarter_cached_objects.smarter_admin_user_profile" ) def get_cached_smarter_admin_user_profile() -> UserProfile: """ Retrieve the admin UserProfile for the smarter account, using caching for performance. :returns: UserProfile instance for the smarter admin user. .. note:: The smarter admin user is typically a superuser or staff user associated with the platform's main account. **Example usage**:: # Retrieve the smarter admin user profile admin_profile = get_cached_smarter_admin_user_profile() # Invalidate cache before fetching admin_profile = get_cached_smarter_admin_user_profile(invalidate=True) """ return smarter_cached_objects.smarter_admin_user_profile
[docs] def account_number_from_url(url: Optional[str] = None, invalidate: Optional[bool] = False) -> Optional[str]: """ Extract the account number from a Smarter platform URL, using caching for performance. :param url: String. The URL to parse for an account number. :param invalidate: Boolean, optional. If True, invalidates the cache before fetching. :returns: The extracted account number as a string, or None if not found. .. note:: The function validates the URL format before extraction. .. warning:: If the URL does not contain a valid account number, None is returned. .. tip:: Use ``invalidate=True`` after updating URLs or account number patterns to ensure cache consistency. **Example usage**:: # Extract account number from a URL account_number = account_number_from_url(url="https://hr.3141-5926-5359.alpha.api.example.com/") # Result: '3141-5926-5359' # Invalidate cache before fetching account_number = account_number_from_url(url="https://hr.3141-5926-5359.alpha.api.example.com/", invalidate=True) """ if not url: return None if not isinstance(url, str): logger.warning("invalid URL type: %s", type(url)) return None @cache_results() def _account_number_from_url(url: str, class_name=Account.__name__) -> Optional[str]: match = SMARTER_ACCOUNT_NUMBER_PATTERN.search(url) retval = match.group(0) if match else None if retval is not None: logger.debug("extracted and cached account number %s from URL %s", retval, url) return retval if invalidate: _account_number_from_url.invalidate(url, class_name=Account.__name__) return _account_number_from_url(url, class_name=Account.__name__)
[docs] def get_users_for_account(account: Account) -> list[User]: """ Retrieve a list of users associated with a given account. :param account: Account instance. The account for which to retrieve users. :returns: List of User instances. .. important:: The account parameter is required. If not provided, an exception is raised. .. warning:: If the account has no associated users, an empty list is returned. **Example usage**:: # Get all users for an account users = get_users_for_account(account) """ if not account: raise SmarterValueError("Account is required") users = User.objects.filter(user_profile__account=account) return [*users]
[docs] def get_user_profiles_for_account(account: Account) -> list[UserProfile]: """ Retrieve a list of user profiles associated with a given account. :param account: Account instance. The account for which to retrieve user profiles. :returns: List of UserProfile instances, or None if no profiles exist. .. important:: The account parameter is required. If not provided, an exception is raised. .. warning:: If the account has no associated user profiles, None is returned. **Example usage**:: # Get all user profiles for an account profiles = get_user_profiles_for_account(account) """ if not account: raise SmarterValueError("Account is required") user_profiles = UserProfile.objects.filter(account=account) return list(user_profiles)
[docs] @deprecated( "This function is deprecated and may be removed in a future release. Please use with_ownership_permission_for() instead." ) def valid_resource_owners_for_user(user_profile: Optional[UserProfile]) -> list[UserProfile]: """ Get a list of valid owners for the given user profile. This function retrieves all user profiles associated with the same account as the provided user profile. These profiles are considered valid owners for ORM resources created by the user. :param user_profile: The `UserProfile` instance representing the user. :type user_profile: UserProfile :return: A list of `UserProfile` instances that are valid ORM resource owners. :rtype: list[UserProfile] .. seealso:: - :class:`UserProfile` Example usage: .. code-block:: python from smarter.apps.account.models import UserProfile from smarter.apps.account.utils import valid_resource_owners_for_user user_profile = UserProfile.objects.get(user__username="exampleuser") owners = valid_resource_owners_for_user(user_profile) print("Valid resource owners:", [owner.user.username for owner in owners]) """ logger.debug("called with user_profile: %s", user_profile) if not user_profile: return [smarter_cached_objects.smarter_admin_user_profile] account_admin = get_cached_admin_user_for_account(invalidate=False, account=user_profile.account) if not isinstance(account_admin, UserProfile): return [user_profile, smarter_cached_objects.smarter_admin_user_profile] return [user_profile, account_admin, smarter_cached_objects.smarter_admin_user_profile]
[docs] def is_platform_staff(user: Optional[object]) -> bool: """ Return whether a user is one of the platform's own staff: an active staff user of the Smarter account. ``User.is_staff`` alone means that a user administers each account they belong to, so many customer accounts' admins have it, and some of them are superusers too. (An account admin may instead have ``UserProfile.is_account_admin``, which administers one account and is never platform staff.) The platform's staff are the staff users of the Smarter account (``SMARTER_ACCOUNT_NUMBER``), which runs the platform. Users who sign up themselves also join the Smarter account, but not as staff. This is a security check, so it is never cached: a user who stops being staff, or leaves the Smarter account, loses access at once. **Side effects:** one database query, for the user's profile in the Smarter account. :param user: The user, or anything else, e.g. ``AnonymousUser`` or None, which is not staff. :returns: True if the user is active, staff, and has a profile in the Smarter account. """ if not isinstance(user, User): return False if not user.is_active: return False if not user.is_staff: return False smarter_account = smarter_cached_objects.smarter_account in_smarter_account = UserProfile.objects.filter(user=user, account=smarter_account).exists() return in_smarter_account
__all__ = [ "ACCOUNT_ADMIN_USERNAME_SUFFIX", "account_admin_username", "delete_created_admin_user", "set_account_admin", "get_cached_default_account", "get_cached_account_for_user", "get_cached_user_for_user_id", "get_cached_user_for_username", "get_cached_admin_user_for_account", "get_cached_smarter_admin_user_profile", "account_number_from_url", "get_users_for_account", "get_user_profiles_for_account", "valid_resource_owners_for_user", "is_platform_staff", ]