-
Notifications
You must be signed in to change notification settings - Fork 167
Expand file tree
/
Copy pathcore.py
More file actions
2402 lines (2109 loc) · 92.1 KB
/
Copy pathcore.py
File metadata and controls
2402 lines (2109 loc) · 92.1 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
"""
flask_security.core
~~~~~~~~~~~~~~~~~~~
Flask-Security core module
:copyright: (c) 2012 by Matt Wright.
:copyright: (c) 2017 by CERN.
:copyright: (c) 2017 by ETH Zurich, Swiss Data Science Center.
:copyright: (c) 2019-2026 by J. Christopher Wagner (jwag).
:license: MIT, see LICENSE for more details.
"""
from __future__ import annotations
from datetime import datetime, timedelta
from dataclasses import dataclass
import importlib
import time
import typing as t
import warnings
from flask import current_app, g, session
from flask_login import AnonymousUserMixin, LoginManager
from flask_login import UserMixin as BaseUserMixin
from flask_login import current_user
from flask_principal import Identity, Principal, RoleNeed, UserNeed, identity_loaded
from itsdangerous import URLSafeTimedSerializer, URLSafeSerializer
from passlib.context import CryptContext
from werkzeug.datastructures import ImmutableList
from werkzeug.local import LocalProxy
from .babel import FsDomain
from .change_email import ChangeEmailForm
from .change_username import ChangeUsernameForm
from .decorators import (
default_reauthn_handler,
default_unauthn_handler,
default_unauthz_handler,
)
from .forms import (
ChangePasswordForm,
ConfirmRegisterForm,
ForgotPasswordForm,
Form,
LoginForm,
LogoutForm,
PasswordlessLoginForm,
RegisterForm,
RegisterFormMixin,
RegisterFormV2,
ResetPasswordForm,
SendConfirmationForm,
TwoFactorVerifyCodeForm,
TwoFactorSetupForm,
TwoFactorRescueForm,
UsernameRecoveryForm,
VerifyForm,
build_username_field,
build_register_form,
build_login_form,
)
from .json import setup_json
from .mail_util import MailUtil
from .password_util import PasswordUtil
from .phone_util import PhoneUtil
from .oauth_glue import OAuthGlue
from .proxies import _security
from .recovery_codes import (
MfRecoveryForm,
MfRecoveryCodesForm,
MfRecoveryCodesUtil,
)
from .signals import user_failed_authn
from .tf_plugin import TfPlugin, TwoFactorSelectForm
from .tokens import RefreshTokenForm
from .twofactor import tf_send_security_token
from .unified_signin import (
UnifiedSigninForm,
UnifiedSigninSetupForm,
UnifiedSigninSetupValidateForm,
UnifiedVerifyForm,
us_send_security_token,
)
from .webauthn import (
WebAuthnDeleteForm,
WebAuthnRegisterForm,
WebAuthnRegisterResponseForm,
WebAuthnSigninForm,
WebAuthnSigninResponseForm,
WebAuthnVerifyForm,
)
from .webauthn_util import WebauthnUtil
from .username_util import UsernameUtil
from .totp import Totp
from .utils import _
from .utils import config_value as cv
from .utils import (
FsPermNeed,
add_cache_control,
csrf_cookie_handler,
default_render_template,
default_want_json,
get_identity_attribute,
get_identity_attributes,
get_message,
get_request_attr,
is_user_authenticated,
naive_utcnow,
parse_auth_token,
set_request_attr,
uia_email_mapper,
uia_username_mapper,
url_for_security,
verify_and_update_password,
)
from .views import create_blueprint, default_render_json
if t.TYPE_CHECKING: # pragma: no cover
import flask
from flask import Request
from flask.typing import ResponseValue
import flask_login.mixins
from authlib.integrations.flask_client import OAuth
from .datastore import UserDatastore
# List of authentication mechanisms supported.
AUTHN_MECHANISMS = ("basic", "session", "token")
#: Default Flask-Security configuration
_default_config: dict[str, t.Any] = {
"ANONYMOUS_USER_DISABLED": False,
"BLUEPRINT_NAME": "security",
"CLI_ROLES_NAME": "roles",
"CLI_USERS_NAME": "users",
"URL_PREFIX": None,
"STATIC_FOLDER": "static",
"STATIC_FOLDER_URL": "/fs-static",
"SUBDOMAIN": None,
"FLASH_MESSAGES": True,
"RETURN_GENERIC_RESPONSES": False,
"USE_REGISTER_V2": True,
"I18N_DOMAIN": "flask_security",
"I18N_DIRNAME": "builtin",
"EMAIL_VALIDATOR_ARGS": None,
"PASSWORD_HASH": "argon2",
"PASSWORD_SALT": None,
"PASSWORD_SINGLE_HASH": {
"django_argon2",
"django_bcrypt_sha256",
"django_pbkdf2_sha256",
"django_pbkdf2_sha1",
"django_bcrypt",
"django_salted_md5",
"django_salted_sha1",
"django_des_crypt",
"plaintext",
},
"PASSWORD_SCHEMES": [
"bcrypt",
"argon2",
"des_crypt",
"pbkdf2_sha256",
"pbkdf2_sha512",
"sha256_crypt",
"sha512_crypt",
# And always last one...
"plaintext",
],
"DEPRECATED_PASSWORD_SCHEMES": ["auto"],
"PASSWORD_HASH_OPTIONS": {}, # Deprecated at passlib 1.7
"PASSWORD_HASH_PASSLIB_OPTIONS": {}, # passlib >= 1.7.1 method to pass options
# (as part of CryptoContext.using)
"PASSWORD_LENGTH_MIN": 8,
"PASSWORD_COMPLEXITY_CHECKER": None,
"PASSWORD_CHECK_BREACHED": False,
"PASSWORD_BREACHED_COUNT": 1,
"PASSWORD_NORMALIZE_FORM": "NFKD",
"PASSWORD_REQUIRED": True,
"PASSWORD_CONFIRM_REQUIRED": True, # for RegisterFormV2
"HASHING_SCHEMES": ["sha256_crypt", "hex_md5"],
"DEPRECATED_HASHING_SCHEMES": ["auto"],
"LOGIN_URL": "/login",
"LOGOUT_URL": "/logout",
"REGISTER_URL": "/register",
"RESET_URL": "/reset",
"CHANGE_URL": "/change",
"CONFIRM_URL": "/confirm",
"VERIFY_URL": "/verify",
"TWO_FACTOR_SETUP_URL": "/tf-setup",
"TWO_FACTOR_TOKEN_VALIDATION_URL": "/tf-validate",
"TWO_FACTOR_RESCUE_URL": "/tf-rescue",
"TWO_FACTOR_SELECT_URL": "/tf-select",
"TWO_FACTOR_POST_SETUP_VIEW": ".two_factor_setup", # endpoint or URL
"TWO_FACTOR_ERROR_VIEW": ".login",
"LOGOUT_METHODS": ["POST"],
"LOGOUT_CSRF": False,
"LOGOUT_USER_TEMPLATE": "security/logout_user.html",
"POST_LOGIN_VIEW": "/",
"POST_LOGOUT_VIEW": "/",
"LOGIN_ERROR_VIEW": None, # spa
"POST_OAUTH_LOGIN_VIEW": None, # spa
"POST_OAUTH_VERIFY_VIEW": None, # spa
"CONFIRM_ERROR_VIEW": None, # spa
"POST_CONFIRM_VIEW": None, # spa
"RESET_VIEW": None, # spa
"RESET_ERROR_VIEW": None, # spa
"VERIFY_ERROR_VIEW": None, # spa
"POST_RESET_VIEW": None,
"POST_CHANGE_VIEW": None,
"POST_VERIFY_VIEW": None,
"POST_REGISTER_VIEW": None,
"UNAUTHORIZED_VIEW": None,
"REQUIRES_CONFIRMATION_ERROR_VIEW": None,
"REDIRECT_HOST": None,
"REDIRECT_BEHAVIOR": None,
"REDIRECT_ALLOW_SUBDOMAINS": False,
"REDIRECT_BASE_DOMAIN": None,
"REDIRECT_ALLOWED_SUBDOMAINS": [],
"FORGOT_PASSWORD_TEMPLATE": "security/forgot_password.html",
"LOGIN_USER_TEMPLATE": "security/login_user.html",
"REGISTER_USER_TEMPLATE": "security/register_user.html",
"RESET_PASSWORD_TEMPLATE": "security/reset_password.html",
"CHANGE_PASSWORD_TEMPLATE": "security/change_password.html",
"SEND_CONFIRMATION_TEMPLATE": "security/send_confirmation.html",
"SEND_LOGIN_TEMPLATE": "security/send_login.html",
"VERIFY_TEMPLATE": "security/verify.html",
"TWO_FACTOR_VERIFY_CODE_TEMPLATE": "security/two_factor_verify_code.html",
"TWO_FACTOR_SETUP_TEMPLATE": "security/two_factor_setup.html",
"TWO_FACTOR_SELECT_TEMPLATE": "security/two_factor_select.html",
"CONFIRMABLE": False,
"REGISTERABLE": False,
"RECOVERABLE": False,
"TRACKABLE": False,
"PASSWORDLESS": False,
"CHANGEABLE": False,
"TWO_FACTOR": False,
"SEND_REGISTER_EMAIL": True,
"SEND_PASSWORD_CHANGE_EMAIL": True,
"SEND_PASSWORD_RESET_EMAIL": True,
"SEND_PASSWORD_RESET_NOTICE_EMAIL": True,
"LOGIN_WITHIN": timedelta(days=1),
"CHANGE_EMAIL": False,
"CHANGE_EMAIL_TEMPLATE": "security/change_email.html",
"CHANGE_EMAIL_WITHIN": timedelta(hours=2),
"CHANGE_EMAIL_URL": "/change-email",
"CHANGE_EMAIL_CONFIRM_URL": "/change-email-confirm",
"CHANGE_EMAIL_ERROR_VIEW": None, # spa
"POST_CHANGE_EMAIL_VIEW": None, # spa
"CHANGE_EMAIL_SALT": "change-email-salt",
"CHANGE_EMAIL_SUBJECT": _("Confirm your new email address"),
"CHANGE_USERNAME": False,
"CHANGE_USERNAME_TEMPLATE": "security/change_username.html",
"CHANGE_USERNAME_URL": "/change-username",
"POST_CHANGE_USERNAME_VIEW": None,
"SEND_USERNAME_CHANGE_EMAIL": True,
"TWO_FACTOR_AUTHENTICATOR_VALIDITY": 120,
"TWO_FACTOR_MAIL_VALIDITY": 300,
"TWO_FACTOR_SMS_VALIDITY": 120,
"TWO_FACTOR_ALWAYS_VALIDATE": True,
"TWO_FACTOR_LOGIN_VALIDITY": timedelta(days=30),
"TWO_FACTOR_VALIDITY_SALT": "tf-validity-salt",
"TWO_FACTOR_VALIDITY_COOKIE_NAME": "tf_validity",
"TWO_FACTOR_VALIDITY_COOKIE": {
"httponly": True,
"secure": True,
"samesite": "Strict",
},
"TWO_FACTOR_SETUP_SALT": "tf-setup-salt",
"TWO_FACTOR_SETUP_WITHIN": timedelta(minutes=30),
"TWO_FACTOR_RESCUE_EMAIL": True,
"MULTI_FACTOR_RECOVERY_CODES": False,
"MULTI_FACTOR_RECOVERY_CODES_N": 5,
"MULTI_FACTOR_RECOVERY_CODES_URL": "/mf-recovery-codes",
"MULTI_FACTOR_RECOVERY_CODES_TEMPLATE": "security/mf_recovery_codes.html",
"MULTI_FACTOR_RECOVERY_URL": "/mf-recovery",
"MULTI_FACTOR_RECOVERY_TEMPLATE": "security/mf_recovery.html",
"MULTI_FACTOR_RECOVERY_CODES_KEYS": None,
"MULTI_FACTOR_RECOVERY_CODE_TTL": None,
"OAUTH_ENABLE": False,
"OAUTH_BUILTIN_PROVIDERS": ["github", "google"],
"OAUTH_START_URL": "/login/oauthstart",
"OAUTH_RESPONSE_URL": "/login/oauthresponse",
"OAUTH_VERIFY_START_URL": "/login/oauth-verify-start",
"OAUTH_VERIFY_RESPONSE_URL": "/login/oauth-verify-response",
"CONFIRM_EMAIL_WITHIN": timedelta(days=2),
"RESET_PASSWORD_WITHIN": timedelta(days=1),
"LOGIN_WITHOUT_CONFIRMATION": False,
"AUTO_LOGIN_AFTER_CONFIRM": False,
"AUTO_LOGIN_AFTER_RESET": False,
"EMAIL_SENDER": LocalProxy(
lambda: current_app.config.get("MAIL_DEFAULT_SENDER", "no-reply@localhost")
),
"TWO_FACTOR_RESCUE_MAIL": "no-reply@localhost",
"TOKEN_AUTHENTICATION_KEY": "auth_token",
"TOKEN_AUTHENTICATION_HEADER": "Authentication-Token",
"TOKEN_MAX_AGE": timedelta(minutes=15),
"TOKEN_EXPIRE_TIMESTAMP": lambda user: 0,
"REFRESH_TOKEN": False,
"REFRESH_TOKEN_SALT": "refresh-token-salt",
"REFRESH_TOKEN_MAX_AGE": timedelta(days=90),
"REFRESH_TOKEN_MAX_IDLE": timedelta(days=7),
"REFRESH_TOKEN_CLEANUP_EXPIRED": True,
"REFRESH_TOKEN_CLEANUP_REVOKED": False,
"REFRESH_TOKEN_URL": "/refresh-token",
"REFRESH_TOKEN_COOKIE_NAME": "fs_refresh",
"REFRESH_TOKEN_COOKIE": {
"samesite": "Strict",
"httponly": True,
"secure": True,
},
"CONFIRM_SALT": "confirm-salt",
"RESET_SALT": "reset-salt",
"LOGIN_SALT": "login-salt",
"CHANGE_SALT": "change-salt",
"REMEMBER_SALT": "remember-salt",
"DEFAULT_REMEMBER_ME": False,
"DEFAULT_HTTP_AUTH_REALM": _("Login Required"),
"EMAIL_SUBJECT_REGISTER": _("Welcome"),
"EMAIL_SUBJECT_CONFIRM": _("Please confirm your email"),
"EMAIL_SUBJECT_PASSWORDLESS": _("Login instructions"),
"EMAIL_SUBJECT_PASSWORD_NOTICE": _("Your password has been reset"),
"EMAIL_SUBJECT_PASSWORD_CHANGE_NOTICE": _("Your password has been changed"),
"EMAIL_SUBJECT_PASSWORD_RESET": _("Password reset instructions"),
"EMAIL_SUBJECT_USERNAME_CHANGE_NOTICE": _("Your username has been changed"),
"EMAIL_SUBJECT_USERNAME_RECOVERY": _("Your requested username"),
"EMAIL_PLAINTEXT": True,
"EMAIL_HTML": True,
"EMAIL_SUBJECT_TWO_FACTOR": _("Two-Factor Login"),
"EMAIL_SUBJECT_TWO_FACTOR_RESCUE": _("Two-Factor Rescue"),
"USER_IDENTITY_ATTRIBUTES": [
{"email": {"mapper": uia_email_mapper, "case_insensitive": True}}
],
"PHONE_REGION_DEFAULT": "US",
"FRESHNESS": timedelta(hours=24),
"FRESHNESS_GRACE_PERIOD": timedelta(hours=1),
"FRESHNESS_ALLOW_AUTH_TOKEN": True,
"API_ENABLED_METHODS": ["session", "token"],
"DATETIME_FACTORY": naive_utcnow,
"TOTP_SECRETS": None,
"TOTP_ISSUER": None,
"SMS_SERVICE": "Dummy",
"SMS_SERVICE_CONFIG": {
"ACCOUNT_SID": None,
"AUTH_TOKEN": None,
"PHONE_NUMBER": None,
},
"TWO_FACTOR_REQUIRED": False,
"TWO_FACTOR_ENABLED_METHODS": ["email", "authenticator", "sms"],
"TWO_FACTOR_IMPLEMENTATIONS": {
"code": "flask_security.twofactor.CodeTfPlugin",
"webauthn": "flask_security.webauthn.WebAuthnTfPlugin",
},
"UNIFIED_SIGNIN": False,
"USERNAME_RECOVERY": False,
"USERNAME_RECOVERY_TEMPLATE": "security/recover_username.html",
"USERNAME_RECOVERY_URL": "/recover-username",
"US_SETUP_SALT": "us-setup-salt",
"US_SIGNIN_URL": "/us-signin",
"US_SIGNIN_SEND_CODE_URL": "/us-signin/send-code",
"US_SETUP_URL": "/us-setup",
"US_VERIFY_URL": "/us-verify",
"US_VERIFY_SEND_CODE_URL": "/us-verify/send-code",
"US_VERIFY_LINK_URL": "/us-verify-link",
"US_POST_SETUP_VIEW": ".us_setup", # endpoint or URL
"US_SIGNIN_TEMPLATE": "security/us_signin.html",
"US_SETUP_TEMPLATE": "security/us_setup.html",
"US_VERIFY_TEMPLATE": "security/us_verify.html",
"US_ENABLED_METHODS": ["password", "email", "authenticator", "sms"],
"US_MFA_REQUIRED": ["password", "email"],
"US_TOKEN_VALIDITY": 120,
"US_EMAIL_SUBJECT": _("Verification Code"),
"US_SETUP_WITHIN": timedelta(minutes=30),
"US_SIGNIN_REPLACES_LOGIN": False,
"CACHE_CONTROL": {"private": True, "no-store": True},
"CSRF_PROTECT_MECHANISMS": AUTHN_MECHANISMS,
"CSRF_IGNORE_UNAUTH_ENDPOINTS": False,
"CSRF_COOKIE_NAME": None,
"CSRF_COOKIE": {
"samesite": "Strict",
"httponly": False,
"secure": True,
},
"CSRF_HEADER": "X-XSRF-Token",
"CSRF_COOKIE_REFRESH_EACH_REQUEST": False,
"BACKWARDS_COMPAT_AUTH_TOKEN": False,
"JOIN_USER_ROLES": True,
"USERNAME_ENABLE": False,
"USERNAME_REQUIRED": False,
"USERNAME_MIN_LENGTH": 4,
"USERNAME_MAX_LENGTH": 32,
"USERNAME_NORMALIZE_FORM": "NFKD",
"WEBAUTHN": False,
"WAN_CHALLENGE_BYTES": None, # uses system default
"WAN_POST_REGISTER_VIEW": ".wan_register", # endpoint or URL
"WAN_RP_NAME": "My Flask App",
"WAN_SALT": "wan-salt",
"WAN_REGISTER_TIMEOUT": 60000, # milliseconds
"WAN_REGISTER_TEMPLATE": "security/wan_register.html",
"WAN_REGISTER_URL": "/wan-register",
"WAN_REGISTER_WITHIN": timedelta(minutes=30),
"WAN_SIGNIN_TIMEOUT": 60000, # milliseconds
"WAN_SIGNIN_TEMPLATE": "security/wan_signin.html",
"WAN_SIGNIN_URL": "/wan-signin",
"WAN_SIGNIN_WITHIN": timedelta(minutes=1),
"WAN_DELETE_URL": "/wan-delete",
"WAN_VERIFY_URL": "/wan-verify",
"WAN_VERIFY_TEMPLATE": "security/wan_verify.html",
"WAN_ALLOW_AS_FIRST_FACTOR": True,
"WAN_ALLOW_AS_MULTI_FACTOR": True,
"WAN_ALLOW_USER_HINTS": True,
"WAN_ALLOW_AS_VERIFY": ["first", "secondary"],
"ZXCVBN_MINIMUM_SCORE": 3,
}
#: Default Flask-Security messages
_default_messages = {
"API_ERROR": (_("Input not appropriate for requested API"), "error"),
"GENERIC_AUTHN_FAILED": (
_("Authentication failed - identity or password/passcode invalid"),
"error",
),
"GENERIC_RECOVERY": (
_(
"If that email address is in our system, "
"you will receive an email describing how to reset your password."
),
"info",
),
"GENERIC_US_SIGNIN": (
_("If that identity is in our system, you were sent a code."),
"info",
),
"UNAUTHORIZED": (_("You do not have permission to view this resource."), "error"),
"UNAUTHENTICATED": (
_("You must sign in to view this resource."),
"error",
),
"REAUTHENTICATION_REQUIRED": (
_("You must reauthenticate to access this endpoint"),
"error",
),
"CONFIRM_REGISTRATION": (
_(
"Thank you. To confirm your email address %(email)s,"
" please click on the link"
" in the email we have just sent to you."
),
"success",
),
"EMAIL_CONFIRMED": (_("Thank you. Your email has been confirmed."), "success"),
"ALREADY_CONFIRMED": (_("Your email has already been confirmed."), "info"),
"INVALID_CONFIRMATION_TOKEN": (_("Invalid confirmation token."), "error"),
"EMAIL_ALREADY_ASSOCIATED": (
_("%(email)s is already associated with an account."),
"error",
),
"IDENTITY_ALREADY_ASSOCIATED": (
_(
"Identity attribute '%(attr)s' with value '%(value)s' is already"
" associated with an account."
),
"error",
),
"IDENTITY_NOT_REGISTERED": (
_("Identity %(id)s not registered"),
"error",
),
"OAUTH_HANDSHAKE_ERROR": (
_(
"An error occurred while communicating with the OAuth provider:"
" (%(exerror)s - %(exdesc)s). "
"Please try again."
),
"error",
),
"PASSWORD_MISMATCH": (_("Password does not match"), "error"),
"RETYPE_PASSWORD_MISMATCH": (_("Passwords do not match"), "error"),
"INVALID_REDIRECT": (_("Redirections outside the domain are forbidden"), "error"),
"INVALID_RECOVERY_CODE": (_("Recovery code invalid"), "error"),
"NO_RECOVERY_CODES_SETUP": (_("No recovery codes generated yet"), "info"),
"PASSWORD_RESET_REQUEST": (
_("Instructions to reset your password have been sent to %(email)s."),
"info",
),
"PASSWORD_RESET_EXPIRED": (
_("You did not reset your password within %(within)s. "),
"error",
),
"INVALID_RESET_PASSWORD_TOKEN": (_("Invalid reset password token."), "error"),
"CONFIRMATION_REQUIRED": (_("Email requires confirmation."), "error"),
"CONFIRMATION_REQUEST": (
_("Confirmation instructions have been sent to %(email)s."),
"info",
),
"CONFIRMATION_EXPIRED": (
_("You did not confirm your email within %(within)s. "),
"error",
),
"LOGIN_EXPIRED": (
_(
"You did not login within %(within)s. New instructions to login "
"have been sent to %(email)s."
),
"error",
),
"LOGIN_EMAIL_SENT": (
_("Instructions to login have been sent to %(email)s."),
"success",
),
"INVALID_LOGIN_TOKEN": (_("Invalid login token."), "error"),
"DISABLED_ACCOUNT": (_("Account is disabled."), "error"),
"EMAIL_NOT_PROVIDED": (_("Email not provided"), "error"),
"INVALID_EMAIL_ADDRESS": (_("Invalid email address"), "error"),
"INVALID_CODE": (_("Invalid code"), "error"),
"PASSWORD_NOT_PROVIDED": (_("Password not provided"), "error"),
"PASSWORD_INVALID_LENGTH": (
_("Password must be at least %(length)s characters"),
"error",
),
"PASSWORD_TOO_SIMPLE": (_("Password not complex enough"), "error"),
"PASSWORD_BREACHED": (_("Password on breached list"), "error"),
"PASSWORD_BREACHED_SITE_ERROR": (
_("Failed to contact breached passwords site"),
"error",
),
"PHONE_INVALID": (_("Phone number not valid e.g. missing country code"), "error"),
"USER_DOES_NOT_EXIST": (_("Specified user does not exist"), "error"),
"INVALID_PASSWORD": (_("Invalid password"), "error"),
"INVALID_PASSWORD_CODE": (_("Password or code submitted is not valid"), "error"),
"PASSWORDLESS_LOGIN_SUCCESSFUL": (_("You have successfully logged in."), "success"),
"FORGOT_PASSWORD": (_("Forgot password?"), "info"),
"PASSWORD_RESET": (
_(
"You successfully reset your password and you have been logged in "
"automatically."
),
"success",
),
"PASSWORD_RESET_NO_LOGIN": (
_(
"You successfully reset your password."
" Please authenticate using your new password."
),
"success",
),
"PASSWORD_IS_THE_SAME": (
_("Your new password must be different than your previous password."),
"error",
),
"PASSWORD_CHANGE": (_("You successfully changed your password."), "success"),
"LOGIN": (_("Please log in to access this page."), "info"),
"REFRESH": (_("Please reauthenticate to access this page."), "info"),
"REFRESH_TOKEN_INVALID": (_("Refresh token is invalid (%(reason)s)"), "error"),
"REAUTHENTICATION_SUCCESSFUL": (_("Reauthentication successful"), "info"),
"ANONYMOUS_USER_REQUIRED": (
_("You can only access this endpoint when not logged in."),
"error",
),
"CODE_HAS_BEEN_SENT": (_("Code has been sent."), "info"),
"FAILED_TO_SEND_CODE": (_("Failed to send code. Please try again later"), "error"),
"TWO_FACTOR_INVALID_TOKEN": (_("Invalid code"), "error"),
"TWO_FACTOR_LOGIN_SUCCESSFUL": (_("Your code has been confirmed"), "success"),
"TWO_FACTOR_CHANGE_METHOD_SUCCESSFUL": (
_("You successfully changed your two-factor method."),
"success",
),
"TWO_FACTOR_PERMISSION_DENIED": (
_("You currently do not have permissions to access this page"),
"error",
),
"TWO_FACTOR_METHOD_NOT_AVAILABLE": (_("Marked method is not valid"), "error"),
"TWO_FACTOR_DISABLED": (
_("You successfully disabled two-factor authorization."),
"success",
),
"TWO_FACTOR_SETUP_EXPIRED": (
_("Setup must be completed within %(within)s. Please start over."),
"error",
),
"US_CURRENT_METHODS": (
_("Currently active sign in options: %(method_list)s."),
"info",
),
"US_METHOD_NOT_AVAILABLE": (_("Requested method is not valid"), "error"),
"US_SETUP_EXPIRED": (
_("Setup must be completed within %(within)s. Please start over."),
"error",
),
"US_SETUP_SUCCESSFUL": (_("Unified sign in setup successful"), "info"),
"US_SPECIFY_IDENTITY": (_("You must specify a valid identity to sign in"), "error"),
"USE_CODE": (_("Use this code to sign in: %(code)s"), "info"),
"USERNAME_CHANGE": (_("You successfully changed your username"), "success"),
"USERNAME_INVALID_LENGTH": (
_(
"Username must be at least %(min)d characters and less than"
" %(max)d characters"
),
"error",
),
"USERNAME_ILLEGAL_CHARACTERS": (
_("Username contains illegal characters"),
"error",
),
"USERNAME_DISALLOWED_CHARACTERS": (
_("Username can contain only letters and numbers"),
"error",
),
"USERNAME_NOT_PROVIDED": (_("Username not provided"), "error"),
"USERNAME_ALREADY_ASSOCIATED": (
_("%(username)s is already associated with an account."),
"error",
),
"WEBAUTHN_EXPIRED": (
_("Passkey operations must be completed within %(within)s. Please start over."),
"error",
),
"WEBAUTHN_NAME_REQUIRED": (
_("Nickname for new passkey is required."),
"error",
),
"WEBAUTHN_NAME_INUSE": (
_("%(name)s is already associated with a passkey."),
"error",
),
"WEBAUTHN_NAME_NOT_FOUND": (
_("%(name)s not registered with current user."),
"error",
),
"WEBAUTHN_CREDENTIAL_DELETED": (
_("Successfully deleted the passkey with name: %(name)s"),
"info",
),
"WEBAUTHN_REGISTER_SUCCESSFUL": (
_("Successfully added the passkey with name: %(name)s"),
"info",
),
"WEBAUTHN_CREDENTIAL_ID_INUSE": (
_("Passkey already registered."),
"error",
),
"WEBAUTHN_UNKNOWN_CREDENTIAL_ID": (
_("Unregistered passkey."),
"error",
),
"WEBAUTHN_ORPHAN_CREDENTIAL_ID": (
_("Passkey doesn't belong to any user."),
"error",
),
"WEBAUTHN_NO_VERIFY": (
_("Could not verify passkey: %(cause)s."),
"error",
),
"WEBAUTHN_CREDENTIAL_WRONG_USAGE": (
_("Passkey not registered for this use (first or secondary)"),
"error",
),
"WEBAUTHN_MISMATCH_USER_HANDLE": (
_("Credential user handle didn't match"),
"error",
),
"CHANGE_EMAIL_EXPIRED": (
_("Confirmation must be completed within %(within)s. Please start over."),
"error",
),
"CHANGE_EMAIL_CONFIRMED": (
_("Change of email address confirmed"),
"success",
),
"CHANGE_EMAIL_SENT": (
_(
"Instructions to confirm your new email address have"
" been sent to %(email)s."
),
"success",
),
"USERNAME_RECOVERY_REQUEST": (
_("If registered, your username will be sent to your email."),
"info",
),
}
def _default_form_instantiator(
name: str, cls: t.Type[Form], *args: t.Any, **kwargs: dict[str, t.Any]
) -> Form:
return cls(*args, **kwargs)
@dataclass
class FormInfo:
"""
Each view form has a name - assigned by Flask-Security.
As part of every request, the form is instantiated using (usually) request.form or
request.json.
The default instantiator simply uses the class constructor - however
applications can provide their OWN instantiator which can do pretty much anything
as long as it returns an instantiated form. The 'cls' argument is optional since
the instantiator COULD be form agnostic (using the form name to differentiate).
The instantiator callable will always be called from a flask request context
and receive the following arguments::
(name, form_cls_name (optional), **kwargs)
kwargs will always have `formdata` and often will have `meta`. All kwargs
must be passed to the underlying form constructor.
See :py:meth:`flask_security.Security.set_form_info`
.. versionadded:: 5.1.0
"""
instantiator: t.Callable[..., Form] = _default_form_instantiator
cls: t.Type[Form] | None = None
def _user_loader(user_id):
"""Load based on fs_uniquifier (alternative_id).
If the db model and db are properly configured and set there is no way we should
ever see a null user_id. But it is clearly wrong.
"""
if not user_id:
return None
user = _security.datastore.find_user(fs_uniquifier=str(user_id))
if user and user.active:
set_request_attr("fs_authn_via", "session")
set_request_attr("fs_paa", session.get("fs_paa", 0))
return user
return None
def _request_loader(request):
# Short-circuit if we have already been called and verified.
# This can happen since Flask-Login will call us (if no session) and our own
# decorator @auth_token_required can call us.
# N.B. we don't call current_user here since that in fact might try and LOAD
# a user - which would call us again.
if get_request_attr("fs_authn_via") == "token":
return g._login_user
header_key = cv("TOKEN_AUTHENTICATION_HEADER")
args_key = cv("TOKEN_AUTHENTICATION_KEY")
header_token = request.headers.get(header_key, None)
token = request.args.get(args_key, header_token)
if request.is_json:
data = request.get_json(silent=True) or {}
if isinstance(data, dict):
token = data.get(args_key, token)
try:
tdata = parse_auth_token(token)
# Fallback to fs_uniquifier - allows upgrading to token_uniquifier while
# old tokens still work.
user = None
if hasattr(_security.datastore.user_model, "fs_token_uniquifier"):
user = _security.datastore.find_user(fs_token_uniquifier=tdata["uid"])
if not user:
user = _security.datastore.find_user(fs_uniquifier=tdata["uid"])
except Exception:
return None
if user and user.active and user.verify_auth_token(tdata):
set_request_attr("fs_authn_via", "token")
if cv("FRESHNESS_ALLOW_AUTH_TOKEN"):
set_request_attr("fs_paa", tdata.get("fs_paa", 0))
return user
return None
def _identity_loader():
# N.B. once AnonymousUser is gone - can just check current_user
if current_user and hasattr(current_user, "fs_uniquifier"):
return Identity(current_user.fs_uniquifier)
return None
def _on_identity_loaded(sender, identity):
if current_user and hasattr(current_user, "fs_uniquifier"):
identity.provides.add(UserNeed(current_user.fs_uniquifier))
for role in getattr(current_user, "roles", []):
identity.provides.add(RoleNeed(role.name))
for fsperm in role.get_permissions():
identity.provides.add(FsPermNeed(fsperm))
identity.user = current_user
def _get_login_manager(app, security):
lm = LoginManager()
# Flask-Login is likely going in the direction of removing AnonymousUser
# however this might wreak havoc on applications that just assume that
# current_user is always set.
if cv("ANONYMOUS_USER_DISABLED", app=app):
lm.anonymous_user = lambda: None
else:
lm.anonymous_user = AnonymousUser
lm.user_loader(_user_loader)
lm.request_loader(_request_loader)
# Set Flask-Login handler so @login_required will have same behavior as
# @auth_required
lm.unauthorized_callback = security._unauthn_handler
# Note: since we redirect unauthenticated requests to us - we no longer need to
# mess with Flask-Login login_view, or message settings.
# We also (5.4.0) stop doing anything with need_fresh_login - we support time-based
# freshness.
lm.init_app(app)
return lm
def _get_principal(app):
p = Principal(app, use_sessions=False)
p.identity_loader(_identity_loader)
return p
def _get_pwd_context(app: flask.Flask) -> CryptContext:
pw_hash = cv("PASSWORD_HASH", app=app)
schemes = cv("PASSWORD_SCHEMES", app=app)
deprecated = cv("DEPRECATED_PASSWORD_SCHEMES", app=app)
if pw_hash not in schemes:
allowed = ", ".join(schemes[:-1]) + " and " + schemes[-1]
raise ValueError(
f"Invalid password hashing scheme {pw_hash}. Allowed values are {allowed}"
)
cc = CryptContext(
schemes=schemes,
default=pw_hash,
deprecated=deprecated,
**cv("PASSWORD_HASH_PASSLIB_OPTIONS", app=app),
)
return cc
def _get_hashing_context(app: flask.Flask) -> CryptContext:
schemes = cv("HASHING_SCHEMES", app=app)
deprecated = cv("DEPRECATED_HASHING_SCHEMES", app=app)
return CryptContext(schemes=schemes, deprecated=deprecated)
def _get_serializer(app, name, serializer=URLSafeTimedSerializer):
secret_key = app.config.get("SECRET_KEY")
derived_keys = app.config.get("SECRET_KEY_FALLBACKS")
secret_keys = [secret_key] + (
derived_keys if isinstance(derived_keys, list) else []
)
salt = cv(f"{name.upper()}_SALT", app=app)
return serializer(secret_keys, salt=salt)
def _context_processor():
return dict(
url_for_security=url_for_security,
security=_security,
_fs_is_user_authenticated=is_user_authenticated,
)
class RoleMixin:
"""Mixin for `Role` model definitions"""
if t.TYPE_CHECKING: # pragma: no cover
id: int
name: str
description: str | None
permissions: list[str] | None
update_datetime: datetime
def __init__(self, **kwargs): ...
def __eq__(self, other):
return self.name == other or self.name == getattr(other, "name", None)
def __ne__(self, other):
return not self.__eq__(other)
def __hash__(self):
return hash(self.name)
def get_permissions(self) -> set:
"""
Return set of permissions associated with role.
.. versionadded:: 3.3.0
"""
if hasattr(self, "permissions") and self.permissions:
return set(self.permissions)
return set()
class UserMixin(BaseUserMixin):
"""Mixin for `User` model definitions"""
if t.TYPE_CHECKING: # pragma: no cover
# These are defined in the applications Model files.
id: int
email: str
username: str | None
password: str | None
active: bool
fs_uniquifier: str
fs_token_uniquifier: str
fs_webauthn_user_handle: str
confirmed_at: datetime | None
last_login_at: datetime
current_login_at: datetime
last_login_ip: str | None
current_login_ip: str | None
login_count: int
tf_primary_method: str | None
tf_totp_secret: str | None
tf_phone_number: str | None
mf_recovery_codes: list[str] | None
us_phone_number: str | None
us_totp_secrets: str | bytes | None
create_datetime: datetime
update_datetime: datetime
roles: list[RoleMixin]
webauthn: list[WebAuthnMixin]
refresh_trackers: list[RefreshTrackerMixin]
def __init__(self, **kwargs): ...
def get_id(self) -> str:
"""Returns the user identification attribute. 'Alternative-token' for
Flask-Login. This is always ``fs_uniquifier``.
.. versionadded:: 3.4.0
"""
return str(self.fs_uniquifier)
@property
def is_active(self) -> bool:
"""Returns `True` if the user is active."""
return self.active
def get_auth_token(self) -> str | bytes:
"""Constructs the user's authentication token.
:raises ValueError: If ``fs_token_uniquifier`` is part of model but not set.
Uses ``fs_uniquifier`` or ``fs_token_uniquifier`` (if in the UserModel)
to identify this user. If ``fs_token_uniquifier`` is used then
changing password doesn't invalidate auth tokens.
Calls :meth:`.UserMixin.augment_auth_token` which applications can override
to add any additional information.
The returned value is securely signed using the ``remember_token_serializer``
.. versionchanged:: 4.0.0
If user model has ``fs_token_uniquifier`` - use that (raise ValueError
if not set). Otherwise, fallback to using ``fs_uniquifier``.
.. versionchanged:: 5.4.0
New format - a dict with a version string. Add a token-based expiry
option as well as a session id.
.. versionchanged:: 5.5.0
Remove session id (never set or used); added fs_paa (last authentication
timestamp)
"""
from .proxies import _datastore
uid = getattr(self, _datastore.get_token_uniquifier_name())
if not uid:
raise ValueError()
tdata: dict[str, t.Any] = {
"ver": str(5),
"uid": uid,
"fs_paa": time.time(), # equivalent of session["fs_paa"]
"exp": int(cv("TOKEN_EXPIRE_TIMESTAMP")(self)), # if >0 then shorter of
# :data:SECURITY_MAX_AGE and this.
}
# Let application add things
self.augment_auth_token(tdata)
# Serialize and sign
return _security.remember_token_serializer.dumps(tdata)
def augment_auth_token(self, tdata: dict[str, t.Any]) -> None:
"""Override this to add/modify parts of the auth token.
Additions to the dict can be made here and verified in
:meth:`.UserMixin.verify_auth_token`
.. versionadded:: 5.4.0
"""
return
def verify_auth_token(self, tdata: dict[str, t.Any]) -> bool:
"""
Override this to perform additional verification of contents of auth token.
Prior to this being called the token has been validated (via signing)
and has not expired (either with MAX_AGE or specific 'exp' value).