|
| 1 | +import logging |
| 2 | + |
| 3 | +from django.contrib.auth.hashers import UNUSABLE_PASSWORD_PREFIX, UNUSABLE_PASSWORD_SUFFIX_LENGTH, get_hashers_by_algorithm, identify_hasher, make_password |
| 4 | +from django.contrib.auth.models import AbstractUser |
| 5 | +from django.db import models |
| 6 | +from django.utils.translation import gettext as _ |
| 7 | + |
| 8 | +from ansible_base.activitystream.models import AuditableModel |
| 9 | +from ansible_base.lib.abstract_models.common import CommonModel |
| 10 | +from ansible_base.lib.abstract_models.user import AbstractDABUser |
| 11 | +from ansible_base.lib.managers.user import UserUnmanagedManager |
| 12 | +from ansible_base.lib.utils.models import user_summary_fields |
| 13 | +from ansible_base.resource_registry.fields import AnsibleResourceField |
| 14 | + |
| 15 | +logger = logging.getLogger('ansible_base.django_template.models.user') |
| 16 | + |
| 17 | + |
| 18 | +def password_is_hashed(password): |
| 19 | + """ |
| 20 | + Returns a boolean of whether password is hashed with loaded algorithms |
| 21 | + """ |
| 22 | + if password is None: |
| 23 | + return False |
| 24 | + try: |
| 25 | + hasher = identify_hasher(password) |
| 26 | + except ValueError: |
| 27 | + # hasher can't be identified or is not loaded |
| 28 | + return False |
| 29 | + return hasher.algorithm in get_hashers_by_algorithm().keys() |
| 30 | + |
| 31 | + |
| 32 | +def password_is_usable(password): |
| 33 | + """ |
| 34 | + Returns True if password is None or wasn't generated by django.contrib.auth.hashers.make_password(None) |
| 35 | + """ |
| 36 | + unusable_password_len = len(UNUSABLE_PASSWORD_PREFIX) + UNUSABLE_PASSWORD_SUFFIX_LENGTH |
| 37 | + |
| 38 | + # what are the odds that a user password starts with unusable prefix and the same length :-? |
| 39 | + return password is None or not (password.startswith(UNUSABLE_PASSWORD_PREFIX) and len(password) == unusable_password_len) |
| 40 | + |
| 41 | + |
| 42 | +class AbstractTemplateUser(AbstractDABUser, CommonModel, AuditableModel): |
| 43 | + class Meta(AbstractUser.Meta): |
| 44 | + abstract = True |
| 45 | + |
| 46 | + ignore_relations = [ |
| 47 | + 'groups', # not using the auth app stuff, see Team model |
| 48 | + 'user_permissions', # not using auth app permissions |
| 49 | + 'logentry', # used for Django admin pages, not the API |
| 50 | + 'social_auth', # Social auth endpoint |
| 51 | + 'organizations_administered', # We are going to merge [teams|orgs] the user is an admin in with [teams|orgs] the user is a member of |
| 52 | + 'teams_administered', |
| 53 | + ] |
| 54 | + activity_stream_excluded_field_names = ['last_login'] |
| 55 | + |
| 56 | + encrypted_fields = () # handed as special case by UserSerializer |
| 57 | + PASSWORD_FIELDS = ["password"] # Mark password fields so ansible_base.lib.rest_filters can properly block attempts to filter over password |
| 58 | + |
| 59 | + resource = AnsibleResourceField(primary_key_field="id") |
| 60 | + |
| 61 | + managed = models.BooleanField( |
| 62 | + editable=False, |
| 63 | + blank=False, |
| 64 | + default=False, |
| 65 | + help_text=_("Indicates if this user is managed by the system. It cannot be modified once created."), |
| 66 | + ) |
| 67 | + |
| 68 | + # By default, skip managed users (use all_objects for all users queryset) |
| 69 | + objects = UserUnmanagedManager() |
| 70 | + |
| 71 | + def __init__(self, *args, is_platform_auditor=False, **kwargs): |
| 72 | + super().__init__(*args, **kwargs) |
| 73 | + if is_platform_auditor: |
| 74 | + self._is_platform_auditor = True |
| 75 | + # Store the original value of the fields to check for field changes later |
| 76 | + self._original_fields = self._get_fields() |
| 77 | + |
| 78 | + def _get_fields(self): |
| 79 | + """ |
| 80 | + Return a dictionary of the model's instance fields and their current values. |
| 81 | + """ |
| 82 | + return {field.name: self.__dict__.get(field.name) for field in self._meta.fields} |
| 83 | + |
| 84 | + def save(self, *args, **kwargs): |
| 85 | + # If the password is empty string lets make it None, this will get turned into an unusable password by make_password |
| 86 | + if self.password == '': |
| 87 | + self.password = None |
| 88 | + |
| 89 | + if password_is_usable(self.password) and not password_is_hashed(self.password): |
| 90 | + self.password = make_password(self.password) |
| 91 | + |
| 92 | + super().save(*args, **kwargs) |
| 93 | + |
| 94 | + def summary_fields(self): |
| 95 | + return user_summary_fields(self) |
| 96 | + |
| 97 | + @property |
| 98 | + def organizations(self): |
| 99 | + |
| 100 | + from ansible_base.lib.utils.auth import get_organization_model |
| 101 | + if get_organization_model(return_none_on_error=True) is None: |
| 102 | + raise AttributeError("Property not available") |
| 103 | + else: |
| 104 | + return get_organization_model().access_qs(self, 'member') |
0 commit comments