-
Notifications
You must be signed in to change notification settings - Fork 938
/
views.py
1867 lines (1625 loc) · 64.7 KB
/
views.py
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
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import datetime
import hashlib
import json
import uuid
import humanize
import pytz
import sentry_sdk
from first import first
from pyramid.httpexceptions import (
HTTPBadRequest,
HTTPMovedPermanently,
HTTPNotFound,
HTTPSeeOther,
HTTPTooManyRequests,
HTTPUnauthorized,
)
from pyramid.interfaces import ISecurityPolicy
from pyramid.security import forget, remember
from pyramid.view import view_config, view_defaults
from sqlalchemy.exc import NoResultFound
from webauthn.helpers import bytes_to_base64url
from webob.multidict import MultiDict
from warehouse.accounts import REDIRECT_FIELD_NAME
from warehouse.accounts.forms import (
LoginForm,
ReAuthenticateForm,
RecoveryCodeAuthenticationForm,
RegistrationForm,
RequestPasswordResetForm,
ResetPasswordForm,
TOTPAuthenticationForm,
UsernameSearchForm,
WebAuthnAuthenticationForm,
)
from warehouse.accounts.interfaces import (
IPasswordBreachedService,
ITokenService,
IUserService,
TokenException,
TokenExpired,
TokenInvalid,
TokenMissing,
TooManyEmailsAdded,
TooManyFailedLogins,
TooManyPasswordResetRequests,
)
from warehouse.accounts.models import Email, User
from warehouse.admin.flags import AdminFlagValue
from warehouse.authnz import Permissions
from warehouse.cache.origin import origin_cache
from warehouse.captcha.interfaces import ICaptchaService
from warehouse.email import (
send_added_as_collaborator_email,
send_added_as_organization_member_email,
send_collaborator_added_email,
send_declined_as_invited_organization_member_email,
send_email_verification_email,
send_organization_member_added_email,
send_organization_member_invite_declined_email,
send_password_change_email,
send_password_reset_email,
send_recovery_code_reminder_email,
)
from warehouse.events.tags import EventTag
from warehouse.metrics.interfaces import IMetricsService
from warehouse.oidc.forms import (
DeletePublisherForm,
PendingActiveStatePublisherForm,
PendingGitHubPublisherForm,
PendingGitLabPublisherForm,
PendingGooglePublisherForm,
)
from warehouse.oidc.interfaces import TooManyOIDCRegistrations
from warehouse.oidc.models import (
PendingActiveStatePublisher,
PendingGitHubPublisher,
PendingGitLabPublisher,
PendingGooglePublisher,
PendingOIDCPublisher,
)
from warehouse.organizations.interfaces import IOrganizationService
from warehouse.organizations.models import OrganizationRole, OrganizationRoleType
from warehouse.packaging.models import (
JournalEntry,
Project,
ProjectFactory,
Release,
Role,
RoleInvitation,
)
from warehouse.rate_limiting.interfaces import IRateLimiter
from warehouse.utils.http import is_safe_url
USER_ID_INSECURE_COOKIE = "user_id__insecure"
REMEMBER_DEVICE_COOKIE = "remember_device"
@view_config(context=TooManyFailedLogins, has_translations=True)
def failed_logins(exc, request):
resp = HTTPTooManyRequests(
request._(
"There have been too many unsuccessful login attempts. "
"You have been locked out for {}. "
"Please try again later.".format(
humanize.naturaldelta(exc.resets_in.total_seconds())
)
),
retry_after=exc.resets_in.total_seconds(),
)
# TODO: This is kind of gross, but we need it for as long as the legacy
# upload API exists and is supported. Once we get rid of that we can
# get rid of this as well.
resp.status = "{} {}".format(resp.status_code, "Too Many Failed Login Attempts")
return resp
@view_config(context=TooManyEmailsAdded, has_translations=True)
def unverified_emails(exc, request):
return HTTPTooManyRequests(
request._(
"Too many emails have been added to this account without verifying "
"them. Check your inbox and follow the verification links. (IP: ${ip})",
mapping={"ip": request.remote_addr},
),
retry_after=exc.resets_in.total_seconds(),
)
@view_config(context=TooManyPasswordResetRequests, has_translations=True)
def incomplete_password_resets(exc, request):
return HTTPTooManyRequests(
request._(
"Too many password resets have been requested for this account without "
"completing them. Check your inbox and follow the verification links. "
"(IP: ${ip})",
mapping={"ip": request.remote_addr},
),
retry_after=exc.resets_in.total_seconds(),
)
@view_config(
route_name="accounts.profile",
context=User,
renderer="accounts/profile.html",
decorator=[
origin_cache(1 * 24 * 60 * 60, stale_if_error=1 * 24 * 60 * 60) # 1 day each.
],
has_translations=True,
)
def profile(user, request):
if user.username != request.matchdict.get("username", user.username):
return HTTPMovedPermanently(request.current_route_path(username=user.username))
projects = (
request.db.query(Project)
.filter(Project.users.contains(user))
.join(Project.releases)
.order_by(Release.created.desc())
.all()
)
return {"user": user, "projects": projects}
@view_config(
route_name="accounts.search",
renderer="api/account_search.html",
uses_session=True,
)
def accounts_search(request) -> dict[str, list[User]]:
"""
Search for usernames based on prefix.
Used with autocomplete.
User must be logged in.
"""
if request.user is None:
raise HTTPUnauthorized()
form = UsernameSearchForm(request.params)
if not form.validate():
raise HTTPBadRequest()
search_limiter = request.find_service(IRateLimiter, name="accounts.search")
if not search_limiter.test(request.ip_address):
# TODO: This should probably `raise HTTPTooManyRequests` instead,
# but we need to make sure that the client library can handle it.
# See: https://github.com/afcapel/stimulus-autocomplete/issues/136
return {"users": []}
user_service = request.find_service(IUserService, context=None)
# type guard, see:
# https://github.com/python/typeshed/pull/10557#issuecomment-1732358909
assert form.username.data is not None
users = user_service.get_users_by_prefix(form.username.data.strip())
search_limiter.hit(request.ip_address)
if not users:
raise HTTPNotFound()
return {"users": users}
@view_config(
route_name="accounts.login",
renderer="accounts/login.html",
uses_session=True,
require_csrf=True,
require_methods=False,
has_translations=True,
)
def login(request, redirect_field_name=REDIRECT_FIELD_NAME, _form_class=LoginForm):
# TODO: Logging in should reset request.user
if request.user is not None:
return HTTPSeeOther(request.route_path("manage.projects"))
user_service = request.find_service(IUserService, context=None)
breach_service = request.find_service(IPasswordBreachedService, context=None)
redirect_to = request.POST.get(
redirect_field_name, request.GET.get(redirect_field_name)
)
form = _form_class(
request.POST,
request=request,
user_service=user_service,
breach_service=breach_service,
check_password_metrics_tags=["method:auth", "auth_method:login_form"],
)
if request.method == "POST":
if form.validate():
# Get the user id for the given username.
username = form.username.data
userid = user_service.find_userid(username)
# If the user has enabled two-factor authentication and they do not have
# a valid saved device.
two_factor_required = user_service.has_two_factor(userid) and (
not _check_remember_device_token(request, userid)
)
if two_factor_required:
two_factor_data = {"userid": userid}
if redirect_to:
two_factor_data["redirect_to"] = redirect_to
token_service = request.find_service(ITokenService, name="two_factor")
token = token_service.dumps(two_factor_data)
# Stuff our token in the query and redirect to two-factor page.
resp = HTTPSeeOther(
request.route_path("accounts.two-factor", _query=token)
)
return resp
else:
# If the user-originating redirection url is not safe, then
# redirect to the index instead.
if not redirect_to or not is_safe_url(
url=redirect_to, host=request.host
):
redirect_to = request.route_path("manage.projects")
# Actually perform the login routine for our user.
headers = _login_user(request, userid)
# Now that we're logged in we'll want to redirect the user to
# either where they were trying to go originally, or to the default
# view.
resp = HTTPSeeOther(redirect_to, headers=dict(headers))
# We'll use this cookie so that client side javascript can
# Determine the actual user ID (not username, user ID). This is
# *not* a security sensitive context and it *MUST* not be used
# where security matters.
#
# We'll also hash this value just to avoid leaking the actual User
# IDs here, even though it really shouldn't matter.
resp.set_cookie(
USER_ID_INSECURE_COOKIE,
hashlib.blake2b(
str(userid).encode("ascii"), person=b"warehouse.userid"
)
.hexdigest()
.lower(),
)
return resp
return {
"form": form,
"redirect": {"field": REDIRECT_FIELD_NAME, "data": redirect_to},
}
@view_config(
route_name="accounts.two-factor",
renderer="accounts/two-factor.html",
uses_session=True,
require_csrf=True,
require_methods=False,
has_translations=True,
)
def two_factor_and_totp_validate(request, _form_class=TOTPAuthenticationForm):
# TODO: Using `request.user` here fails `test_totp_auth()` because
# of how the test is constructed. We should fix that.
if request.identity is not None:
return HTTPSeeOther(request.route_path("manage.projects"))
try:
two_factor_data = _get_two_factor_data(request)
except TokenException:
request.session.flash(
request._("Invalid or expired two factor login."), queue="error"
)
return HTTPSeeOther(request.route_path("accounts.login"))
userid = two_factor_data.get("userid")
redirect_to = two_factor_data.get("redirect_to")
user_service = request.find_service(IUserService, context=None)
two_factor_state = {}
if user_service.has_totp(userid):
two_factor_state["totp_form"] = _form_class(
request.POST,
request=request,
user_id=userid,
user_service=user_service,
check_password_metrics_tags=["method:auth", "auth_method:login_form"],
)
if user_service.has_webauthn(userid):
two_factor_state["has_webauthn"] = True
if user_service.has_recovery_codes(userid):
two_factor_state["has_recovery_codes"] = True
two_factor_state["remember_device_days"] = request.registry.settings[
"remember_device.days"
]
if request.method == "POST":
form = two_factor_state["totp_form"]
if form.validate():
two_factor_method = "totp"
_login_user(request, userid, two_factor_method, two_factor_label="totp")
user_service.update_user(userid, last_totp_value=form.totp_value.data)
resp = HTTPSeeOther(redirect_to)
resp.set_cookie(
USER_ID_INSECURE_COOKIE,
hashlib.blake2b(str(userid).encode("ascii"), person=b"warehouse.userid")
.hexdigest()
.lower(),
)
if not two_factor_state.get("has_recovery_codes", False):
send_recovery_code_reminder_email(request, request.user)
if form.remember_device.data:
_remember_device(request, resp, userid, two_factor_method)
return resp
else:
form.totp_value.data = ""
return two_factor_state
@view_config(
uses_session=True,
request_method="GET",
route_name="accounts.webauthn-authenticate.options",
renderer="json",
has_translations=True,
)
def webauthn_authentication_options(request):
if request.user is not None:
return {"fail": {"errors": [request._("Already authenticated")]}}
try:
two_factor_data = _get_two_factor_data(request)
except TokenException:
request.session.flash(
request._("Invalid or expired two factor login."), queue="error"
)
return {"fail": {"errors": [request._("Invalid or expired two factor login.")]}}
userid = two_factor_data.get("userid")
user_service = request.find_service(IUserService, context=None)
return user_service.get_webauthn_assertion_options(
userid, challenge=request.session.get_webauthn_challenge(), rp_id=request.domain
)
@view_config(
require_csrf=True,
require_methods=False,
uses_session=True,
request_method="POST",
request_param=WebAuthnAuthenticationForm.__params__,
route_name="accounts.webauthn-authenticate.validate",
renderer="json",
has_translations=True,
)
def webauthn_authentication_validate(request):
# TODO: Using `request.user` here fails `test_webauthn_validate()` because
# of how the test is constructed. We should fix that.
if request.identity is not None:
return {"fail": {"errors": ["Already authenticated"]}}
try:
two_factor_data = _get_two_factor_data(request)
except TokenException:
request.session.flash(
request._("Invalid or expired two factor login."), queue="error"
)
return {"fail": {"errors": [request._("Invalid or expired two factor login.")]}}
redirect_to = two_factor_data.get("redirect_to")
userid = two_factor_data.get("userid")
user_service = request.find_service(IUserService, context=None)
form = WebAuthnAuthenticationForm(
request.POST,
request=request,
user_id=userid,
user_service=user_service,
challenge=request.session.get_webauthn_challenge(),
origin=request.host_url,
rp_id=request.domain,
)
request.session.clear_webauthn_challenge()
if form.validate():
webauthn = user_service.get_webauthn_by_credential_id(
userid, bytes_to_base64url(form.validated_credential.credential_id)
)
webauthn.sign_count = form.validated_credential.new_sign_count
two_factor_method = "webauthn"
_login_user(request, userid, two_factor_method, two_factor_label=webauthn.label)
request.response.set_cookie(
USER_ID_INSECURE_COOKIE,
hashlib.blake2b(str(userid).encode("ascii"), person=b"warehouse.userid")
.hexdigest()
.lower(),
)
if not request.user.has_recovery_codes:
send_recovery_code_reminder_email(request, request.user)
if form.remember_device.data:
_remember_device(request, request.response, userid, two_factor_method)
return {
"success": request._("Successful WebAuthn assertion"),
"redirect_to": redirect_to,
}
errors = [str(error) for error in form.credential.errors]
return {"fail": {"errors": errors}}
def _check_remember_device_token(request, user_id) -> bool:
"""
Returns true if the given remember device cookie is valid for the given user.
"""
remember_device_token = request.cookies.get(REMEMBER_DEVICE_COOKIE)
if not remember_device_token:
return False
token_service = request.find_service(ITokenService, name="remember_device")
try:
data = token_service.loads(remember_device_token)
user_id_token = data.get("user_id")
return user_id_token == str(user_id)
except TokenException:
return False
def _remember_device(request, response, userid, two_factor_method) -> None:
"""
Generates and sets a cookie for remembering this device.
"""
remember_device_data = {"user_id": str(userid)}
token_service = request.find_service(ITokenService, name="remember_device")
token = token_service.dumps(remember_device_data)
response.set_cookie(
REMEMBER_DEVICE_COOKIE,
token,
max_age=request.registry.settings["remember_device.seconds"],
httponly=True,
secure=request.scheme == "https",
samesite=b"strict",
path=request.route_path("accounts.login"),
)
request.user.record_event(
tag=EventTag.Account.TwoFactorDeviceRemembered,
request=request,
additional={
"two_factor_method": two_factor_method,
},
)
@view_config(
route_name="accounts.recovery-code",
renderer="accounts/recovery-code.html",
uses_session=True,
require_csrf=True,
require_methods=False,
has_translations=True,
)
def recovery_code(request, _form_class=RecoveryCodeAuthenticationForm):
if request.user is not None:
return HTTPSeeOther(request.route_path("manage.projects"))
try:
two_factor_data = _get_two_factor_data(request)
except TokenException:
request.session.flash(
request._("Invalid or expired two factor login."), queue="error"
)
return HTTPSeeOther(request.route_path("accounts.login"))
userid = two_factor_data.get("userid")
user_service = request.find_service(IUserService, context=None)
form = _form_class(
request.POST, request=request, user_id=userid, user_service=user_service
)
if request.method == "POST":
if form.validate():
_login_user(request, userid, two_factor_method="recovery-code")
resp = HTTPSeeOther(request.route_path("manage.account"))
resp.set_cookie(
USER_ID_INSECURE_COOKIE,
hashlib.blake2b(str(userid).encode("ascii"), person=b"warehouse.userid")
.hexdigest()
.lower(),
)
user = user_service.get_user(userid)
user.record_event(
tag=EventTag.Account.RecoveryCodesUsed,
request=request,
)
request.session.flash(
request._(
"Recovery code accepted. The supplied code cannot be used again."
),
queue="success",
)
return resp
else:
form.recovery_code_value.data = ""
return {"form": form}
@view_config(
route_name="accounts.logout",
renderer="accounts/logout.html",
uses_session=True,
require_csrf=True,
require_methods=False,
has_translations=True,
)
def logout(request, redirect_field_name=REDIRECT_FIELD_NAME):
# TODO: Logging out should reset request.user
redirect_to = request.POST.get(
redirect_field_name, request.GET.get(redirect_field_name)
)
# If the user-originating redirection url is not safe, then redirect to
# the index instead.
if not redirect_to or not is_safe_url(url=redirect_to, host=request.host):
redirect_to = "/"
# If we're already logged out, then we'll go ahead and issue our redirect right
# away instead of trying to log a non-existent user out.
if request.user is None:
return HTTPSeeOther(redirect_to)
if request.method == "POST":
# A POST to the logout view tells us to logout. There's no form to
# validate here because there's no data. We should be protected against
# CSRF attacks still because of the CSRF framework, so users will still
# need a post body that contains the CSRF token.
headers = forget(request)
# When crossing an authentication boundary we want to create a new
# session identifier. We don't want to keep any information in the
# session when going from authenticated to unauthenticated because
# user's generally expect that logging out is a destructive action
# that erases all of their private data. However, if we don't clear the
# session then another user can use the computer after them, log in to
# their account, and then gain access to anything sensitive stored in
# the session for the original user.
request.session.invalidate()
# We've logged the user out, so we want to ensure that we invalid the cache
# for our security policy, if we're using one that can be reset during login
security_policy = request.registry.queryUtility(ISecurityPolicy)
if hasattr(security_policy, "reset"):
security_policy.reset(request)
# Now that we're logged out we'll want to redirect the user to either
# where they were originally, or to the default view.
resp = HTTPSeeOther(redirect_to, headers=dict(headers))
# Ensure that we delete our user_id__insecure cookie, since the user is
# no longer logged in.
resp.delete_cookie(USER_ID_INSECURE_COOKIE)
return resp
return {"redirect": {"field": REDIRECT_FIELD_NAME, "data": redirect_to}}
@view_config(
route_name="accounts.register",
renderer="accounts/register.html",
uses_session=True,
require_csrf=True,
require_methods=False,
has_translations=True,
)
def register(request, _form_class=RegistrationForm):
if request.user is not None:
return HTTPSeeOther(request.route_path("manage.projects"))
# Check if the honeypot field has been filled
if request.method == "POST" and request.POST.get("confirm_form"):
return HTTPSeeOther(request.route_path("index"))
if request.flags.enabled(AdminFlagValue.DISALLOW_NEW_USER_REGISTRATION):
request.session.flash(
request._(
"New user registration temporarily disabled. "
"See https://pypi.org/help#admin-intervention for details."
),
queue="error",
)
return HTTPSeeOther(request.route_path("index"))
user_service = request.find_service(IUserService, context=None)
breach_service = request.find_service(IPasswordBreachedService, context=None)
captcha_service = request.find_service(ICaptchaService, name="captcha")
request.find_service(name="csp").merge(captcha_service.csp_policy)
# the form contains an auto-generated field from recaptcha with
# hyphens in it. make it play nice with wtforms.
post_body = MultiDict(
{key.replace("-", "_"): value for key, value in request.POST.items()}
)
form = _form_class(
request=request,
formdata=post_body,
user_service=user_service,
captcha_service=captcha_service,
breach_service=breach_service,
)
if request.method == "POST" and form.validate():
email_limiter = request.find_service(IRateLimiter, name="email.verify")
user = user_service.create_user(
form.username.data, form.full_name.data, form.new_password.data
)
email = user_service.add_email(user.id, form.email.data, primary=True)
user.record_event(
tag=EventTag.Account.AccountCreate,
request=request,
additional={"email": form.email.data},
)
send_email_verification_email(request, (user, email))
email_limiter.hit(user.id)
return HTTPSeeOther(
request.route_path("index"), headers=dict(_login_user(request, user.id))
)
return {"form": form}
@view_config(
route_name="accounts.request-password-reset",
renderer="accounts/request-password-reset.html",
uses_session=True,
require_csrf=True,
require_methods=False,
has_translations=True,
)
def request_password_reset(request, _form_class=RequestPasswordResetForm):
if request.user is not None:
return HTTPSeeOther(request.route_path("index"))
user_service = request.find_service(IUserService, context=None)
form = _form_class(request.POST, user_service=user_service)
if request.method == "POST" and form.validate():
user = user_service.get_user_by_username(form.username_or_email.data)
if user is None:
user = user_service.get_user_by_email(form.username_or_email.data)
if user is not None:
email = first(
user.emails, key=lambda e: e.email == form.username_or_email.data
)
else:
token_service = request.find_service(ITokenService, name="password")
n_hours = token_service.max_age // 60 // 60
# We could not find the user by username nor email.
# Return a response as if we did, to avoid leaking registered emails.
return {"n_hours": n_hours}
if not user_service.ratelimiters["password.reset"].test(user.id):
raise TooManyPasswordResetRequests(
resets_in=user_service.ratelimiters["password.reset"].resets_in(user.id)
)
if user.can_reset_password:
send_password_reset_email(request, (user, email))
user.record_event(
tag=EventTag.Account.PasswordResetRequest,
request=request,
)
user_service.ratelimiters["password.reset"].hit(user.id)
token_service = request.find_service(ITokenService, name="password")
n_hours = token_service.max_age // 60 // 60
return {"n_hours": n_hours}
else:
user.record_event(
tag=EventTag.Account.PasswordResetAttempt,
request=request,
)
request.session.flash(
request._(
(
"Automated password reset prohibited for your user. "
"Contact a PyPI administrator for assistance"
),
),
queue="error",
)
return HTTPSeeOther(request.route_path("accounts.request-password-reset"))
return {"form": form}
@view_config(
route_name="accounts.reset-password",
renderer="accounts/reset-password.html",
uses_session=True,
require_csrf=True,
require_methods=False,
has_translations=True,
)
def reset_password(request, _form_class=ResetPasswordForm):
if request.user is not None:
return HTTPSeeOther(request.route_path("index"))
user_service = request.find_service(IUserService, context=None)
breach_service = request.find_service(IPasswordBreachedService, context=None)
token_service = request.find_service(ITokenService, name="password")
def _error(message):
request.session.flash(message, queue="error")
return HTTPSeeOther(request.route_path("accounts.request-password-reset"))
try:
token = request.params.get("token")
data = token_service.loads(token)
except TokenExpired:
return _error(request._("Expired token: request a new password reset link"))
except TokenInvalid:
return _error(request._("Invalid token: request a new password reset link"))
except TokenMissing:
return _error(request._("Invalid token: no token supplied"))
# Check whether this token is being used correctly
if data.get("action") != "password-reset":
return _error(request._("Invalid token: not a password reset token"))
# Check whether a user with the given user ID exists
user = user_service.get_user(uuid.UUID(data.get("user.id")))
if user is None:
return _error(request._("Invalid token: user not found"))
# Check whether the user has logged in since the token was created
last_login = datetime.datetime.fromisoformat(data.get("user.last_login"))
# Before updating itsdangerous to 2.x the last_login was naive,
# now it's localized to UTC
if not last_login.tzinfo:
last_login = pytz.UTC.localize(last_login)
if user.last_login and user.last_login > last_login:
sentry_sdk.set_context(
"user",
{
"username": user.username,
"last_login": user.last_login,
"token_last_login": last_login,
},
)
sentry_sdk.capture_message(
f"Password reset token used after user logged in for {user.username}",
level="warning",
)
return _error(
request._(
"Invalid token: user has logged in since this token was requested"
)
)
# Check whether the password has been changed since the token was created
password_date = datetime.datetime.fromisoformat(data.get("user.password_date"))
# Before updating itsdangerous to 2.x the password_date was naive,
# now it's localized to UTC
if not password_date.tzinfo:
password_date = pytz.UTC.localize(password_date)
current_password_date = (
user.password_date
if user.password_date is not None
else datetime.datetime.min.replace(tzinfo=pytz.UTC)
)
if current_password_date > password_date:
return _error(
request._(
"Invalid token: password has already been changed since this "
"token was requested"
)
)
form = _form_class(
request.POST,
username=user.username,
full_name=user.name,
email=user.email,
user_service=user_service,
breach_service=breach_service,
)
if request.method == "POST" and form.validate():
password_reset_limiter = request.find_service(
IRateLimiter, name="password.reset"
)
# Update password.
user_service.update_user(user.id, password=form.new_password.data)
user.record_event(
tag=EventTag.Account.PasswordReset,
request=request,
)
password_reset_limiter.clear(user.id)
# Send password change email
send_password_change_email(request, user)
# Flash a success message
request.session.flash(
request._("You have reset your password"), queue="success"
)
# Redirect to account login.
return HTTPSeeOther(request.route_path("accounts.login"))
return {"form": form}
@view_config(
route_name="accounts.verify-email",
uses_session=True,
permission=Permissions.AccountVerifyEmail,
has_translations=True,
)
def verify_email(request):
token_service = request.find_service(ITokenService, name="email")
email_limiter = request.find_service(IRateLimiter, name="email.add")
verify_limiter = request.find_service(IRateLimiter, name="email.verify")
def _error(message):
request.session.flash(message, queue="error")
return HTTPSeeOther(request.route_path("manage.account"))
try:
token = request.params.get("token")
data = token_service.loads(token)
except TokenExpired:
return _error(request._("Expired token: request a new email verification link"))
except TokenInvalid:
return _error(request._("Invalid token: request a new email verification link"))
except TokenMissing:
return _error(request._("Invalid token: no token supplied"))
# Check whether this token is being used correctly
if data.get("action") != "email-verify":
return _error(request._("Invalid token: not an email verification token"))
try:
email = (
request.db.query(Email)
.filter(Email.id == int(data["email.id"]), Email.user == request.user)
.one()
)
except NoResultFound:
return _error(request._("Email not found"))
if email.verified:
return _error(request._("Email already verified"))
email.verified = True
email.unverify_reason = None
email.transient_bounces = 0
email.user.record_event(
tag=EventTag.Account.EmailVerified,
request=request,
additional={"email": email.email, "primary": email.primary},
)
# Reset the email-adding rate limiter for this IP address
email_limiter.clear(request.remote_addr)
# Reset the email verification rate limiter for this User
verify_limiter.clear(request.user.id)
if not email.primary:
confirm_message = request._(
"You can now set this email as your primary address"
)
else:
confirm_message = request._("This is your primary address")
request.user.is_active = True
request.session.flash(
request._(
"Email address ${email_address} verified. ${confirm_message}.",
mapping={"email_address": email.email, "confirm_message": confirm_message},
),
queue="success",
)
# If they've already set up a 2FA app, send them to their account page.
if request.user.has_two_factor:
return HTTPSeeOther(request.route_path("manage.account"))
# Otherwise, send them to the two-factor setup page.
return HTTPSeeOther(request.route_path("manage.account.two-factor"))
def _get_two_factor_data(request, _redirect_to="/"):
token_service = request.find_service(ITokenService, name="two_factor")
two_factor_data, timestamp = token_service.loads(
request.query_string, return_timestamp=True
)
if two_factor_data.get("userid") is None:
raise TokenInvalid
user_service = request.find_service(IUserService, context=None)
user = user_service.get_user(two_factor_data.get("userid"))
if timestamp < user.last_login:
raise TokenInvalid
# If the user-originating redirection url is not safe, then
# redirect to the index instead.
redirect_to = two_factor_data.get("redirect_to")
if redirect_to is None or not is_safe_url(url=redirect_to, host=request.host):
two_factor_data["redirect_to"] = _redirect_to
return two_factor_data
@view_config(
route_name="accounts.verify-organization-role",
renderer="accounts/organization-invite-confirmation.html",
require_methods=False,
uses_session=True,