-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmodels.py
More file actions
236 lines (192 loc) · 7.77 KB
/
Copy pathmodels.py
File metadata and controls
236 lines (192 loc) · 7.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
import zoneinfo
from datetime import timedelta
import swapper
from constance import config
from django.apps import apps
from django.conf import settings
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin
from django.core.exceptions import ValidationError
from django.db import models
from django.db.models import TextChoices
from django.utils import timezone
from django.utils.translation import gettext_lazy as _
from model_utils.models import TimeStampedModel
from phonenumber_field.modelfields import PhoneNumberField
from baseapp_core.graphql.models import RelayModel
from baseapp_core.models import CaseInsensitiveEmailField, DocumentIdMixin
from .managers import UserManager
def use_relay_model():
try:
from baseapp_core.graphql.models import RelayModel
return RelayModel
except ImportError:
return object
def use_profile_model():
if apps.is_installed("baseapp_profiles"):
from baseapp_profiles.models import ProfilableModel
class UserProfilableModel(ProfilableModel):
profile = models.OneToOneField(
swapper.get_model_name("baseapp_profiles", "Profile"),
related_name="%(class)s",
on_delete=models.SET_NULL,
verbose_name=_("profile"),
null=True,
blank=True,
)
profile_name_sql = "NEW.first_name || ' ' || NEW.last_name"
profile_owner_sql = "NEW.id"
class Meta:
abstract = True
return UserProfilableModel
class NoProfileModel(models.Model):
class Meta:
abstract = True
return NoProfileModel
def validate_timezone(value: str) -> None:
"""Reject values that aren't valid IANA timezone names (blank is allowed)."""
if value and value not in zoneinfo.available_timezones():
raise ValidationError(
_("%(value)s is not a valid IANA timezone name."),
params={"value": value},
)
class AbstractUser(
use_profile_model(),
PermissionsMixin,
DocumentIdMixin,
RelayModel,
AbstractBaseUser,
):
email = CaseInsensitiveEmailField(unique=True, db_index=True)
is_email_verified = models.BooleanField(default=False)
date_joined = models.DateTimeField(_("date joined"), default=timezone.now)
password_changed_date = models.DateTimeField(
_("last date password was changed"), default=timezone.now
)
# Changing email
new_email = CaseInsensitiveEmailField(blank=True)
is_new_email_confirmed = models.BooleanField(
default=False,
help_text="Has the user confirmed they want an email change?",
)
# Details
first_name = models.CharField(max_length=100, blank=True)
last_name = models.CharField(max_length=100, blank=True)
phone_number = PhoneNumberField(blank=True, null=True, unique=True)
is_active = models.BooleanField(
_("active"),
default=True,
help_text=_(
"Designates whether this user should be treated as active. "
"Unselect this instead of deleting accounts."
),
)
is_staff = models.BooleanField(
_("staff status"),
default=False,
help_text=_("Designates whether the user can log into this admin site."),
)
objects = UserManager()
preferred_language = models.CharField(max_length=9, choices=settings.LANGUAGES, default="en")
timezone = models.CharField(
_("timezone"),
max_length=64,
blank=True,
default="",
validators=[validate_timezone],
help_text=_("IANA timezone name used to display dates and times for this user."),
)
USERNAME_FIELD = "email"
class Meta:
abstract = True
verbose_name = _("user")
verbose_name_plural = _("users")
permissions = [
("view_all_users", _("can view all users")),
("view_user_email", _("can view user's email field")),
("view_user_phone_number", _("can view user's phone number field")),
("view_user_is_superuser", _("can view user's is_superuser field")),
("view_user_is_staff", _("can view user's is_staff field")),
("view_user_is_email_verified", _("can view user's is_email_verified field")),
("view_user_password_changed_date", _("can view user's password_changed_date field")),
("view_user_new_email", _("can view user's new_email field")),
("view_user_is_new_email_confirmed", _("can view user's is_new_email_confirmed field")),
]
def __str__(self):
return self.get_full_name()
def get_full_name(self):
names = [self.first_name, self.last_name]
full_name = " ".join([name for name in names if name]).strip()
return full_name or self.email
@property
def avatar(self):
# TODO: deprecate
if profile := getattr(self, "profile", None):
return profile.image
return None
@property
def password_expired(self) -> bool:
if "is_password_expired" in self.__dict__:
return bool(self.__dict__["is_password_expired"])
expiration_interval = int(getattr(config, "USER_PASSWORD_EXPIRATION_INTERVAL", 0))
if expiration_interval <= 0:
return False
expires_at = self.password_changed_date + timezone.timedelta(days=expiration_interval)
return timezone.now() >= expires_at
@classmethod
def get_graphql_object_type(cls):
from .graphql.object_types import UserObjectType
return UserObjectType
def save(self, *args, **kwargs):
if hasattr(self, "tracker"):
with self.tracker:
if self.tracker.has_changed("password"):
self.password_changed_date = timezone.now()
super().save(*args, **kwargs)
def anonymize_and_delete(self):
from .rest_framework.users.tasks import anonymize_and_delete_user_task
delay_days = config.ANONYMIZE_TASK_DELAY_DAYS
eta = timezone.now() + timedelta(days=delay_days)
anonymize_and_delete_user_task.apply_async(args=[self.id], eta=eta)
class PasswordValidation(models.Model):
class Validators(TextChoices):
UserAttributeSimilarityValidator = (
"django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
"User Attribute Similarity",
)
MinimumLengthValidator = (
"django.contrib.auth.password_validation.MinimumLengthValidator",
"Minimum Length",
)
CommonPasswordValidator = (
"django.contrib.auth.password_validation.CommonPasswordValidator",
"Common Password",
)
NumericPasswordValidator = (
"django.contrib.auth.password_validation.NumericPasswordValidator",
"Numeric Password",
)
MustContainCapitalLetterValidator = (
"baseapp_auth.password_validators.MustContainCapitalLetterValidator",
"Must Contain Capital Letter",
)
MustContainSpecialCharacterValidator = (
"baseapp_auth.password_validators.MustContainSpecialCharacterValidator",
"Must Contain Special Character",
)
name = models.CharField(max_length=255, choices=Validators.choices)
options = models.JSONField(null=True, blank=True)
is_active = models.BooleanField(default=True)
def __str__(self):
return self.name
class SuperuserUpdateLog(TimeStampedModel):
assigner = models.ForeignKey(
settings.AUTH_USER_MODEL,
related_name="superuser_assigner_logs",
on_delete=models.CASCADE,
)
assignee = models.ForeignKey(
settings.AUTH_USER_MODEL,
related_name="superuser_assignee_logs",
on_delete=models.CASCADE,
)
made_superuser = models.BooleanField()