-
Notifications
You must be signed in to change notification settings - Fork 128
Expand file tree
/
Copy pathauth.py
More file actions
1542 lines (1211 loc) · 52.7 KB
/
Copy pathauth.py
File metadata and controls
1542 lines (1211 loc) · 52.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
__copyright__ = "Copyright (C) 2014 Andreas Kloeckner"
__license__ = """
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
import re
from collections.abc import Callable
from typing import (
TYPE_CHECKING,
Any,
Concatenate,
ParamSpec,
TypeAlias,
cast,
)
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Button, Div, Layout, Submit
from django import forms, http
from django.conf import settings
from django.contrib import messages
from django.contrib.auth import (
REDIRECT_FIELD_NAME,
get_user_model,
login as auth_login,
logout as auth_logout,
)
from django.contrib.auth.decorators import login_required, user_passes_test
from django.contrib.auth.forms import AuthenticationForm as AuthenticationFormBase
from django.contrib.auth.validators import ASCIIUsernameValidator
from django.core.exceptions import (
MultipleObjectsReturned,
ObjectDoesNotExist,
PermissionDenied,
SuspiciousOperation,
)
from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404, redirect, render, resolve_url
from django.template.response import TemplateResponse
from django.urls import reverse
from django.utils.http import url_has_allowed_host_and_scheme
from django.utils.translation import gettext_lazy as _
from django.views.decorators.cache import never_cache
from django.views.decorators.csrf import csrf_protect
from django.views.decorators.debug import sensitive_post_parameters
from django_tomselect.app_settings import TomSelectConfig
from django_tomselect.autocompletes import AutocompleteModelView
from django_tomselect.forms import TomSelectModelChoiceField
from djangosaml2.backends import Saml2Backend
from accounts.models import User
from course.constants import (
ParticipationPermission as PPerm,
ParticipationStatus,
UserStatus,
)
from course.models import (
AuthenticationToken,
Participation,
ParticipationRole,
)
from course.utils import CoursePageContext, course_view, render_course_page
from relate.utils import (
HTML5DateTimeInput,
RelateHttpRequest,
StyledForm,
StyledModelForm,
get_site_name,
is_authed,
string_concat,
)
if TYPE_CHECKING:
import datetime
from django.db.models import query
# {{{ impersonation
def get_pre_impersonation_user(request: RelateHttpRequest):
is_impersonating = hasattr(
request, "relate_impersonate_original_user")
if is_impersonating:
return request.relate_impersonate_original_user
return None
def get_impersonable_user_qset(impersonator: User) -> query.QuerySet[User]:
if impersonator.is_superuser:
return User.objects.exclude(pk=impersonator.pk)
my_participations = Participation.objects.filter(
user=impersonator,
status=ParticipationStatus.active)
impersonable_user_qset = User.objects.none()
for part in my_participations:
# Notice: if a TA is not allowed to view participants'
# profile in one course, then he/she is not able to impersonate
# any user, even in courses he/she is allow to view profiles
# of all users.
if part.has_permission(PPerm.view_participant_masked_profile):
return User.objects.none()
impersonable_roles = [
argument
for perm, argument in part.permissions()
if perm == PPerm.impersonate_role]
q = (Participation.objects
.filter(course=part.course,
status=ParticipationStatus.active,
roles__identifier__in=impersonable_roles)
.select_related("user"))
# There can be duplicate records. Removing duplicate records is needed
# only when rendering ImpersonateForm
impersonable_user_qset = (
impersonable_user_qset
| User.objects.filter(pk__in=q.values_list("user__pk", flat=True))
)
return impersonable_user_qset
class ImpersonateMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
if "impersonate_id" in request.session:
imp_id = request.session["impersonate_id"]
impersonee = None
try:
if imp_id is not None:
impersonee = cast("User", get_user_model().objects.get(id=imp_id))
except ObjectDoesNotExist:
pass
may_impersonate = False
if impersonee is not None:
if request.user.is_superuser:
may_impersonate = True
else:
qset = get_impersonable_user_qset(cast("User", request.user))
if qset.filter(pk=cast("User", impersonee).pk).count():
may_impersonate = True
if may_impersonate:
request.relate_impersonate_original_user = request.user
request.user = impersonee
else:
messages.add_message(request, messages.ERROR,
_("Error while impersonating."))
return self.get_response(request)
class UserAutocompleteView(AutocompleteModelView):
"""Autocomplete view for user search in the impersonation form."""
model = User
search_lookups = [
"username__icontains",
"email__icontains",
"first_name__icontains",
"last_name__icontains",
]
value_fields = ["id", "username", "email", "first_name", "last_name"]
virtual_fields = ["label"]
def get_queryset(self):
qset = get_impersonable_user_qset(
cast("User", self.request.user)) # type: ignore[attr-defined]
queryset = (User.objects
.filter(pk__in=qset.values_list("pk", flat=True))
.order_by("last_name", "first_name", "username"))
return self.search(queryset, self.query)
def hook_prepare_results(self, results):
prepared = []
for item in results:
if item.get("first_name") and item.get("last_name"):
label = (
f"{item['first_name']} {item['last_name']}"
f" ({item['username']} - {item['email']})")
else:
label = f"{item['username']} ({item['email']})"
item["label"] = label
prepared.append(item)
return prepared
class ImpersonateForm(StyledForm):
def __init__(self, *args: Any, **kwargs: Any) -> None:
kwargs.pop("impersonable_qset")
super().__init__(*args, **kwargs)
self.fields["user"] = TomSelectModelChoiceField(
required=True,
help_text=_("Select user to impersonate."),
config=TomSelectConfig(
url="user-autocomplete",
value_field="id",
label_field="label",
minimum_query_length=0,
preload=True,
),
label=_("User"))
self.fields["add_impersonation_header"] = forms.BooleanField(
required=False,
initial=True,
label=_("Add impersonation header"),
help_text=_("Add impersonation header to every page rendered "
"while impersonating, as a reminder that impersonation "
"is in progress."))
self.helper.add_input(Submit("submit", _("Impersonate")))
def impersonate(request: http.HttpRequest) -> http.HttpResponse:
if not is_authed(request.user):
raise PermissionDenied()
impersonable_user_qset = get_impersonable_user_qset(cast("User", request.user))
if not impersonable_user_qset.count():
raise PermissionDenied()
if hasattr(request, "relate_impersonate_original_user"):
messages.add_message(request, messages.ERROR,
_("Already impersonating someone."))
return redirect("relate-home")
# Remove duplicate and sort
# order_by().distinct() directly on impersonable_user_qset will not work
qset = (User.objects
.filter(pk__in=impersonable_user_qset.values_list("pk", flat=True))
.order_by("last_name", "first_name", "username"))
if request.method == "POST":
form = ImpersonateForm(request.POST, impersonable_qset=qset)
if form.is_valid():
impersonee = form.cleaned_data["user"]
request.session["impersonate_id"] = impersonee.id
request.session["relate_impersonation_header"] = form.cleaned_data[
"add_impersonation_header"]
# Because we'll likely no longer have access to this page.
return redirect("relate-home")
else:
form = ImpersonateForm(impersonable_qset=qset)
return render(request, "generic-form.html", {
"form_description": _("Impersonate user"),
"form": form
})
def stop_impersonating(request: http.HttpRequest) -> http.JsonResponse:
if request.method != "POST":
raise PermissionDenied(_("only AJAX POST is allowed"))
if not request.user.is_authenticated:
raise PermissionDenied()
if "stop_impersonating" not in request.POST:
raise SuspiciousOperation(_("odd POST parameters"))
if not hasattr(request, "relate_impersonate_original_user"):
# prevent user without pperm to stop_impersonating
my_participations = Participation.objects.filter(
user=request.user,
status=ParticipationStatus.active)
may_impersonate = False
for part in my_participations:
perms = [
perm
for perm, argument in part.permissions()
if perm == PPerm.impersonate_role]
if any(perms):
may_impersonate = True
break
if not may_impersonate:
raise PermissionDenied(_("may not stop impersonating"))
messages.add_message(request, messages.ERROR,
_("Not currently impersonating anyone."))
return http.JsonResponse({})
del request.session["impersonate_id"]
messages.add_message(request, messages.INFO,
_("No longer impersonating anyone."))
return http.JsonResponse({"result": "success"})
def impersonation_context_processor(request):
return {
"currently_impersonating":
hasattr(request, "relate_impersonate_original_user"),
"add_impersonation_header":
request.session.get("relate_impersonation_header", True),
}
# }}}
def make_sign_in_key(user: User) -> str:
# Try to ensure these hashes aren't guessable.
import hashlib
import random
from time import time
m = hashlib.sha1()
m.update(user.email.encode("utf-8"))
m.update(hex(random.getrandbits(128)).encode())
m.update(str(time()).encode("utf-8"))
return m.hexdigest()
def logout_confirmation_required(
func=None, redirect_field_name=REDIRECT_FIELD_NAME,
logout_confirmation_url="relate-logout-confirmation"):
"""
Decorator for views that checks that no user is logged in.
If a user is currently logged in, redirect him/her to the logout
confirmation page.
"""
actual_decorator = user_passes_test(
lambda u: u.is_anonymous,
login_url=logout_confirmation_url,
redirect_field_name=redirect_field_name
)
if func:
return actual_decorator(func)
return actual_decorator
class EmailedTokenBackend:
def authenticate(self, request, user_id=None, token=None):
users = get_user_model().objects.filter(
id=user_id, sign_in_key=token)
assert users.count() <= 1
if users.count() == 0:
return None
(user,) = users
user.status = UserStatus.active
user.sign_in_key = None
user.save()
return user
def get_user(self, user_id):
try:
return get_user_model().objects.get(pk=user_id)
except get_user_model().DoesNotExist:
return None
# {{{ choice
@logout_confirmation_required
def sign_in_choice(request, redirect_field_name=REDIRECT_FIELD_NAME):
redirect_to = request.POST.get(redirect_field_name,
request.GET.get(redirect_field_name, ""))
next_uri = ""
if redirect_to:
next_uri = f"?{redirect_field_name}={redirect_to}"
return render(request, "sign-in-choice.html", {
"next_uri": next_uri,
"social_provider_to_logo": {
"google-oauth2": "google",
},
"social_provider_to_human_name": {
"google-oauth2": "Google",
},
})
# }}}
# {{{ conventional login
class LoginForm(AuthenticationFormBase):
def __init__(self, *args, **kwargs):
self.helper = FormHelper()
self.helper.form_tag = False
self.helper.label_class = "col-lg-2"
self.helper.field_class = "col-lg-8"
self.helper.add_input(Submit("submit", _("Sign in")))
super().__init__(*args, **kwargs)
@sensitive_post_parameters()
@csrf_protect
@never_cache
@logout_confirmation_required
def sign_in_by_user_pw(request, redirect_field_name=REDIRECT_FIELD_NAME):
"""
Displays the login form and handles the login action.
"""
if not settings.RELATE_SIGN_IN_BY_USERNAME_ENABLED:
messages.add_message(request, messages.ERROR,
_("Username-based sign-in is not being used"))
return redirect("relate-sign_in_choice")
redirect_to = request.POST.get(redirect_field_name,
request.GET.get(redirect_field_name, ""))
if request.method == "POST":
form = LoginForm(request, data=request.POST)
if form.is_valid():
# Ensure the user-originating redirection url is safe.
if not url_has_allowed_host_and_scheme(
url=redirect_to,
allowed_hosts={request.get_host()},
require_https=request.is_secure()):
redirect_to = resolve_url("relate-home")
user = form.get_user()
# Okay, security check complete. Log the user in.
auth_login(request, user)
return HttpResponseRedirect(redirect_to)
else:
form = LoginForm(request)
next_uri = ""
if redirect_to:
next_uri = f"?{redirect_field_name}={redirect_to}"
context = {
"form": form,
redirect_field_name: redirect_to,
"next_uri": next_uri,
}
return TemplateResponse(request, "course/login.html", context)
class SignUpForm(StyledModelForm):
username = forms.CharField(required=True, max_length=30,
label=_("Username"),
validators=[ASCIIUsernameValidator()])
class Meta:
model = get_user_model()
fields = ("email",)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields["email"].required = True
self.helper.add_input(
Submit("submit", _("Send email")))
@logout_confirmation_required
def sign_up(request):
if not settings.RELATE_REGISTRATION_ENABLED:
raise SuspiciousOperation(
_("self-registration is not enabled"))
if request.method == "POST":
form = SignUpForm(request.POST)
if form.is_valid():
if get_user_model().objects.filter(
username=form.cleaned_data["username"]).count():
messages.add_message(request, messages.ERROR,
_("A user with that username already exists."))
else:
email = form.cleaned_data["email"]
user = get_user_model()(
email=email,
username=form.cleaned_data["username"])
user.set_unusable_password()
user.status = UserStatus.unconfirmed
user.sign_in_key = make_sign_in_key(user)
user.save()
from relate.utils import render_email_template
message = render_email_template("course/sign-in-email.txt", {
"user": user,
"sign_in_uri": request.build_absolute_uri(
reverse(
"relate-reset_password_stage2",
args=(user.id, user.sign_in_key,))
+ "?to_profile=1"),
"home_uri": request.build_absolute_uri(
reverse("relate-home"))
})
from django.core.mail import EmailMessage
msg = EmailMessage(
string_concat(f"[{_(get_site_name())}] ",
_("Verify your email")),
message,
getattr(settings, "NO_REPLY_EMAIL_FROM",
settings.ROBOT_EMAIL_FROM),
[email])
from relate.utils import get_outbound_mail_connection
msg.connection = (
get_outbound_mail_connection("no_reply")
if hasattr(settings, "NO_REPLY_EMAIL_FROM")
else get_outbound_mail_connection("robot"))
msg.send()
messages.add_message(request, messages.INFO,
_("Email sent. Please check your email and click "
"the link."))
return redirect("relate-home")
else:
if ("email" in form.errors
and "That email address is already in use."
in form.errors["email"]):
messages.add_message(request, messages.ERROR,
_("That email address is already in use. "
"Would you like to "
"<a href='%s'>reset your password</a> instead?")
% reverse(
"relate-reset_password"))
else:
form = SignUpForm()
return render(request, "generic-form.html", {
"form_description": _("Sign up"),
"form": form
})
class ResetPasswordFormByEmail(StyledForm):
email = forms.EmailField(required=True, label=_("Email"),
max_length=User._meta.get_field("email").max_length)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.helper.add_input(
Submit("submit", _("Send email")))
class ResetPasswordFormByInstid(StyledForm):
instid = forms.CharField(max_length=100,
required=True,
label=_("Institutional ID"))
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.helper.add_input(
Submit("submit", _("Send email")))
def masked_email(email: str):
# return a masked email address
at = email.find("@")
return email[:2] + "*" * (len(email[3:at])-1) + email[at-1:]
@logout_confirmation_required
def reset_password(request: RelateHttpRequest, field: str = "email"):
if not settings.RELATE_REGISTRATION_ENABLED:
raise SuspiciousOperation(
_("self-registration is not enabled"))
# return form class by string of class name
ResetPasswordForm = globals()["ResetPasswordFormBy" + field.title()] # noqa
if request.method == "POST":
form = ResetPasswordForm(request.POST)
user = None
if form.is_valid():
exist_users_with_same_email = False
if field == "instid":
inst_id = form.cleaned_data["instid"]
try:
user = get_user_model().objects.get(
institutional_id__iexact=inst_id)
except ObjectDoesNotExist:
pass
if field == "email":
email = form.cleaned_data["email"]
try:
user = get_user_model().objects.get(email__iexact=email)
except ObjectDoesNotExist:
pass
except MultipleObjectsReturned:
exist_users_with_same_email = True
if exist_users_with_same_email:
# This is for backward compatibility.
messages.add_message(request, messages.ERROR,
_("Failed to send an email: multiple users were "
"unexpectedly using that same "
"email address. Please "
"contact site staff."))
else:
if user is None:
FIELD_DICT = { # noqa
"email": _("email address"),
"instid": _("institutional ID")
}
messages.add_message(request, messages.ERROR,
_("That %(field)s doesn't have an "
"associated user account. Are you "
"sure you've registered?")
% {"field": FIELD_DICT[field]})
else:
if not user.email:
messages.add_message(request, messages.ERROR,
_("The account with that institution ID "
"doesn't have an associated email."))
else:
email = user.email
user.sign_in_key = make_sign_in_key(user)
user.save()
from relate.utils import render_email_template
message = render_email_template(
"course/sign-in-email.txt", {
"user": user,
"sign_in_uri": request.build_absolute_uri(
reverse(
"relate-reset_password_stage2",
args=(user.id, user.sign_in_key,))),
"home_uri": request.build_absolute_uri(
reverse("relate-home"))
})
from django.core.mail import EmailMessage
msg = EmailMessage(
string_concat(f"[{_(get_site_name())}] ",
_("Password reset")),
message,
getattr(settings, "NO_REPLY_EMAIL_FROM",
settings.ROBOT_EMAIL_FROM),
[email])
from relate.utils import get_outbound_mail_connection
msg.connection = (
get_outbound_mail_connection("no_reply")
if hasattr(settings, "NO_REPLY_EMAIL_FROM")
else get_outbound_mail_connection("robot"))
msg.send()
if field == "instid":
messages.add_message(request, messages.INFO,
_("The email address associated with that "
"account is %s.")
% masked_email(email))
messages.add_message(request, messages.INFO,
_("Email sent. Please check your email and "
"click the link."))
return redirect("relate-home")
else:
form = ResetPasswordForm()
return render(request, "reset-passwd-form.html", {
"field": field,
"form_description":
_("Password reset on %(site_name)s")
% {"site_name": _(get_site_name())},
"form": form
})
class ResetPasswordStage2Form(StyledForm):
password = forms.CharField(widget=forms.PasswordInput(),
label=_("Password"))
password_repeat = forms.CharField(widget=forms.PasswordInput(),
label=_("Password confirmation"))
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.helper.add_input(
Submit("submit_user", _("Update")))
def clean(self):
cleaned_data = super().clean()
password = cleaned_data.get("password")
password_repeat = cleaned_data.get("password_repeat")
if password and password != password_repeat:
self.add_error("password_repeat",
_("The two password fields didn't match."))
@logout_confirmation_required
def reset_password_stage2(
request: RelateHttpRequest,
user_id: str,
sign_in_key: str):
if not settings.RELATE_REGISTRATION_ENABLED:
raise SuspiciousOperation(
_("self-registration is not enabled"))
def check_sign_in_key(user_id: int, token: str):
user = get_user_model().objects.get(id=user_id)
return user.sign_in_key == token
try:
if not check_sign_in_key(user_id=int(user_id), token=sign_in_key):
messages.add_message(request, messages.ERROR,
_("Invalid sign-in token. Perhaps you've used an old token "
"email?"))
raise PermissionDenied(_("invalid sign-in token"))
except get_user_model().DoesNotExist:
messages.add_message(request, messages.ERROR, _("Account does not exist."))
raise PermissionDenied(_("invalid sign-in token"))
if request.method == "POST":
form = ResetPasswordStage2Form(request.POST)
if form.is_valid():
from django.contrib.auth import authenticate, login
user = authenticate(user_id=int(user_id), token=sign_in_key)
if user is None:
messages.add_message(request, messages.ERROR,
_("Invalid sign-in token. Perhaps you've used an old token "
"email?"))
raise PermissionDenied(_("invalid sign-in token"))
if not user.is_active:
messages.add_message(request, messages.ERROR,
_("Account disabled."))
raise PermissionDenied(_("invalid sign-in token"))
user.set_password(form.cleaned_data["password"])
user.save()
login(request, user)
if (not (user.first_name and user.last_name)
or "to_profile" in request.GET):
messages.add_message(request, messages.INFO,
_("Successfully signed in. "
"Please complete your registration information below."))
return redirect(
reverse("relate-user_profile")+"?first_login=1")
else:
messages.add_message(request, messages.INFO,
_("Successfully signed in."))
return redirect("relate-home")
else:
form = ResetPasswordStage2Form()
return render(request, "generic-form.html", {
"form_description":
_("Password reset on %(site_name)s")
% {"site_name": _(get_site_name())},
"form": form
})
# }}}
# {{{ email sign-in flow
class SignInByEmailForm(StyledForm):
email = forms.EmailField(required=True, label=_("Email"),
# For now, until we upgrade to a custom user model.
max_length=User._meta.get_field("email").max_length)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.helper.add_input(
Submit("submit", _("Send sign-in email")))
@logout_confirmation_required
def sign_in_by_email(request):
if not settings.RELATE_SIGN_IN_BY_EMAIL_ENABLED:
messages.add_message(request, messages.ERROR,
_("Email-based sign-in is not being used"))
return redirect("relate-sign_in_choice")
if request.method == "POST":
form = SignInByEmailForm(request.POST)
if form.is_valid():
email = form.cleaned_data["email"]
user, created = get_user_model().objects.get_or_create(
email__iexact=email,
defaults={"username": email, "email": email})
if created:
user.set_unusable_password()
user.status = UserStatus.unconfirmed
user.sign_in_key = make_sign_in_key(user)
user.save()
from relate.utils import render_email_template
message = render_email_template("course/sign-in-email.txt", {
"user": user,
"sign_in_uri": request.build_absolute_uri(
reverse(
"relate-sign_in_stage2_with_token",
args=(user.id, user.sign_in_key,))),
"home_uri": request.build_absolute_uri(reverse("relate-home"))
})
from django.core.mail import EmailMessage
msg = EmailMessage(
_("Your %(relate_site_name)s sign-in link")
% {"relate_site_name": _(get_site_name())},
message,
getattr(settings, "NO_REPLY_EMAIL_FROM",
settings.ROBOT_EMAIL_FROM),
[user.email])
from relate.utils import get_outbound_mail_connection
msg.connection = (
get_outbound_mail_connection("no_reply")
if hasattr(settings, "NO_REPLY_EMAIL_FROM")
else get_outbound_mail_connection("robot"))
msg.send()
messages.add_message(request, messages.INFO,
_("Email sent. Please check your email and click the link."))
return redirect("relate-home")
else:
form = SignInByEmailForm()
return render(request, "course/login-by-email.html", {
"form_description": "",
"form": form
})
@logout_confirmation_required
def sign_in_stage2_with_token(request, user_id, sign_in_key):
if not settings.RELATE_SIGN_IN_BY_EMAIL_ENABLED:
messages.add_message(request, messages.ERROR,
_("Email-based sign-in is not being used"))
return redirect("relate-sign_in_choice")
from django.contrib.auth import authenticate, login
user = authenticate(user_id=int(user_id), token=sign_in_key)
if user is None:
if not get_user_model().objects.filter(pk=int(user_id)).count():
messages.add_message(request, messages.ERROR,
_("Account does not exist."))
else:
messages.add_message(request, messages.ERROR,
_("Invalid sign-in token. Perhaps you've used an old "
"token email?"))
raise PermissionDenied(_("invalid sign-in token"))
if not user.is_active:
messages.add_message(request, messages.ERROR,
_("Account disabled."))
raise PermissionDenied(_("invalid sign-in token"))
login(request, user)
if not (user.first_name and user.last_name):
messages.add_message(request, messages.INFO,
_("Successfully signed in. "
"Please complete your registration information below."))
return redirect(
reverse("relate-user_profile")+"?first_login=1")
else:
messages.add_message(request, messages.INFO,
_("Successfully signed in."))
return redirect("relate-home")
# }}}
# {{{ user profile
def is_inst_id_editable_before_validation() -> bool:
return getattr(
settings, "RELATE_EDITABLE_INST_ID_BEFORE_VERIFICATION", True)
class UserForm(StyledModelForm):
institutional_id_confirm = forms.CharField(
max_length=100,
label=_("Institutional ID Confirmation"),
required=False)
class Meta:
model = get_user_model()
fields = ("first_name", "last_name", "email", "institutional_id",
"editor_mode")
def __init__(self, *args, **kwargs):
self.is_inst_id_locked = kwargs.pop("is_inst_id_locked")
super().__init__(*args, **kwargs)
if self.instance.name_verified:
self.fields["first_name"].disabled = True
self.fields["last_name"].disabled = True
self.fields["email"].disabled = True
if self.is_inst_id_locked:
self.fields["institutional_id"].disabled = True
self.fields["institutional_id_confirm"].disabled = True
else:
self.fields["institutional_id_confirm"].initial = (
self.instance.institutional_id)
self.fields["institutional_id"].help_text = (
_("The unique ID your university or school provided, "
"which may be used by some courses to verify "
"eligibility to enroll. "
"<b>Once %(submitted_or_verified)s, it cannot be "
"changed</b>.")
% {"submitted_or_verified":
(is_inst_id_editable_before_validation()
and _("verified")) or _("submitted")})
# {{{ build layout
name_fields_layout = ["last_name", "first_name", "email"]
fields_layout = [Div(*name_fields_layout, css_class="well")]
if getattr(settings, "RELATE_SHOW_INST_ID_FORM", True):
inst_field_group_layout = ["institutional_id"]
if not self.is_inst_id_locked:
inst_field_group_layout.append("institutional_id_confirm")
fields_layout.append(Div(*inst_field_group_layout, css_class="well",
css_id="institutional_id_block"))
else:
# This is needed for django-crispy-form version < 1.7
self.fields["institutional_id"].widget = forms.HiddenInput()
if getattr(settings, "RELATE_SHOW_EDITOR_FORM", True):
fields_layout.append(Div("editor_mode", css_class="well"))
else:
# This is needed for django-crispy-form version < 1.7
self.fields["editor_mode"].widget = forms.HiddenInput()
self.helper.layout = Layout(*fields_layout)
self.helper.add_input(
Submit("submit_user", _("Update")))
self.helper.add_input(
Button("signout", _("Sign out"), css_class="btn btn-danger",
onclick=(
"window.location.href='{}'".format(reverse("relate-logout")))))
# }}}
def clean_institutional_id_confirm(self):
inst_id_confirmed = self.cleaned_data.get("institutional_id_confirm")
if not self.is_inst_id_locked:
inst_id = self.cleaned_data.get("institutional_id")
if inst_id and not inst_id_confirmed:
raise forms.ValidationError(_("This field is required."))
if any([inst_id, inst_id_confirmed]) and inst_id != inst_id_confirmed:
raise forms.ValidationError(_("Inputs do not match."))