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.

forms.py 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. import unicodedata
  2. from django import forms
  3. from django.contrib.auth import (
  4. authenticate, get_user_model, password_validation,
  5. )
  6. from django.contrib.auth.hashers import (
  7. UNUSABLE_PASSWORD_PREFIX, identify_hasher,
  8. )
  9. from django.contrib.auth.models import User
  10. from django.contrib.auth.tokens import default_token_generator
  11. from django.contrib.sites.shortcuts import get_current_site
  12. from django.core.mail import EmailMultiAlternatives
  13. from django.template import loader
  14. from django.utils.encoding import force_bytes
  15. from django.utils.http import urlsafe_base64_encode
  16. from django.utils.text import capfirst
  17. from django.utils.translation import gettext, gettext_lazy as _
  18. UserModel = get_user_model()
  19. class ReadOnlyPasswordHashWidget(forms.Widget):
  20. template_name = 'auth/widgets/read_only_password_hash.html'
  21. read_only = True
  22. def get_context(self, name, value, attrs):
  23. context = super().get_context(name, value, attrs)
  24. summary = []
  25. if not value or value.startswith(UNUSABLE_PASSWORD_PREFIX):
  26. summary.append({'label': gettext("No password set.")})
  27. else:
  28. try:
  29. hasher = identify_hasher(value)
  30. except ValueError:
  31. summary.append({'label': gettext("Invalid password format or unknown hashing algorithm.")})
  32. else:
  33. for key, value_ in hasher.safe_summary(value).items():
  34. summary.append({'label': gettext(key), 'value': value_})
  35. context['summary'] = summary
  36. return context
  37. class ReadOnlyPasswordHashField(forms.Field):
  38. widget = ReadOnlyPasswordHashWidget
  39. def __init__(self, *args, **kwargs):
  40. kwargs.setdefault("required", False)
  41. super().__init__(*args, **kwargs)
  42. def bound_data(self, data, initial):
  43. # Always return initial because the widget doesn't
  44. # render an input field.
  45. return initial
  46. def has_changed(self, initial, data):
  47. return False
  48. class UsernameField(forms.CharField):
  49. def to_python(self, value):
  50. return unicodedata.normalize('NFKC', super().to_python(value))
  51. class UserCreationForm(forms.ModelForm):
  52. """
  53. A form that creates a user, with no privileges, from the given username and
  54. password.
  55. """
  56. error_messages = {
  57. 'password_mismatch': _("The two password fields didn't match."),
  58. }
  59. password1 = forms.CharField(
  60. label=_("Password"),
  61. strip=False,
  62. widget=forms.PasswordInput,
  63. help_text=password_validation.password_validators_help_text_html(),
  64. )
  65. password2 = forms.CharField(
  66. label=_("Password confirmation"),
  67. widget=forms.PasswordInput,
  68. strip=False,
  69. help_text=_("Enter the same password as before, for verification."),
  70. )
  71. class Meta:
  72. model = User
  73. fields = ("username",)
  74. field_classes = {'username': UsernameField}
  75. def __init__(self, *args, **kwargs):
  76. super().__init__(*args, **kwargs)
  77. if self._meta.model.USERNAME_FIELD in self.fields:
  78. self.fields[self._meta.model.USERNAME_FIELD].widget.attrs.update({'autofocus': True})
  79. def clean_password2(self):
  80. password1 = self.cleaned_data.get("password1")
  81. password2 = self.cleaned_data.get("password2")
  82. if password1 and password2 and password1 != password2:
  83. raise forms.ValidationError(
  84. self.error_messages['password_mismatch'],
  85. code='password_mismatch',
  86. )
  87. return password2
  88. def _post_clean(self):
  89. super()._post_clean()
  90. # Validate the password after self.instance is updated with form data
  91. # by super().
  92. password = self.cleaned_data.get('password2')
  93. if password:
  94. try:
  95. password_validation.validate_password(password, self.instance)
  96. except forms.ValidationError as error:
  97. self.add_error('password2', error)
  98. def save(self, commit=True):
  99. user = super().save(commit=False)
  100. user.set_password(self.cleaned_data["password1"])
  101. if commit:
  102. user.save()
  103. return user
  104. class UserChangeForm(forms.ModelForm):
  105. password = ReadOnlyPasswordHashField(
  106. label=_("Password"),
  107. help_text=_(
  108. "Raw passwords are not stored, so there is no way to see this "
  109. "user's password, but you can change the password using "
  110. "<a href=\"{}\">this form</a>."
  111. ),
  112. )
  113. class Meta:
  114. model = User
  115. fields = '__all__'
  116. field_classes = {'username': UsernameField}
  117. def __init__(self, *args, **kwargs):
  118. super().__init__(*args, **kwargs)
  119. password = self.fields.get('password')
  120. if password:
  121. password.help_text = password.help_text.format('../password/')
  122. user_permissions = self.fields.get('user_permissions')
  123. if user_permissions:
  124. user_permissions.queryset = user_permissions.queryset.select_related('content_type')
  125. def clean_password(self):
  126. # Regardless of what the user provides, return the initial value.
  127. # This is done here, rather than on the field, because the
  128. # field does not have access to the initial value
  129. return self.initial.get('password')
  130. class AuthenticationForm(forms.Form):
  131. """
  132. Base class for authenticating users. Extend this to get a form that accepts
  133. username/password logins.
  134. """
  135. username = UsernameField(widget=forms.TextInput(attrs={'autofocus': True}))
  136. password = forms.CharField(
  137. label=_("Password"),
  138. strip=False,
  139. widget=forms.PasswordInput,
  140. )
  141. error_messages = {
  142. 'invalid_login': _(
  143. "Please enter a correct %(username)s and password. Note that both "
  144. "fields may be case-sensitive."
  145. ),
  146. 'inactive': _("This account is inactive."),
  147. }
  148. def __init__(self, request=None, *args, **kwargs):
  149. """
  150. The 'request' parameter is set for custom auth use by subclasses.
  151. The form data comes in via the standard 'data' kwarg.
  152. """
  153. self.request = request
  154. self.user_cache = None
  155. super().__init__(*args, **kwargs)
  156. # Set the max length and label for the "username" field.
  157. self.username_field = UserModel._meta.get_field(UserModel.USERNAME_FIELD)
  158. self.fields['username'].max_length = self.username_field.max_length or 254
  159. if self.fields['username'].label is None:
  160. self.fields['username'].label = capfirst(self.username_field.verbose_name)
  161. def clean(self):
  162. username = self.cleaned_data.get('username')
  163. password = self.cleaned_data.get('password')
  164. if username is not None and password:
  165. self.user_cache = authenticate(self.request, username=username, password=password)
  166. if self.user_cache is None:
  167. raise self.get_invalid_login_error()
  168. else:
  169. self.confirm_login_allowed(self.user_cache)
  170. return self.cleaned_data
  171. def confirm_login_allowed(self, user):
  172. """
  173. Controls whether the given User may log in. This is a policy setting,
  174. independent of end-user authentication. This default behavior is to
  175. allow login by active users, and reject login by inactive users.
  176. If the given user cannot log in, this method should raise a
  177. ``forms.ValidationError``.
  178. If the given user may log in, this method should return None.
  179. """
  180. if not user.is_active:
  181. raise forms.ValidationError(
  182. self.error_messages['inactive'],
  183. code='inactive',
  184. )
  185. def get_user(self):
  186. return self.user_cache
  187. def get_invalid_login_error(self):
  188. return forms.ValidationError(
  189. self.error_messages['invalid_login'],
  190. code='invalid_login',
  191. params={'username': self.username_field.verbose_name},
  192. )
  193. class PasswordResetForm(forms.Form):
  194. email = forms.EmailField(label=_("Email"), max_length=254)
  195. def send_mail(self, subject_template_name, email_template_name,
  196. context, from_email, to_email, html_email_template_name=None):
  197. """
  198. Send a django.core.mail.EmailMultiAlternatives to `to_email`.
  199. """
  200. subject = loader.render_to_string(subject_template_name, context)
  201. # Email subject *must not* contain newlines
  202. subject = ''.join(subject.splitlines())
  203. body = loader.render_to_string(email_template_name, context)
  204. email_message = EmailMultiAlternatives(subject, body, from_email, [to_email])
  205. if html_email_template_name is not None:
  206. html_email = loader.render_to_string(html_email_template_name, context)
  207. email_message.attach_alternative(html_email, 'text/html')
  208. email_message.send()
  209. def get_users(self, email):
  210. """Given an email, return matching user(s) who should receive a reset.
  211. This allows subclasses to more easily customize the default policies
  212. that prevent inactive users and users with unusable passwords from
  213. resetting their password.
  214. """
  215. active_users = UserModel._default_manager.filter(**{
  216. '%s__iexact' % UserModel.get_email_field_name(): email,
  217. 'is_active': True,
  218. })
  219. return (u for u in active_users if u.has_usable_password())
  220. def save(self, domain_override=None,
  221. subject_template_name='registration/password_reset_subject.txt',
  222. email_template_name='registration/password_reset_email.html',
  223. use_https=False, token_generator=default_token_generator,
  224. from_email=None, request=None, html_email_template_name=None,
  225. extra_email_context=None):
  226. """
  227. Generate a one-use only link for resetting password and send it to the
  228. user.
  229. """
  230. email = self.cleaned_data["email"]
  231. for user in self.get_users(email):
  232. if not domain_override:
  233. current_site = get_current_site(request)
  234. site_name = current_site.name
  235. domain = current_site.domain
  236. else:
  237. site_name = domain = domain_override
  238. context = {
  239. 'email': email,
  240. 'domain': domain,
  241. 'site_name': site_name,
  242. 'uid': urlsafe_base64_encode(force_bytes(user.pk)).decode(),
  243. 'user': user,
  244. 'token': token_generator.make_token(user),
  245. 'protocol': 'https' if use_https else 'http',
  246. **(extra_email_context or {}),
  247. }
  248. self.send_mail(
  249. subject_template_name, email_template_name, context, from_email,
  250. email, html_email_template_name=html_email_template_name,
  251. )
  252. class SetPasswordForm(forms.Form):
  253. """
  254. A form that lets a user change set their password without entering the old
  255. password
  256. """
  257. error_messages = {
  258. 'password_mismatch': _("The two password fields didn't match."),
  259. }
  260. new_password1 = forms.CharField(
  261. label=_("New password"),
  262. widget=forms.PasswordInput,
  263. strip=False,
  264. help_text=password_validation.password_validators_help_text_html(),
  265. )
  266. new_password2 = forms.CharField(
  267. label=_("New password confirmation"),
  268. strip=False,
  269. widget=forms.PasswordInput,
  270. )
  271. def __init__(self, user, *args, **kwargs):
  272. self.user = user
  273. super().__init__(*args, **kwargs)
  274. def clean_new_password2(self):
  275. password1 = self.cleaned_data.get('new_password1')
  276. password2 = self.cleaned_data.get('new_password2')
  277. if password1 and password2:
  278. if password1 != password2:
  279. raise forms.ValidationError(
  280. self.error_messages['password_mismatch'],
  281. code='password_mismatch',
  282. )
  283. password_validation.validate_password(password2, self.user)
  284. return password2
  285. def save(self, commit=True):
  286. password = self.cleaned_data["new_password1"]
  287. self.user.set_password(password)
  288. if commit:
  289. self.user.save()
  290. return self.user
  291. class PasswordChangeForm(SetPasswordForm):
  292. """
  293. A form that lets a user change their password by entering their old
  294. password.
  295. """
  296. error_messages = {
  297. **SetPasswordForm.error_messages,
  298. 'password_incorrect': _("Your old password was entered incorrectly. Please enter it again."),
  299. }
  300. old_password = forms.CharField(
  301. label=_("Old password"),
  302. strip=False,
  303. widget=forms.PasswordInput(attrs={'autofocus': True}),
  304. )
  305. field_order = ['old_password', 'new_password1', 'new_password2']
  306. def clean_old_password(self):
  307. """
  308. Validate that the old_password field is correct.
  309. """
  310. old_password = self.cleaned_data["old_password"]
  311. if not self.user.check_password(old_password):
  312. raise forms.ValidationError(
  313. self.error_messages['password_incorrect'],
  314. code='password_incorrect',
  315. )
  316. return old_password
  317. class AdminPasswordChangeForm(forms.Form):
  318. """
  319. A form used to change the password of a user in the admin interface.
  320. """
  321. error_messages = {
  322. 'password_mismatch': _("The two password fields didn't match."),
  323. }
  324. required_css_class = 'required'
  325. password1 = forms.CharField(
  326. label=_("Password"),
  327. widget=forms.PasswordInput(attrs={'autofocus': True}),
  328. strip=False,
  329. help_text=password_validation.password_validators_help_text_html(),
  330. )
  331. password2 = forms.CharField(
  332. label=_("Password (again)"),
  333. widget=forms.PasswordInput,
  334. strip=False,
  335. help_text=_("Enter the same password as before, for verification."),
  336. )
  337. def __init__(self, user, *args, **kwargs):
  338. self.user = user
  339. super().__init__(*args, **kwargs)
  340. def clean_password2(self):
  341. password1 = self.cleaned_data.get('password1')
  342. password2 = self.cleaned_data.get('password2')
  343. if password1 and password2:
  344. if password1 != password2:
  345. raise forms.ValidationError(
  346. self.error_messages['password_mismatch'],
  347. code='password_mismatch',
  348. )
  349. password_validation.validate_password(password2, self.user)
  350. return password2
  351. def save(self, commit=True):
  352. """Save the new password."""
  353. password = self.cleaned_data["password1"]
  354. self.user.set_password(password)
  355. if commit:
  356. self.user.save()
  357. return self.user
  358. @property
  359. def changed_data(self):
  360. data = super().changed_data
  361. for name in self.fields:
  362. if name not in data:
  363. return []
  364. return ['password']