Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

models.py 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  1. from django.contrib import auth
  2. from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
  3. from django.contrib.contenttypes.models import ContentType
  4. from django.core.exceptions import PermissionDenied
  5. from django.core.mail import send_mail
  6. from django.db import models
  7. from django.db.models.manager import EmptyManager
  8. from django.utils import timezone
  9. from django.utils.translation import gettext_lazy as _
  10. from .validators import UnicodeUsernameValidator
  11. def update_last_login(sender, user, **kwargs):
  12. """
  13. A signal receiver which updates the last_login date for
  14. the user logging in.
  15. """
  16. user.last_login = timezone.now()
  17. user.save(update_fields=['last_login'])
  18. class PermissionManager(models.Manager):
  19. use_in_migrations = True
  20. def get_by_natural_key(self, codename, app_label, model):
  21. return self.get(
  22. codename=codename,
  23. content_type=ContentType.objects.db_manager(self.db).get_by_natural_key(app_label, model),
  24. )
  25. class Permission(models.Model):
  26. """
  27. The permissions system provides a way to assign permissions to specific
  28. users and groups of users.
  29. The permission system is used by the Django admin site, but may also be
  30. useful in your own code. The Django admin site uses permissions as follows:
  31. - The "add" permission limits the user's ability to view the "add" form
  32. and add an object.
  33. - The "change" permission limits a user's ability to view the change
  34. list, view the "change" form and change an object.
  35. - The "delete" permission limits the ability to delete an object.
  36. - The "view" permission limits the ability to view an object.
  37. Permissions are set globally per type of object, not per specific object
  38. instance. It is possible to say "Mary may change news stories," but it's
  39. not currently possible to say "Mary may change news stories, but only the
  40. ones she created herself" or "Mary may only change news stories that have a
  41. certain status or publication date."
  42. The permissions listed above are automatically created for each model.
  43. """
  44. name = models.CharField(_('name'), max_length=255)
  45. content_type = models.ForeignKey(
  46. ContentType,
  47. models.CASCADE,
  48. verbose_name=_('content type'),
  49. )
  50. codename = models.CharField(_('codename'), max_length=100)
  51. objects = PermissionManager()
  52. class Meta:
  53. verbose_name = _('permission')
  54. verbose_name_plural = _('permissions')
  55. unique_together = (('content_type', 'codename'),)
  56. ordering = ('content_type__app_label', 'content_type__model',
  57. 'codename')
  58. def __str__(self):
  59. return "%s | %s | %s" % (
  60. self.content_type.app_label,
  61. self.content_type,
  62. self.name,
  63. )
  64. def natural_key(self):
  65. return (self.codename,) + self.content_type.natural_key()
  66. natural_key.dependencies = ['contenttypes.contenttype']
  67. class GroupManager(models.Manager):
  68. """
  69. The manager for the auth's Group model.
  70. """
  71. use_in_migrations = True
  72. def get_by_natural_key(self, name):
  73. return self.get(name=name)
  74. class Group(models.Model):
  75. """
  76. Groups are a generic way of categorizing users to apply permissions, or
  77. some other label, to those users. A user can belong to any number of
  78. groups.
  79. A user in a group automatically has all the permissions granted to that
  80. group. For example, if the group 'Site editors' has the permission
  81. can_edit_home_page, any user in that group will have that permission.
  82. Beyond permissions, groups are a convenient way to categorize users to
  83. apply some label, or extended functionality, to them. For example, you
  84. could create a group 'Special users', and you could write code that would
  85. do special things to those users -- such as giving them access to a
  86. members-only portion of your site, or sending them members-only email
  87. messages.
  88. """
  89. name = models.CharField(_('name'), max_length=80, unique=True)
  90. permissions = models.ManyToManyField(
  91. Permission,
  92. verbose_name=_('permissions'),
  93. blank=True,
  94. )
  95. objects = GroupManager()
  96. class Meta:
  97. verbose_name = _('group')
  98. verbose_name_plural = _('groups')
  99. def __str__(self):
  100. return self.name
  101. def natural_key(self):
  102. return (self.name,)
  103. class UserManager(BaseUserManager):
  104. use_in_migrations = True
  105. def _create_user(self, username, email, password, **extra_fields):
  106. """
  107. Create and save a user with the given username, email, and password.
  108. """
  109. if not username:
  110. raise ValueError('The given username must be set')
  111. email = self.normalize_email(email)
  112. username = self.model.normalize_username(username)
  113. user = self.model(username=username, email=email, **extra_fields)
  114. user.set_password(password)
  115. user.save(using=self._db)
  116. return user
  117. def create_user(self, username, email=None, password=None, **extra_fields):
  118. extra_fields.setdefault('is_staff', False)
  119. extra_fields.setdefault('is_superuser', False)
  120. return self._create_user(username, email, password, **extra_fields)
  121. def create_superuser(self, username, email, password, **extra_fields):
  122. extra_fields.setdefault('is_staff', True)
  123. extra_fields.setdefault('is_superuser', True)
  124. if extra_fields.get('is_staff') is not True:
  125. raise ValueError('Superuser must have is_staff=True.')
  126. if extra_fields.get('is_superuser') is not True:
  127. raise ValueError('Superuser must have is_superuser=True.')
  128. return self._create_user(username, email, password, **extra_fields)
  129. # A few helper functions for common logic between User and AnonymousUser.
  130. def _user_get_all_permissions(user, obj):
  131. permissions = set()
  132. for backend in auth.get_backends():
  133. if hasattr(backend, "get_all_permissions"):
  134. permissions.update(backend.get_all_permissions(user, obj))
  135. return permissions
  136. def _user_has_perm(user, perm, obj):
  137. """
  138. A backend can raise `PermissionDenied` to short-circuit permission checking.
  139. """
  140. for backend in auth.get_backends():
  141. if not hasattr(backend, 'has_perm'):
  142. continue
  143. try:
  144. if backend.has_perm(user, perm, obj):
  145. return True
  146. except PermissionDenied:
  147. return False
  148. return False
  149. def _user_has_module_perms(user, app_label):
  150. """
  151. A backend can raise `PermissionDenied` to short-circuit permission checking.
  152. """
  153. for backend in auth.get_backends():
  154. if not hasattr(backend, 'has_module_perms'):
  155. continue
  156. try:
  157. if backend.has_module_perms(user, app_label):
  158. return True
  159. except PermissionDenied:
  160. return False
  161. return False
  162. class PermissionsMixin(models.Model):
  163. """
  164. Add the fields and methods necessary to support the Group and Permission
  165. models using the ModelBackend.
  166. """
  167. is_superuser = models.BooleanField(
  168. _('superuser status'),
  169. default=False,
  170. help_text=_(
  171. 'Designates that this user has all permissions without '
  172. 'explicitly assigning them.'
  173. ),
  174. )
  175. groups = models.ManyToManyField(
  176. Group,
  177. verbose_name=_('groups'),
  178. blank=True,
  179. help_text=_(
  180. 'The groups this user belongs to. A user will get all permissions '
  181. 'granted to each of their groups.'
  182. ),
  183. related_name="user_set",
  184. related_query_name="user",
  185. )
  186. user_permissions = models.ManyToManyField(
  187. Permission,
  188. verbose_name=_('user permissions'),
  189. blank=True,
  190. help_text=_('Specific permissions for this user.'),
  191. related_name="user_set",
  192. related_query_name="user",
  193. )
  194. class Meta:
  195. abstract = True
  196. def get_group_permissions(self, obj=None):
  197. """
  198. Return a list of permission strings that this user has through their
  199. groups. Query all available auth backends. If an object is passed in,
  200. return only permissions matching this object.
  201. """
  202. permissions = set()
  203. for backend in auth.get_backends():
  204. if hasattr(backend, "get_group_permissions"):
  205. permissions.update(backend.get_group_permissions(self, obj))
  206. return permissions
  207. def get_all_permissions(self, obj=None):
  208. return _user_get_all_permissions(self, obj)
  209. def has_perm(self, perm, obj=None):
  210. """
  211. Return True if the user has the specified permission. Query all
  212. available auth backends, but return immediately if any backend returns
  213. True. Thus, a user who has permission from a single auth backend is
  214. assumed to have permission in general. If an object is provided, check
  215. permissions for that object.
  216. """
  217. # Active superusers have all permissions.
  218. if self.is_active and self.is_superuser:
  219. return True
  220. # Otherwise we need to check the backends.
  221. return _user_has_perm(self, perm, obj)
  222. def has_perms(self, perm_list, obj=None):
  223. """
  224. Return True if the user has each of the specified permissions. If
  225. object is passed, check if the user has all required perms for it.
  226. """
  227. return all(self.has_perm(perm, obj) for perm in perm_list)
  228. def has_module_perms(self, app_label):
  229. """
  230. Return True if the user has any permissions in the given app label.
  231. Use similar logic as has_perm(), above.
  232. """
  233. # Active superusers have all permissions.
  234. if self.is_active and self.is_superuser:
  235. return True
  236. return _user_has_module_perms(self, app_label)
  237. class AbstractUser(AbstractBaseUser, PermissionsMixin):
  238. """
  239. An abstract base class implementing a fully featured User model with
  240. admin-compliant permissions.
  241. Username and password are required. Other fields are optional.
  242. """
  243. username_validator = UnicodeUsernameValidator()
  244. username = models.CharField(
  245. _('username'),
  246. max_length=150,
  247. unique=True,
  248. help_text=_('Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.'),
  249. validators=[username_validator],
  250. error_messages={
  251. 'unique': _("A user with that username already exists."),
  252. },
  253. )
  254. first_name = models.CharField(_('first name'), max_length=30, blank=True)
  255. last_name = models.CharField(_('last name'), max_length=150, blank=True)
  256. email = models.EmailField(_('email address'), blank=True)
  257. is_staff = models.BooleanField(
  258. _('staff status'),
  259. default=False,
  260. help_text=_('Designates whether the user can log into this admin site.'),
  261. )
  262. is_active = models.BooleanField(
  263. _('active'),
  264. default=True,
  265. help_text=_(
  266. 'Designates whether this user should be treated as active. '
  267. 'Unselect this instead of deleting accounts.'
  268. ),
  269. )
  270. date_joined = models.DateTimeField(_('date joined'), default=timezone.now)
  271. objects = UserManager()
  272. EMAIL_FIELD = 'email'
  273. USERNAME_FIELD = 'username'
  274. REQUIRED_FIELDS = ['email']
  275. class Meta:
  276. verbose_name = _('user')
  277. verbose_name_plural = _('users')
  278. abstract = True
  279. def clean(self):
  280. super().clean()
  281. self.email = self.__class__.objects.normalize_email(self.email)
  282. def get_full_name(self):
  283. """
  284. Return the first_name plus the last_name, with a space in between.
  285. """
  286. full_name = '%s %s' % (self.first_name, self.last_name)
  287. return full_name.strip()
  288. def get_short_name(self):
  289. """Return the short name for the user."""
  290. return self.first_name
  291. def email_user(self, subject, message, from_email=None, **kwargs):
  292. """Send an email to this user."""
  293. send_mail(subject, message, from_email, [self.email], **kwargs)
  294. class User(AbstractUser):
  295. """
  296. Users within the Django authentication system are represented by this
  297. model.
  298. Username and password are required. Other fields are optional.
  299. """
  300. class Meta(AbstractUser.Meta):
  301. swappable = 'AUTH_USER_MODEL'
  302. class AnonymousUser:
  303. id = None
  304. pk = None
  305. username = ''
  306. is_staff = False
  307. is_active = False
  308. is_superuser = False
  309. _groups = EmptyManager(Group)
  310. _user_permissions = EmptyManager(Permission)
  311. def __str__(self):
  312. return 'AnonymousUser'
  313. def __eq__(self, other):
  314. return isinstance(other, self.__class__)
  315. def __hash__(self):
  316. return 1 # instances always return the same hash value
  317. def save(self):
  318. raise NotImplementedError("Django doesn't provide a DB representation for AnonymousUser.")
  319. def delete(self):
  320. raise NotImplementedError("Django doesn't provide a DB representation for AnonymousUser.")
  321. def set_password(self, raw_password):
  322. raise NotImplementedError("Django doesn't provide a DB representation for AnonymousUser.")
  323. def check_password(self, raw_password):
  324. raise NotImplementedError("Django doesn't provide a DB representation for AnonymousUser.")
  325. @property
  326. def groups(self):
  327. return self._groups
  328. @property
  329. def user_permissions(self):
  330. return self._user_permissions
  331. def get_group_permissions(self, obj=None):
  332. return set()
  333. def get_all_permissions(self, obj=None):
  334. return _user_get_all_permissions(self, obj=obj)
  335. def has_perm(self, perm, obj=None):
  336. return _user_has_perm(self, perm, obj=obj)
  337. def has_perms(self, perm_list, obj=None):
  338. return all(self.has_perm(perm, obj) for perm in perm_list)
  339. def has_module_perms(self, module):
  340. return _user_has_module_perms(self, module)
  341. @property
  342. def is_anonymous(self):
  343. return True
  344. @property
  345. def is_authenticated(self):
  346. return False
  347. def get_username(self):
  348. return self.username