Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
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 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  1. from django.apps import apps
  2. from django.contrib import auth
  3. from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
  4. from django.contrib.auth.hashers import make_password
  5. from django.contrib.contenttypes.models import ContentType
  6. from django.core.exceptions import PermissionDenied
  7. from django.core.mail import send_mail
  8. from django.db import models
  9. from django.db.models.manager import EmptyManager
  10. from django.utils import timezone
  11. from django.utils.itercompat import is_iterable
  12. from django.utils.translation import gettext_lazy as _
  13. from .validators import UnicodeUsernameValidator
  14. def update_last_login(sender, user, **kwargs):
  15. """
  16. A signal receiver which updates the last_login date for
  17. the user logging in.
  18. """
  19. user.last_login = timezone.now()
  20. user.save(update_fields=["last_login"])
  21. class PermissionManager(models.Manager):
  22. use_in_migrations = True
  23. def get_by_natural_key(self, codename, app_label, model):
  24. return self.get(
  25. codename=codename,
  26. content_type=ContentType.objects.db_manager(self.db).get_by_natural_key(
  27. app_label, model
  28. ),
  29. )
  30. class Permission(models.Model):
  31. """
  32. The permissions system provides a way to assign permissions to specific
  33. users and groups of users.
  34. The permission system is used by the Django admin site, but may also be
  35. useful in your own code. The Django admin site uses permissions as follows:
  36. - The "add" permission limits the user's ability to view the "add" form
  37. and add an object.
  38. - The "change" permission limits a user's ability to view the change
  39. list, view the "change" form and change an object.
  40. - The "delete" permission limits the ability to delete an object.
  41. - The "view" permission limits the ability to view an object.
  42. Permissions are set globally per type of object, not per specific object
  43. instance. It is possible to say "Mary may change news stories," but it's
  44. not currently possible to say "Mary may change news stories, but only the
  45. ones she created herself" or "Mary may only change news stories that have a
  46. certain status or publication date."
  47. The permissions listed above are automatically created for each model.
  48. """
  49. name = models.CharField(_("name"), max_length=255)
  50. content_type = models.ForeignKey(
  51. ContentType,
  52. models.CASCADE,
  53. verbose_name=_("content type"),
  54. )
  55. codename = models.CharField(_("codename"), max_length=100)
  56. objects = PermissionManager()
  57. class Meta:
  58. verbose_name = _("permission")
  59. verbose_name_plural = _("permissions")
  60. unique_together = [["content_type", "codename"]]
  61. ordering = ["content_type__app_label", "content_type__model", "codename"]
  62. def __str__(self):
  63. return "%s | %s" % (self.content_type, self.name)
  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=150, 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. # Lookup the real model class from the global app registry so this
  113. # manager method can be used in migrations. This is fine because
  114. # managers are by definition working on the real model.
  115. GlobalUserModel = apps.get_model(
  116. self.model._meta.app_label, self.model._meta.object_name
  117. )
  118. username = GlobalUserModel.normalize_username(username)
  119. user = self.model(username=username, email=email, **extra_fields)
  120. user.password = make_password(password)
  121. user.save(using=self._db)
  122. return user
  123. def create_user(self, username, email=None, password=None, **extra_fields):
  124. extra_fields.setdefault("is_staff", False)
  125. extra_fields.setdefault("is_superuser", False)
  126. return self._create_user(username, email, password, **extra_fields)
  127. def create_superuser(self, username, email=None, password=None, **extra_fields):
  128. extra_fields.setdefault("is_staff", True)
  129. extra_fields.setdefault("is_superuser", True)
  130. if extra_fields.get("is_staff") is not True:
  131. raise ValueError("Superuser must have is_staff=True.")
  132. if extra_fields.get("is_superuser") is not True:
  133. raise ValueError("Superuser must have is_superuser=True.")
  134. return self._create_user(username, email, password, **extra_fields)
  135. def with_perm(
  136. self, perm, is_active=True, include_superusers=True, backend=None, obj=None
  137. ):
  138. if backend is None:
  139. backends = auth._get_backends(return_tuples=True)
  140. if len(backends) == 1:
  141. backend, _ = backends[0]
  142. else:
  143. raise ValueError(
  144. "You have multiple authentication backends configured and "
  145. "therefore must provide the `backend` argument."
  146. )
  147. elif not isinstance(backend, str):
  148. raise TypeError(
  149. "backend must be a dotted import path string (got %r)." % backend
  150. )
  151. else:
  152. backend = auth.load_backend(backend)
  153. if hasattr(backend, "with_perm"):
  154. return backend.with_perm(
  155. perm,
  156. is_active=is_active,
  157. include_superusers=include_superusers,
  158. obj=obj,
  159. )
  160. return self.none()
  161. # A few helper functions for common logic between User and AnonymousUser.
  162. def _user_get_permissions(user, obj, from_name):
  163. permissions = set()
  164. name = "get_%s_permissions" % from_name
  165. for backend in auth.get_backends():
  166. if hasattr(backend, name):
  167. permissions.update(getattr(backend, name)(user, obj))
  168. return permissions
  169. def _user_has_perm(user, perm, obj):
  170. """
  171. A backend can raise `PermissionDenied` to short-circuit permission checking.
  172. """
  173. for backend in auth.get_backends():
  174. if not hasattr(backend, "has_perm"):
  175. continue
  176. try:
  177. if backend.has_perm(user, perm, obj):
  178. return True
  179. except PermissionDenied:
  180. return False
  181. return False
  182. def _user_has_module_perms(user, app_label):
  183. """
  184. A backend can raise `PermissionDenied` to short-circuit permission checking.
  185. """
  186. for backend in auth.get_backends():
  187. if not hasattr(backend, "has_module_perms"):
  188. continue
  189. try:
  190. if backend.has_module_perms(user, app_label):
  191. return True
  192. except PermissionDenied:
  193. return False
  194. return False
  195. class PermissionsMixin(models.Model):
  196. """
  197. Add the fields and methods necessary to support the Group and Permission
  198. models using the ModelBackend.
  199. """
  200. is_superuser = models.BooleanField(
  201. _("superuser status"),
  202. default=False,
  203. help_text=_(
  204. "Designates that this user has all permissions without "
  205. "explicitly assigning them."
  206. ),
  207. )
  208. groups = models.ManyToManyField(
  209. Group,
  210. verbose_name=_("groups"),
  211. blank=True,
  212. help_text=_(
  213. "The groups this user belongs to. A user will get all permissions "
  214. "granted to each of their groups."
  215. ),
  216. related_name="user_set",
  217. related_query_name="user",
  218. )
  219. user_permissions = models.ManyToManyField(
  220. Permission,
  221. verbose_name=_("user permissions"),
  222. blank=True,
  223. help_text=_("Specific permissions for this user."),
  224. related_name="user_set",
  225. related_query_name="user",
  226. )
  227. class Meta:
  228. abstract = True
  229. def get_user_permissions(self, obj=None):
  230. """
  231. Return a list of permission strings that this user has directly.
  232. Query all available auth backends. If an object is passed in,
  233. return only permissions matching this object.
  234. """
  235. return _user_get_permissions(self, obj, "user")
  236. def get_group_permissions(self, obj=None):
  237. """
  238. Return a list of permission strings that this user has through their
  239. groups. Query all available auth backends. If an object is passed in,
  240. return only permissions matching this object.
  241. """
  242. return _user_get_permissions(self, obj, "group")
  243. def get_all_permissions(self, obj=None):
  244. return _user_get_permissions(self, obj, "all")
  245. def has_perm(self, perm, obj=None):
  246. """
  247. Return True if the user has the specified permission. Query all
  248. available auth backends, but return immediately if any backend returns
  249. True. Thus, a user who has permission from a single auth backend is
  250. assumed to have permission in general. If an object is provided, check
  251. permissions for that object.
  252. """
  253. # Active superusers have all permissions.
  254. if self.is_active and self.is_superuser:
  255. return True
  256. # Otherwise we need to check the backends.
  257. return _user_has_perm(self, perm, obj)
  258. def has_perms(self, perm_list, obj=None):
  259. """
  260. Return True if the user has each of the specified permissions. If
  261. object is passed, check if the user has all required perms for it.
  262. """
  263. if not is_iterable(perm_list) or isinstance(perm_list, str):
  264. raise ValueError("perm_list must be an iterable of permissions.")
  265. return all(self.has_perm(perm, obj) for perm in perm_list)
  266. def has_module_perms(self, app_label):
  267. """
  268. Return True if the user has any permissions in the given app label.
  269. Use similar logic as has_perm(), above.
  270. """
  271. # Active superusers have all permissions.
  272. if self.is_active and self.is_superuser:
  273. return True
  274. return _user_has_module_perms(self, app_label)
  275. class AbstractUser(AbstractBaseUser, PermissionsMixin):
  276. """
  277. An abstract base class implementing a fully featured User model with
  278. admin-compliant permissions.
  279. Username and password are required. Other fields are optional.
  280. """
  281. username_validator = UnicodeUsernameValidator()
  282. username = models.CharField(
  283. _("username"),
  284. max_length=150,
  285. unique=True,
  286. help_text=_(
  287. "Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only."
  288. ),
  289. validators=[username_validator],
  290. error_messages={
  291. "unique": _("A user with that username already exists."),
  292. },
  293. )
  294. first_name = models.CharField(_("first name"), max_length=150, blank=True)
  295. last_name = models.CharField(_("last name"), max_length=150, blank=True)
  296. email = models.EmailField(_("email address"), blank=True)
  297. is_staff = models.BooleanField(
  298. _("staff status"),
  299. default=False,
  300. help_text=_("Designates whether the user can log into this admin site."),
  301. )
  302. is_active = models.BooleanField(
  303. _("active"),
  304. default=True,
  305. help_text=_(
  306. "Designates whether this user should be treated as active. "
  307. "Unselect this instead of deleting accounts."
  308. ),
  309. )
  310. date_joined = models.DateTimeField(_("date joined"), default=timezone.now)
  311. objects = UserManager()
  312. EMAIL_FIELD = "email"
  313. USERNAME_FIELD = "username"
  314. REQUIRED_FIELDS = ["email"]
  315. class Meta:
  316. verbose_name = _("user")
  317. verbose_name_plural = _("users")
  318. abstract = True
  319. def clean(self):
  320. super().clean()
  321. self.email = self.__class__.objects.normalize_email(self.email)
  322. def get_full_name(self):
  323. """
  324. Return the first_name plus the last_name, with a space in between.
  325. """
  326. full_name = "%s %s" % (self.first_name, self.last_name)
  327. return full_name.strip()
  328. def get_short_name(self):
  329. """Return the short name for the user."""
  330. return self.first_name
  331. def email_user(self, subject, message, from_email=None, **kwargs):
  332. """Send an email to this user."""
  333. send_mail(subject, message, from_email, [self.email], **kwargs)
  334. class User(AbstractUser):
  335. """
  336. Users within the Django authentication system are represented by this
  337. model.
  338. Username and password are required. Other fields are optional.
  339. """
  340. class Meta(AbstractUser.Meta):
  341. swappable = "AUTH_USER_MODEL"
  342. class AnonymousUser:
  343. id = None
  344. pk = None
  345. username = ""
  346. is_staff = False
  347. is_active = False
  348. is_superuser = False
  349. _groups = EmptyManager(Group)
  350. _user_permissions = EmptyManager(Permission)
  351. def __str__(self):
  352. return "AnonymousUser"
  353. def __eq__(self, other):
  354. return isinstance(other, self.__class__)
  355. def __hash__(self):
  356. return 1 # instances always return the same hash value
  357. def __int__(self):
  358. raise TypeError(
  359. "Cannot cast AnonymousUser to int. Are you trying to use it in place of "
  360. "User?"
  361. )
  362. def save(self):
  363. raise NotImplementedError(
  364. "Django doesn't provide a DB representation for AnonymousUser."
  365. )
  366. def delete(self):
  367. raise NotImplementedError(
  368. "Django doesn't provide a DB representation for AnonymousUser."
  369. )
  370. def set_password(self, raw_password):
  371. raise NotImplementedError(
  372. "Django doesn't provide a DB representation for AnonymousUser."
  373. )
  374. def check_password(self, raw_password):
  375. raise NotImplementedError(
  376. "Django doesn't provide a DB representation for AnonymousUser."
  377. )
  378. @property
  379. def groups(self):
  380. return self._groups
  381. @property
  382. def user_permissions(self):
  383. return self._user_permissions
  384. def get_user_permissions(self, obj=None):
  385. return _user_get_permissions(self, obj, "user")
  386. def get_group_permissions(self, obj=None):
  387. return set()
  388. def get_all_permissions(self, obj=None):
  389. return _user_get_permissions(self, obj, "all")
  390. def has_perm(self, perm, obj=None):
  391. return _user_has_perm(self, perm, obj=obj)
  392. def has_perms(self, perm_list, obj=None):
  393. if not is_iterable(perm_list) or isinstance(perm_list, str):
  394. raise ValueError("perm_list must be an iterable of permissions.")
  395. return all(self.has_perm(perm, obj) for perm in perm_list)
  396. def has_module_perms(self, module):
  397. return _user_has_module_perms(self, module)
  398. @property
  399. def is_anonymous(self):
  400. return True
  401. @property
  402. def is_authenticated(self):
  403. return False
  404. def get_username(self):
  405. return self.username