Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1# Imports
3import hashlib
4from django.apps import apps as django_apps
5from django.utils.crypto import get_random_string
6from django.utils.timezone import now
7import logging
8from superdjango.conf import SUPERDJANGO
9from superdjango.shortcuts import user_in_group
11log = logging.getLogger(__name__)
13# Exports
15__all__ = (
16 "generate_session_key",
17 "get_user_impersonation_model",
18 "user_is_allowed_to_impersonate",
19)
21# Functions
24def generate_session_key():
25 """Generate a session key to identify an impersonation.
27 :rtype: str
29 """
30 return hashlib.sha1('{0}:{1}'.format(get_random_string(), now()).encode('utf-8')).hexdigest()
33def get_user_impersonation_model():
34 """Get the model used to log impersonation history.
36 :rtype: ImpersonationHistoryModel | None
38 """
39 if SUPERDJANGO.USER_IMPERSONATION_MODEL is None:
40 return None
42 try:
43 return django_apps.get_model(SUPERDJANGO.USER_IMPERSONATION_MODEL, require_ready=False)
44 except ValueError:
45 log.warning('SUPERDJANGO_USER_IMPERSONATION_MODEL must be in the form of "app_label.ModelName".')
46 return None
47 except LookupError:
48 message = 'SUPERDJANGO_USER_IMPERSONATION_MODEL refers to model "%s" which has not been installed.'
49 log.warning(message % SUPERDJANGO.USER_IMPERSONATION_MODEL)
50 return None
53def user_is_allowed_to_impersonate(user):
54 """Determine whether the given user is allowed to impersonate another user.
56 :param user: The user instance to be checked.
57 :type user: AUTH_USER_MODEL
59 :rtype: bool
61 """
62 # Super users are always allowed.
63 if user.is_superuser:
64 return True
66 # Check staff users.
67 if SUPERDJANGO.USER_IMPERSONATION_ENABLED_FOR_STAFF and user.is_staff:
68 return True
70 # Check against group membership.
71 if SUPERDJANGO.USER_IMPERSONATION_ENABLED_FOR_GROUPS is not None:
72 for group in SUPERDJANGO.USER_IMPERSONATION_ENABLED_FOR_GROUPS:
73 if user_in_group(user, group):
74 return True
76 return False