1 |
|
"""
|
2 |
|
This module allows importing AbstractBaseUser even when django.contrib.auth is
|
3 |
|
not in INSTALLED_APPS.
|
4 |
|
"""
|
5 |
|
from __future__ import unicode_literals
|
6 |
|
|
7 |
|
from django.contrib.auth.hashers import (
|
8 |
|
check_password, is_password_usable, make_password,
|
9 |
|
)
|
10 |
|
from django.db import models
|
11 |
|
from django.utils.crypto import salted_hmac
|
12 |
|
from django.utils.encoding import python_2_unicode_compatible
|
13 |
|
from django.utils.translation import ugettext_lazy as _
|
14 |
|
|
15 |
|
|
16 |
|
@python_2_unicode_compatible
|
17 |
|
class AbstractBaseUser(models.Model):
|
18 |
|
password = models.CharField(_('password'), max_length=128)
|
19 |
|
last_login = models.DateTimeField(_('last login'), blank=True, null=True)
|
20 |
|
|
21 |
|
is_active = True
|
22 |
|
|
23 |
|
REQUIRED_FIELDS = []
|
24 |
|
|
25 |
|
class Meta:
|
26 |
|
abstract = True
|
27 |
|
|
28 |
|
def get_username(self):
|
29 |
|
"Return the identifying username for this User"
|
30 |
|
return getattr(self, self.USERNAME_FIELD)
|
31 |
|
|
32 |
|
def __str__(self):
|
33 |
|
return self.get_username()
|
34 |
|
|
35 |
|
def natural_key(self):
|
36 |
|
return (self.get_username(),)
|
37 |
|
|
38 |
|
def is_anonymous(self):
|
39 |
|
"""
|
40 |
|
Always returns False. This is a way of comparing User objects to
|
41 |
|
anonymous users.
|
42 |
|
"""
|
43 |
|
return False
|
44 |
|
|
45 |
|
def is_authenticated(self):
|
46 |
|
"""
|
47 |
|
Always return True. This is a way to tell if the user has been
|
48 |
|
authenticated in templates.
|
49 |
|
"""
|
50 |
|
return True
|
51 |
|
|
52 |
|
def set_password(self, raw_password):
|
53 |
|
self.password = make_password(raw_password)
|
54 |
|
|
55 |
|
def check_password(self, raw_password):
|
56 |
|
"""
|
57 |
|
Returns a boolean of whether the raw_password was correct. Handles
|
58 |
|
hashing formats behind the scenes.
|
59 |
|
"""
|
60 |
|
def setter(raw_password):
|
61 |
|
self.set_password(raw_password)
|
62 |
|
self.save(update_fields=["password"])
|
63 |
|
return check_password(raw_password, self.password, setter)
|
64 |
|
|
65 |
|
def set_unusable_password(self):
|
66 |
|
# Sets a value that will never be a valid hash
|
67 |
|
self.password = make_password(None)
|
68 |
|
|
69 |
|
def has_usable_password(self):
|
70 |
|
return is_password_usable(self.password)
|
71 |
|
|
72 |
|
def get_full_name(self):
|
73 |
|
raise NotImplementedError('subclasses of AbstractBaseUser must provide a get_full_name() method')
|
74 |
|
|
75 |
|
def get_short_name(self):
|
76 |
|
raise NotImplementedError('subclasses of AbstractBaseUser must provide a get_short_name() method.')
|
77 |
|
|
78 |
|
def get_session_auth_hash(self):
|
79 |
|
"""
|
80 |
|
Returns an HMAC of the password field.
|
81 |
|
"""
|
82 |
|
key_salt = "django.contrib.auth.models.AbstractBaseUser.get_session_auth_hash"
|
83 |
|
return salted_hmac(key_salt, self.password).hexdigest()
|