Guest User

Untitled

a guest
Jul 29th, 2018
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.03 KB | None | 0 0
  1. import jwt
  2.  
  3. from datetime import datetime, timedelta
  4.  
  5. from django.conf import settings
  6. from django.contrib.auth.models import (
  7. AbstractBaseUser, BaseUserManager, PermissionsMixin
  8. )
  9. from django.db import models
  10.  
  11. class UserManager(BaseUserManager):
  12. """
  13. Django requires that custom users define their own Manager class. By
  14. inheriting from `BaseUserManager`, we get a lot of the same code used by
  15. Django to create a `User`.
  16.  
  17. All we have to do is override the `create_user` function which we will use
  18. to create `User` objects.
  19. """
  20.  
  21. def create_user(self, username, email, password=None):
  22. """Create and return a `User` with an email, username and password."""
  23. if username is None:
  24. raise TypeError('Users must have a username.')
  25.  
  26. if email is None:
  27. raise TypeError('Users must have an email address.')
  28.  
  29. user = self.model(username=username, email=self.normalize_email(email))
  30. user.set_password(password)
  31. user.save()
  32.  
  33. return user
  34.  
  35. def create_superuser(self, username, email, password):
  36. """
  37. Create and return a `User` with superuser (admin) permissions.
  38. """
  39. if password is None:
  40. raise TypeError('Superusers must have a password.')
  41.  
  42. user = self.create_user(username, email, password)
  43. user.is_superuser = True
  44. user.is_staff = True
  45. user.save()
  46.  
  47. return user
  48.  
  49.  
  50. class User(AbstractBaseUser, PermissionsMixin):
  51. # Each `User` needs a human-readable unique identifier that we can use to
  52. # represent the `User` in the UI. We want to index this column in the
  53. # database to improve lookup performance.
  54. username = models.CharField(db_index=True, max_length=255, unique=True)
  55.  
  56. # We also need a way to contact the user and a way for the user to identify
  57. # themselves when logging in. Since we need an email address for contacting
  58. # the user anyways, we will also use the email for logging in because it is
  59. # the most common form of login credential at the time of writing.
  60. email = models.EmailField(db_index=True, unique=True)
  61.  
  62. # When a user no longer wishes to use our platform, they may try to delete
  63. # their account. That's a problem for us because the data we collect is
  64. # valuable to us and we don't want to delete it. We
  65. # will simply offer users a way to deactivate their account instead of
  66. # letting them delete it. That way they won't show up on the site anymore,
  67. # but we can still analyze the data.
  68. is_active = models.BooleanField(default=True)
  69.  
  70. # The `is_staff` flag is expected by Django to determine who can and cannot
  71. # log into the Django admin site. For most users this flag will always be
  72. # false.
  73. is_staff = models.BooleanField(default=False)
  74.  
  75. # A timestamp representing when this object was created.
  76. created_at = models.DateTimeField(auto_now_add=True)
  77.  
  78. # A timestamp reprensenting when this object was last updated.
  79. updated_at = models.DateTimeField(auto_now=True)
  80.  
  81. # More fields required by Django when specifying a custom user model.
  82.  
  83. # The `USERNAME_FIELD` property tells us which field we will use to log in.
  84. # In this case we want it to be the email field.
  85. USERNAME_FIELD = 'email'
  86. REQUIRED_FIELDS = ['username']
  87.  
  88. # Tells Django that the UserManager class defined above should manage
  89. # objects of this type.
  90. objects = UserManager()
  91.  
  92. def __str__(self):
  93. """
  94. Returns a string representation of this `User`.
  95.  
  96. This string is used when a `User` is printed in the console.
  97. """
  98. return self.email
  99.  
  100. @property
  101. def token(self):
  102. """
  103. Allows us to get a user's token by calling `user.token` instead of
  104. `user.generate_jwt_token().
  105.  
  106. The `@property` decorator above makes this possible. `token` is called
  107. a "dynamic property".
  108. """
  109. return self._generate_jwt_token()
  110.  
  111. def get_full_name(self):
  112. """
  113. This method is required by Django for things like handling emails.
  114. Typically this would be the user's first and last name. Since we do
  115. not store the user's real name, we return their username instead.
  116. """
  117. return self.username
  118.  
  119. def get_short_name(self):
  120. """
  121. This method is required by Django for things like handling emails.
  122. Typically, this would be the user's first name. Since we do not store
  123. the user's real name, we return their username instead.
  124. """
  125. return self.username
  126.  
  127. def _generate_jwt_token(self):
  128. """
  129. Generates a JSON Web Token that stores this user's ID and has an expiry
  130. date set to 60 days into the future.
  131. """
  132. dt = datetime.now() + timedelta(days=60)
  133.  
  134. token = jwt.encode({
  135. 'id': self.pk,
  136. 'exp': int(dt.strftime('%s'))
  137. }, settings.SECRET_KEY, algorithm='HS256')
  138.  
  139. return token.decode('utf-8')
Add Comment
Please, Sign In to add comment