"""
Account utilities: an account's admins, users and profiles, the account number in a url, and the platform-staff check.
Its public names are exported by :mod:`smarter.apps.account.utils`, where callers import them from. The cached
lookups of accounts and users are in :mod:`smarter.apps.account.caching`.
"""
import re
from typing import Optional
from cache_results import cache_results
from typing_extensions import deprecated
from smarter.apps.account.caching import (
account_admin_username,
get_cached_admin_user_for_account,
smarter_cached_objects,
)
from smarter.apps.account.models import (
Account,
User,
UserProfile,
)
from smarter.common.exceptions import 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])
SMARTER_ACCOUNT_NUMBER_PATTERN = re.compile(SmarterValidator.SMARTER_ACCOUNT_NUMBER_REGEX)
[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 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 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]
__all__ = [
"account_number_from_url",
"delete_created_admin_user",
"get_user_profiles_for_account",
"get_users_for_account",
"is_platform_staff",
"set_account_admin",
"valid_resource_owners_for_user",
]