Debian Codegraph @

flask_security/decorators.py

raw
1 """
2 flask_security.decorators
3 ~~~~~~~~~~~~~~~~~~~~~~~~~
4
5 Flask-Security decorators module
6
7 :copyright: (c) 2012-2019 by Matt Wright.
8 :copyright: (c) 2019-2026 by J. Christopher Wagner (jwag).
9 :license: MIT, see LICENSE for more details.
10 """
11
12 from __future__ import annotations
13
14 from collections import namedtuple
15 import datetime
16 from functools import wraps
17 import typing as t
18
19 from flask import Response, abort, current_app, g, redirect, request
20 from flask_login import current_user, login_required # noqa: F401
21 from flask_principal import Identity, Permission, RoleNeed, identity_changed
22 from flask_wtf.csrf import CSRFError
23 from werkzeug.local import LocalProxy
24
25 from .proxies import _security, DecoratedView
26 from .signals import user_unauthenticated
27 from .utils import (
28 FsPermNeed,
29 config_value as cv,
30 do_flash,
31 get_message,
32 get_url,
33 is_user_authenticated,
34 lookup_identity,
35 check_and_update_authn_fresh,
36 json_error_response,
37 set_request_attr,
38 simplify_url,
39 get_request_attr,
40 url_for_security,
41 )
42
43 if t.TYPE_CHECKING: # pragma: no cover
44 from flask.typing import ResponseValue
45
46 # Convenient references
47 _csrf = LocalProxy(lambda: current_app.extensions["csrf"])
48
49 BasicAuth = namedtuple("BasicAuth", "username, password")
50
51
52 def default_unauthn_handler(mechanisms=None, headers=None):
53 """Default callback when a protected endpoint is accessed without the required
54 authentication.
55
56 The :data:`user_unauthenticated` signal is sent.
57
58 If caller wants JSON - return 401.
59 If caller wants BasicAuth - return 401 (the WWW-Authenticate header is set).
60 Otherwise - assume caller is html and redirect if possible to a login view.
61 """
62 user_unauthenticated.send(
63 current_app._get_current_object(), # type: ignore[attr-defined]
64 _async_wrapper=current_app.ensure_sync,
65 )
66 headers = headers or {}
67 m, c = get_message("UNAUTHENTICATED")
68
69 if _security._want_json(request):
70 payload = json_error_response(errors=m)
71 return _security._render_json(payload, 401, headers, None)
72
73 # Basic-Auth is often used to provide a browser based login form and then the
74 # browser will always add the BasicAuth credentials. For that to work we need to
75 # return 401 and not redirect to our login view.
76 if "WWW-Authenticate" in headers:
77 return Response(m, 401, headers)
78
79 do_flash(m, c)
80 # Simplify the original URL to be relative (if possible) and set as 'next' parameter
81 login_url = url_for_security("login", _external=True)
82 next_url = simplify_url(login_url, request.url)
83 redirect_url = url_for_security("login", next=next_url)
84 return redirect(redirect_url)
85
86
87 def default_reauthn_handler(within, grace):
88 """Default callback for 'freshness' related authn failures.
89
90 If caller wants JSON - return 401
91 Otherwise - assume caller is html and redirect if possible to configured view.
92
93 """
94 m, c = get_message("REAUTHENTICATION_REQUIRED")
95
96 if _security._want_json(request):
97 from .webauthn import has_webauthn
98
99 is_us = cv("UNIFIED_SIGNIN")
100 payload = json_error_response(errors=m)
101 payload["reauth_required"] = True
102 payload["unified_signin_enabled"] = is_us
103 payload["has_webauthn_verify_credential"] = has_webauthn(
104 current_user, cv("WAN_ALLOW_AS_VERIFY")
105 )
106 payload["oauth_enabled"] = cv("OAUTH_ENABLE")
107 payload["oauth_providers"] = (
108 _security.oauthglue.provider_names if cv("OAUTH_ENABLE") else []
109 )
110 return _security._render_json(payload, 401, None, None)
111
112 view = "us_verify" if cv("UNIFIED_SIGNIN") else "verify"
113 do_flash(m, c)
114 # Simplify the original URL to be relative (if possible) and set as 'next' parameter
115 view_url = url_for_security(view, _external=True)
116 next_url = simplify_url(view_url, request.url)
117 redirect_url = url_for_security(view, next=next_url)
118 return redirect(redirect_url)
119
120
121 def default_unauthz_handler(func_name, params):
122 unauthz_message, unauthz_message_type = get_message("UNAUTHORIZED")
123 if _security._want_json(request):
124 payload = json_error_response(errors=unauthz_message)
125 return _security._render_json(payload, 403, None, None)
126 if view := cv("UNAUTHORIZED_VIEW"):
127 if callable(view):
128 if not (redirect_to := view()):
129 abort(403)
130 else:
131 redirect_to = get_url(view)
132 do_flash(unauthz_message, unauthz_message_type)
133 return redirect(redirect_to)
134 abort(403)
135
136
137 def _check_token():
138 user = _security.login_manager.request_callback(request)
139 if is_user_authenticated(user):
140 identity_changed.send(
141 current_app._get_current_object(),
142 _async_wrapper=current_app.ensure_sync,
143 identity=Identity(user.fs_uniquifier),
144 )
145 return True
146
147 return False
148
149
150 def _check_session():
151 """
152 Note that flask_login will have already run _load_user (due to someone referencing
153 current_user proxy). This will have called our _user_loader or _request_loader
154 already.
155 This method needs to determine whether the authenticated user was authenticated
156 due to _user_loader or _request_loader and return True for the former.
157 This routine makes sure that if an endpoint is decorated with just allowing
158 'session' that token authentication won't return True (even though the user
159 is in fact correctly authenticated). There are certainly endpoints that need to
160 be web browser/session only (often those that in fact return tokens!).
161 """
162 if not is_user_authenticated(current_user):
163 return False
164 if get_request_attr("fs_authn_via") != "session":
165 return False
166 return True
167
168
169 def _check_http_auth():
170 auth = request.authorization or BasicAuth(username=None, password=None)
171 if not auth.username:
172 return False
173 user = lookup_identity(auth.username)
174 if user and not user.active:
175 return False
176
177 if user and user.verify_and_update_password(auth.password):
178 _security.datastore.commit()
179 _security.login_manager._update_request_context_with_user(user)
180 identity_changed.send(
181 current_app._get_current_object(),
182 _async_wrapper=current_app.ensure_sync,
183 identity=Identity(user.fs_uniquifier),
184 )
185 return True
186
187 return False
188
189
190 def handle_csrf(method: str, json_response: bool = False) -> ResponseValue | None:
191 """Invoke CSRF protection based on authentication method.
192
193 Usually this is called as part of a decorator, but if that isn't
194 appropriate, endpoint code can call this directly.
195
196 If CSRF protection is appropriate, this will call flask_wtf::protect() which
197 will raise a CSRFError(BadRequest) on CSRF failure.
198
199 This routine does nothing if any of these are true:
200
201 #) *WTF_CSRF_ENABLED* is set to False
202
203 #) the Flask-WTF CSRF module hasn't been initialized
204
205 #) csrfProtect already checked and accepted the token
206
207 This means in the default config - CSRF is done as part of form validation,
208 not here. Only if the application calls CSRFProtect(app) will this method
209 do anything. Furthermore - since this is called PRIOR to form instantiation
210 if the request is JSON - it MUST send the csrf_token as a header.
211
212 If the passed in method is not in
213 :py:data:`SECURITY_CSRF_PROTECT_MECHANISMS` then in addition to
214 no CSRF code being run, the flask_wtf request global 'csrf_valid' will be set
215 so that downstream code knows to ignore any CSRF checks.
216
217 Returns None if all ok, returns a Response with JSON error if request
218 wanted JSON - else re-raises the CSRFError exception.
219
220 .. versionadded:: 3.3.0
221
222 .. versionchanged:: 5.4.3
223 Use flask_wtf request global 'csrf_valid' instead of our own to handle
224 application forms that aren't derived from our forms.
225 """
226 if (
227 not current_app.config.get("WTF_CSRF_ENABLED", False)
228 or not current_app.extensions.get("csrf", None)
229 or g.get("csrf_valid", False)
230 ):
231 return None
232
233 if cv("CSRF_PROTECT_MECHANISMS"):
234 if method in cv("CSRF_PROTECT_MECHANISMS"):
235 try:
236 _csrf.protect() # type: ignore
237 except CSRFError as e:
238 if json_response:
239 payload = json_error_response(errors=e.description)
240 return _security._render_json(payload, 400, None, None)
241 raise
242 return None
243 set_request_attr("csrf_valid", True) # flask_wtf global
244 return None
245
246
247 def http_auth_required(realm: t.Any) -> DecoratedView:
248 """Decorator that protects endpoints using Basic HTTP authentication.
249
250 :param realm: optional realm name
251
252 If authentication fails, then a 401 with the 'WWW-Authenticate' header set will be
253 returned.
254
255 Once authenticated, if so configured, CSRF protection will be tested.
256 """
257
258 def decorator(fn):
259 @wraps(fn)
260 def wrapper(*args, **kwargs):
261 if _check_http_auth():
262 eresponse = handle_csrf("basic", _security._want_json(request))
263 if eresponse:
264 return eresponse
265 set_request_attr("fs_authn_via", "basic")
266 return current_app.ensure_sync(fn)(*args, **kwargs)
267 r = cv("DEFAULT_HTTP_AUTH_REALM") if callable(realm) else realm
268 h = {"WWW-Authenticate": f'Basic realm="{r}"'}
269 return _security._unauthn_handler(["basic"], headers=h)
270
271 return wrapper
272
273 if callable(realm):
274 return decorator(realm)
275 return decorator
276
277
278 def auth_token_required(fn: DecoratedView) -> DecoratedView:
279 """Decorator that protects endpoints using token authentication. The token
280 should be added to the request by the client by using a query string
281 variable with a name equal to the configuration value of
282 :py:data:`SECURITY_TOKEN_AUTHENTICATION_KEY` or in a request header named that of
283 the configuration value of :py:data:`SECURITY_TOKEN_AUTHENTICATION_HEADER`
284
285 Once authenticated, if so configured, CSRF protection will be tested.
286 """
287
288 @wraps(fn)
289 def decorated(*args, **kwargs):
290 if _check_token():
291 eresponse = handle_csrf("token", _security._want_json(request))
292 if eresponse:
293 return eresponse
294 set_request_attr("fs_authn_via", "token")
295 return current_app.ensure_sync(fn)(*args, **kwargs)
296 return _security._unauthn_handler(["token"])
297
298 return decorated
299
300
301 def auth_required(
302 *auth_methods: str | t.Callable[[], list[str]] | None,
303 within: int | float | t.Callable[[], datetime.timedelta] = -1,
304 grace: int | float | t.Callable[[], datetime.timedelta] | None = None,
305 ) -> DecoratedView:
306 """
307 Decorator that protects endpoints through multiple mechanisms.
308 Example::
309
310 @app.route('/dashboard')
311 @auth_required('token', 'session')
312 def dashboard():
313 return 'Dashboard'
314
315 :param auth_methods: Specified mechanisms (token, basic, session). If not specified
316 then all current available mechanisms (except "basic") will be tried. A callable
317 can also be passed (useful if you need app/request context). The callable
318 must return a list.
319 :param within: Add 'freshness' check to authentication. Is either an int
320 specifying # of minutes, or a callable that returns a timedelta. For timedeltas,
321 timedelta.total_seconds() is used for the calculations:
322
323 - If > 0, then the caller must have authenticated within the time specified
324 (as measured using the session cookie or authentication token).
325 - If < 0 (the default) no freshness check is performed.
326
327 Note that Basic Auth, by definition, is always 'fresh' and will never result in
328 a redirect/error.
329 :param grace: Add a grace period for freshness checks. As above, either an int
330 or a callable returning a timedelta. If not specified then
331 :py:data:`SECURITY_FRESHNESS_GRACE_PERIOD` is used. The grace period allows
332 callers to complete the required operations w/o being prompted again.
333 See :meth:`flask_security.check_and_update_authn_fresh` for details.
334
335 Note that regardless of order specified - they will be tried in the following
336 order: token, session, basic.
337
338 The first mechanism that succeeds is used, following that, depending on
339 configuration, CSRF protection will be tested.
340
341 On authentication failure :meth:`.Security.unauthn_handler` will be called.
342
343 As a side effect, upon successful authentication, the request global
344 ``fs_authn_via`` will be set to the method ("basic", "token", "session")
345
346 .. note::
347 If "basic" is specified in addition to other methods, then if authentication
348 fails, a 401 with the "WWW-Authenticate" header will be returned - rather than
349 being redirected to the login view.
350
351 .. versionchanged:: 3.3.0
352 If ``auth_methods`` isn't specified, then all will be tried. Authentication
353 mechanisms will always be tried in order of ``token``, ``session``, ``basic``
354 regardless of how they are specified in the ``auth_methods`` parameter.
355
356 .. versionchanged:: 3.4.0
357 Added ``within`` and ``grace`` parameters to enforce a freshness check.
358
359 .. versionchanged:: 3.4.4
360 If ``auth_methods`` isn't specified try all mechanisms EXCEPT ``basic``.
361
362 .. versionchanged:: 4.0.0
363 auth_methods can be passed as a callable.
364
365 """
366
367 login_mechanisms = {
368 "token": lambda: _check_token(),
369 "session": lambda: _check_session(),
370 "basic": lambda: _check_http_auth(),
371 }
372 mechanisms_order = ["token", "session", "basic"]
373
374 def wrapper(fn):
375 @wraps(fn)
376 def decorated_view(
377 *args, auth_methods=auth_methods, within=within, grace=grace, **kwargs
378 ):
379 if callable(within):
380 within = within()
381 else:
382 within = datetime.timedelta(minutes=within)
383 if grace is None:
384 grace = cv("FRESHNESS_GRACE_PERIOD")
385 elif callable(grace):
386 grace = grace()
387 else:
388 grace = datetime.timedelta(minutes=grace)
389
390 if not auth_methods:
391 ams = {"session", "token"}
392 else:
393 ams = []
394 for am in auth_methods:
395 if callable(am):
396 ams.extend(am())
397 else:
398 ams.append(am)
399
400 h = {}
401 if "basic" in ams:
402 r = cv("DEFAULT_HTTP_AUTH_REALM")
403 h["WWW-Authenticate"] = f'Basic realm="{r}"'
404 mechanisms = [
405 (method, login_mechanisms.get(method))
406 for method in mechanisms_order
407 if method in ams
408 ]
409 for method, mechanism in mechanisms:
410 if mechanism and mechanism():
411 # successfully authenticated. Basic auth is by definition 'fresh'.
412 # If 'within' is set - check for freshness of authentication.
413 if not check_and_update_authn_fresh(within, grace, method):
414 return _security._reauthn_handler(within, grace)
415 if eresponse := handle_csrf(method, _security._want_json(request)):
416 return eresponse
417 set_request_attr("fs_authn_via", method)
418 return current_app.ensure_sync(fn)(*args, **kwargs)
419 return _security._unauthn_handler(ams, headers=h)
420
421 return decorated_view
422
423 return wrapper
424
425
426 def unauth_csrf(
427 fall_through: bool = False,
428 ) -> DecoratedView:
429 """Decorator for endpoints that don't need authentication
430 but do want CSRF checks (available via Header rather than just form).
431 This is required when setting *WTF_CSRF_CHECK_DEFAULT* = **False** since in that
432 case, without this decorator, the form validation will attempt to do the CSRF
433 check, and that will fail since the csrf-token is in the header (for pure JSON
434 requests).
435
436 This decorator does nothing unless Flask-WTF::CSRFProtect has been initialized.
437
438 This decorator does nothing if *WTF_CSRF_ENABLED* == **False**.
439
440 This decorator will suppress CSRF if caller isn't authenticated and has set the
441 :py:data:`SECURITY_CSRF_IGNORE_UNAUTH_ENDPOINTS` config variable to **True**.
442
443 If the caller IS authenticated, it will perform normal CSRF checks. This makes
444 this decorator useful for the views that can be called EITHER when authenticated
445 or anonymously.
446
447 .. versionadded:: 3.3.0
448
449 .. versionchanged:: 5.4.3
450 The fall_through parameter is now ignored.
451 Add code to properly handle JSON errors.
452 """
453
454 def wrapper(fn):
455 @wraps(fn)
456 def decorated(*args, **kwargs):
457 if (
458 not current_app.config.get("WTF_CSRF_ENABLED", False)
459 or not current_app.extensions.get("csrf", None)
460 or g.get("csrf_valid", False)
461 ):
462 return current_app.ensure_sync(fn)(*args, **kwargs)
463
464 if cv("CSRF_IGNORE_UNAUTH_ENDPOINTS") and not is_user_authenticated(
465 current_user
466 ):
467 set_request_attr("csrf_valid", True)
468 else:
469 try:
470 _csrf.protect()
471 except CSRFError as e:
472 if _security._want_json(request):
473 payload = json_error_response(errors=e.description)
474 return _security._render_json(payload, 400, None, None)
475 raise
476
477 return current_app.ensure_sync(fn)(*args, **kwargs)
478
479 return decorated
480
481 return wrapper
482
483
484 def roles_required(*roles: str) -> DecoratedView:
485 """Decorator which specifies that a user must have all the specified roles.
486 Example::
487
488 @app.route('/dashboard')
489 @roles_required('admin', 'editor')
490 def dashboard():
491 return 'Dashboard'
492
493 The current user must have both the `admin` role and `editor` role in order
494 to view the page.
495
496 :param roles: The required roles.
497 """
498
499 def wrapper(fn):
500 @wraps(fn)
501 def decorated_view(*args, **kwargs):
502 perms = [Permission(RoleNeed(role)) for role in roles]
503 for perm in perms:
504 if not perm.can():
505 return _security._unauthz_handler(
506 roles_required.__name__, list(roles)
507 )
508 return current_app.ensure_sync(fn)(*args, **kwargs)
509
510 return decorated_view
511
512 return wrapper
513
514
515 def roles_accepted(*roles: str) -> DecoratedView:
516 """Decorator which specifies that a user must have at least one of the
517 specified roles. Example::
518
519 @app.route('/create_post')
520 @roles_accepted('editor', 'author')
521 def create_post():
522 return 'Create Post'
523
524 The current user must have either the `editor` role or `author` role in
525 order to view the page.
526
527 :param roles: The possible roles.
528 """
529
530 def wrapper(fn):
531 @wraps(fn)
532 def decorated_view(*args, **kwargs):
533 perm = Permission(*(RoleNeed(role) for role in roles))
534 if perm.can():
535 return current_app.ensure_sync(fn)(*args, **kwargs)
536 return _security._unauthz_handler(roles_accepted.__name__, list(roles))
537
538 return decorated_view
539
540 return wrapper
541
542
543 def permissions_required(*fsperms: str) -> DecoratedView:
544 """Decorator which specifies that a user must have all the specified permissions.
545 Example::
546
547 @app.route('/dashboard')
548 @permissions_required('admin-write', 'editor-write')
549 def dashboard():
550 return 'Dashboard'
551
552 The current user must have BOTH permissions (via the roles it has)
553 to view the page.
554
555 N.B. Don't confuse these permissions with flask-principle Permission()!
556
557 :param fsperms: The required permissions.
558
559 .. versionadded:: 3.3.0
560 """
561
562 def wrapper(fn):
563 @wraps(fn)
564 def decorated_view(*args, **kwargs):
565 perms = [Permission(FsPermNeed(fsperm)) for fsperm in fsperms]
566 for perm in perms:
567 if not perm.can():
568 return _security._unauthz_handler(
569 permissions_required.__name__, list(fsperms)
570 )
571
572 return current_app.ensure_sync(fn)(*args, **kwargs)
573
574 return decorated_view
575
576 return wrapper
577
578
579 def permissions_accepted(*fsperms: str) -> DecoratedView:
580 """Decorator which specifies that a user must have at least one of the
581 specified permissions. Example::
582
583 @app.route('/create_post')
584 @permissions_accepted('editor-write', 'author-wrote')
585 def create_post():
586 return 'Create Post'
587
588 The current user must have one of the permissions (via the roles it has)
589 to view the page.
590
591 N.B. Don't confuse these permissions with flask-principle Permission()!
592
593 :param fsperms: The possible permissions.
594
595 .. versionadded:: 3.3.0
596 """
597
598 def wrapper(fn):
599 @wraps(fn)
600 def decorated_view(*args, **kwargs):
601 perm = Permission(*(FsPermNeed(fsperm) for fsperm in fsperms))
602 if perm.can():
603 return current_app.ensure_sync(fn)(*args, **kwargs)
604 return _security._unauthz_handler(
605 permissions_accepted.__name__, list(fsperms)
606 )
607
608 return decorated_view
609
610 return wrapper
611
612
613 def anonymous_user_required(f: DecoratedView) -> DecoratedView:
614 """Decorator which requires that caller NOT be logged in.
615 If a logged in user accesses an endpoint protected with this decorator
616 they will be redirected to the :py:data:`SECURITY_POST_LOGIN_VIEW`.
617 If the caller requests a JSON response, a 400 will be returned.
618
619 .. versionchanged:: 3.3.0
620 Support for JSON response was added.
621 """
622
623 @wraps(f)
624 def wrapper(*args, **kwargs):
625 if is_user_authenticated(current_user):
626 if _security._want_json(request):
627 payload = json_error_response(
628 errors=get_message("ANONYMOUS_USER_REQUIRED")[0]
629 )
630 return _security._render_json(payload, 400, None, None)
631 else:
632 return redirect(get_url(cv("POST_LOGIN_VIEW")))
633 return current_app.ensure_sync(f)(*args, **kwargs)
634
635 return wrapper