-
Notifications
You must be signed in to change notification settings - Fork 24
/
mixins.py
211 lines (159 loc) · 5.98 KB
/
mixins.py
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
from django.contrib.auth.models import BaseUserManager
from django.contrib.auth.tokens import default_token_generator
from django.contrib.postgres.fields import CIEmailField
from django.contrib.sites.models import Site
from django.core import checks, signing
from django.db import models
from django.utils import timezone
from django.utils.encoding import force_bytes, python_2_unicode_compatible
from django.utils.http import urlsafe_base64_encode
from django.utils.translation import ugettext_lazy as _
from user_management.utils import notifications
class UserManager(BaseUserManager):
"""Django requires user managers to have create_user & create_superuser."""
def create_user(self, email, password=None, **extra_fields):
if not email:
raise ValueError(_('The given email address must be set'))
email = self.normalize_email(email).lower()
user = self.model(
email=email,
last_login=timezone.now(),
**extra_fields
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, password, **extra_fields):
fields = {
'is_staff': True,
'is_superuser': True,
}
fields.update(extra_fields)
user = self.create_user(email, password, **fields)
return user
def get_by_natural_key(self, email):
"""Get user by email with case-insensitive exact match.
`get_by_natural_key` is used to `authenticate` a user, see:
https://github.com/django/django/blob/c5780adeecfbd85a80b5aa7130dd86e78b23e497/django/contrib/auth/backends.py#L16
"""
return self.get(email__iexact=email)
class DateJoinedUserMixin(models.Model):
date_joined = models.DateTimeField(
verbose_name=_('date joined'),
default=timezone.now,
editable=False,
)
class Meta:
abstract = True
class EmailUserMixin(models.Model):
email = CIEmailField(
verbose_name=_('Email address'),
unique=True,
max_length=511,
)
email_verified = True
objects = UserManager()
USERNAME_FIELD = 'email'
class Meta:
abstract = True
class IsStaffUserMixin(models.Model):
is_staff = models.BooleanField(_('staff status'), default=False)
class Meta:
abstract = True
@python_2_unicode_compatible
class NameUserMethodsMixin:
def get_full_name(self):
return self.name
def get_short_name(self):
return self.name
def __str__(self):
return self.name
class NameUserMixin(NameUserMethodsMixin, models.Model):
name = models.CharField(
verbose_name=_('Name'),
max_length=255,
)
REQUIRED_FIELDS = ['name']
class Meta:
abstract = True
ordering = ['name']
class BasicUserFieldsMixin(
DateJoinedUserMixin, EmailUserMixin, IsStaffUserMixin, NameUserMixin):
class Meta:
abstract = True
class ActiveUserMixin(models.Model):
is_active = models.BooleanField(_('active'), default=True)
class Meta:
abstract = True
class VerifyEmailManager(UserManager):
def create_superuser(self, email, password, **extra_fields):
fields = {
'is_active': True,
}
fields.update(extra_fields)
user = super(VerifyEmailManager, self).create_superuser(
email,
password,
**fields)
return user
class EmailVerifyUserMethodsMixin:
"""
Define how validation and password reset emails are sent.
`password_reset_notification` and `validation_notification` can be overriden to
provide custom settings to send emails.
"""
password_reset_notification = notifications.PasswordResetNotification
validation_notification = notifications.ValidationNotification
def generate_validation_token(self):
"""Generate user token for account validation."""
data = {'email': self.email}
return signing.dumps(data)
def generate_token(self):
"""Generate user token for password reset."""
return default_token_generator.make_token(self)
def generate_uid(self):
"""Generate user uid for password reset."""
return urlsafe_base64_encode(force_bytes(self.pk))
def send_validation_email(self):
"""Send a validation email to the user's email address."""
if self.email_verified:
raise ValueError(_('Cannot validate already active user.'))
site = Site.objects.get_current()
self.validation_notification(user=self, site=site).notify()
def send_password_reset(self):
"""Send a password reset to the user's email address."""
site = Site.objects.get_current()
self.password_reset_notification(user=self, site=site).notify()
class EmailVerifyUserMixin(EmailVerifyUserMethodsMixin, models.Model):
is_active = models.BooleanField(_('active'), default=False)
email_verified = models.BooleanField(
_('Email verified?'),
default=False,
help_text=_('Indicates if the email address has been verified.'))
objects = VerifyEmailManager()
class Meta:
abstract = True
@classmethod
def check(cls, **kwargs):
errors = super(EmailVerifyUserMixin, cls).check(**kwargs)
errors.extend(cls._check_manager(**kwargs))
return errors
@classmethod
def _check_manager(cls, **kwargs):
if isinstance(cls.objects, VerifyEmailManager):
return []
return [
checks.Warning(
"Manager should be an instance of 'VerifyEmailManager'",
hint="Subclass a custom manager from 'VerifyEmailManager'",
obj=cls,
id='user_management.W001',
),
]
class VerifyEmailMixin(EmailVerifyUserMixin, BasicUserFieldsMixin):
class Meta:
abstract = True
class AvatarMixin(models.Model):
avatar = models.ImageField(upload_to='user_avatar', null=True, blank=True)
class Meta:
abstract = True