Debian Codegraph @

flask_security/oauth_glue.py

raw
1 """
2 flask_security.oauth_glue
3 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4
5 Class and methods to glue our login path with authlib for to support 'social' auth.
6
7 :copyright: (c) 2022-2026 by J. Christopher Wagner (jwag).
8 :license: MIT, see LICENSE for more details.
9
10 """
11
12 from __future__ import annotations
13
14 import time
15 import typing as t
16
17 try:
18 # noinspection PyUnresolvedReferences
19 from authlib.integrations.flask_client import OAuth
20
21 # noinspection PyUnresolvedReferences
22 from authlib.integrations.base_client.errors import (
23 OAuthError,
24 )
25 except ImportError: # pragma: no cover
26 pass
27
28 from flask import abort, after_this_request, redirect, request, session
29 from flask_login import current_user
30
31 from .decorators import auth_required, unauth_csrf
32 from .oauth_provider import (
33 OauthCbType,
34 FsOAuthProvider,
35 GoogleFsOauthProvider,
36 GitHubFsOauthProvider,
37 )
38 from .proxies import _security
39 from .utils import (
40 config_value as cv,
41 do_flash,
42 login_user,
43 get_identity_attribute,
44 get_message,
45 get_post_action_redirect,
46 get_url,
47 is_user_authenticated,
48 json_error_response,
49 slash_url_suffix,
50 url_for_security,
51 view_commit,
52 )
53
54 if t.TYPE_CHECKING: # pragma: no cover
55 import flask
56 from flask.typing import ResponseValue
57 from flask_security import UserMixin
58
59
60 @unauth_csrf()
61 def oauthstart(name: str) -> ResponseValue:
62 """View to start an OAuth authentication.
63 Name is a pre-registered OAuth provider.
64 TODO: remember me?
65 """
66 assert _security.oauthglue is not None
67 if is_user_authenticated(current_user):
68 # Just redirect current_user to POST_LOGIN_VIEW.
69 # For json - return an error.
70 # This endpoint is POST only.
71 # This does NOT use get_post_login_redirect() so that it doesn't look at
72 # 'next' - which can cause infinite redirect loops
73 # (see test_common::test_authenticated_loop)
74 if _security._want_json(request):
75 payload = json_error_response(
76 errors=get_message("ANONYMOUS_USER_REQUIRED")[0]
77 )
78 return _security._render_json(payload, 400, None, None)
79 else:
80 return redirect(get_url(cv("POST_LOGIN_VIEW")))
81 # we never want to return here or to the redirect location.
82 # Some providers match on entire redirect url - so we don't want to
83 # store next there. Use session.
84 session.pop("fs_oauth_next", None)
85 if request.args.get("next"):
86 session["fs_oauth_next"] = request.args.get("next")
87 return _security.oauthglue.get_redirect(name, "oauthresponse")
88
89
90 def _oauth_response_common(name: str) -> tuple[t.Any, UserMixin | None] | t.NoReturn:
91 """
92 Common code for oauth response (login or verify)
93 This can abort or raise an OAuthError or return a
94 tuple of (field_value, user)
95 """
96 assert _security.oauthglue is not None
97 authlib_provider = _security.oauthglue.authlib_provider(name)
98 oauth_provider = _security.oauthglue.providers.get(name)
99 if not authlib_provider or not oauth_provider:
100 # this should only happen with purposeful bad API call
101 abort(404) # TODO - redirect... to where?
102 # This parses the Flask Request and can raise an OAuthError
103 token = authlib_provider.authorize_access_token()
104
105 field_name, field_value = oauth_provider.fetch_identity_cb(
106 _security.oauthglue.oauth_app, token
107 )
108 # we only allow configured IDENTITY_ATTRIBUTES and run
109 # the mapper (which for email will normalize it)
110 if not (uia := get_identity_attribute(field_name)):
111 raise OAuthError(
112 error="Config error",
113 description=f"Invalid identity attribute: {field_name}",
114 )
115 field_value = uia["mapper"](field_value)
116 user = _security.datastore.find_user(**{field_name: field_value})
117 return field_value, user
118
119
120 def oauthresponse(name: str) -> ResponseValue:
121 """
122 Callback from oauth provider - response is provider specific
123 Since this is a callback from oauth provider - there is no form,
124 We may have stored the original 'next' in the session
125 N.B. all responses MUST be redirects.
126 """
127 assert _security.oauthglue is not None
128 oauth_provider = _security.oauthglue.providers.get(name)
129 try:
130 field_value, user = _oauth_response_common(name)
131 except OAuthError as e:
132 """One known way this can happen is if the session cookie 'samesite'
133 is set to 'strict' and e.g. the first time the user goes to github
134 and has to authorize this app and then redirect - the session
135 cookie isn't sent - and by default that is where the state is kept.
136 """
137 assert oauth_provider is not None
138 return oauth_provider.oauth_response_failure("LOGIN_ERROR_VIEW", e)
139 form_error: list[str] = []
140 if user and user.is_active and not user.is_locked(form_error):
141 after_this_request(view_commit)
142 next_loc = session.pop("fs_oauth_next", None)
143 response = _security.two_factor_plugins.tf_enter(
144 user, False, "oauth", next_loc=next_loc
145 )
146 if response:
147 return response
148 # two-factor not required - login user
149 login_user(user, authn_via=["oauth"])
150 if cv("REDIRECT_BEHAVIOR") == "spa":
151 redirect_url = get_url(
152 cv("POST_OAUTH_LOGIN_VIEW"), qparams=user.get_redirect_qparams()
153 )
154 else:
155 redirect_url = get_post_action_redirect(
156 "SECURITY_POST_LOGIN_VIEW", dict(next=next_loc)
157 )
158 return redirect(redirect_url)
159 # Seems ok to show identity - the only identity it could be is the callers
160 # so seems no way this can be used to enumerate registered users.
161 if user and not user.is_active:
162 m, c = get_message("DISABLED_ACCOUNT")
163 elif form_error:
164 m = form_error[0]
165 c = "error"
166 else:
167 m, c = get_message("IDENTITY_NOT_REGISTERED", id=field_value)
168 if cv("REDIRECT_BEHAVIOR") == "spa":
169 return redirect(get_url(cv("LOGIN_ERROR_VIEW"), qparams={c: m}))
170 do_flash(m, c)
171 # TODO: should redirect to where we came from?
172 return redirect(url_for_security("login"))
173
174
175 @auth_required(lambda: cv("API_ENABLED_METHODS"))
176 def oauth_verify_start(name: str) -> ResponseValue:
177 """
178 Re-authenticate to reset freshness time.
179 With a forms-based app this is the result of a reauthn_handler redirect.
180 """
181 # we never want to return here or to the redirect location.
182 # Some providers match on entire redirect url - so we don't want to
183 # store next there. Use session.
184 assert _security.oauthglue is not None
185 session.pop("fs_oauth_next", None)
186 if request.args.get("next"):
187 session["fs_oauth_next"] = request.args.get("next")
188 return _security.oauthglue.get_redirect(name, "oauth_verify_response")
189
190
191 def oauth_verify_response(name: str) -> ResponseValue:
192 """
193 Callback from oauth provider - response is provider-specific
194 Since this is a callback from oauth provider - there is no form,
195 We may have stored the original 'next' in the session
196 N.B. all responses MUST be redirects.
197 """
198 assert _security.oauthglue is not None
199 oauth_provider = _security.oauthglue.providers.get(name)
200 try:
201 field_value, user = _oauth_response_common(name)
202 except OAuthError as e:
203 """One known way this can happen is if the session cookie 'samesite'
204 is set to 'strict' and e.g. the first time the user goes to github
205 and has to authorize this app and then redirect - the session
206 cookie isn't sent - and by default that is where the state is kept.
207 """
208 assert oauth_provider is not None
209 return oauth_provider.oauth_response_failure("VERIFY_ERROR_VIEW", e)
210 next_loc = session.pop("fs_oauth_next", None)
211 if user and user.email == current_user.email:
212 # verified - so set freshness time.
213 session["fs_paa"] = time.time()
214 if cv("REDIRECT_BEHAVIOR") == "spa":
215 redirect_url = get_url(
216 cv("POST_OAUTH_VERIFY_VIEW"), qparams=user.get_redirect_qparams()
217 )
218 else:
219 do_flash(*get_message("REAUTHENTICATION_SUCCESSFUL"))
220 redirect_url = get_post_action_redirect(
221 "SECURITY_POST_VERIFY_VIEW", dict(next=next_loc)
222 )
223 return redirect(redirect_url)
224
225 m, c = get_message("IDENTITY_NOT_REGISTERED", id=field_value)
226 if cv("REDIRECT_BEHAVIOR") == "spa":
227 return redirect(get_url(cv("VERIFY_ERROR_VIEW"), qparams={c: m}))
228 do_flash(m, c)
229 # Go back to verify - this is the same logic as in default_reauthn_handler
230 view = "us_verify" if cv("UNIFIED_SIGNIN") else "verify"
231 return redirect(url_for_security(view, next=next_loc))
232
233
234 class OAuthGlue:
235 """
236 Provide the necessary glue between the Flask-Security login process and
237 authlib oauth client code.
238
239 There are some builtin providers that can be used or not - configured via
240 :py:data:`SECURITY_OAUTH_BUILTIN_PROVIDERS`. Any other provider can be registered
241 using :py:meth:`register_provider_ext`.
242
243 See `Flask OAuth Client <https://docs.authlib.org/en/latest/client/flask.html>`_
244
245 .. versionadded:: 5.1.0
246
247 .. versionchanged:: 5.4.0
248 Added register_provider_ext which allows applications more control to
249 manage new providers (such as extended error handling).
250
251 .. versionchanged:: 5.8.0
252 Added endpoints for verify using OAuth.
253 """
254
255 def __init__(self, app: flask.Flask, oauthapp: OAuth | None = None):
256 if not oauthapp:
257 oauthapp = OAuth(app)
258 self.oauth = oauthapp
259 self.providers: dict[str, FsOAuthProvider] = dict()
260 if cv("OAUTH_BUILTIN_PROVIDERS", app=app):
261 for provider in cv("OAUTH_BUILTIN_PROVIDERS", app=app):
262 if provider == "github":
263 self.register_provider_ext(GitHubFsOauthProvider("github"))
264 elif provider == "google":
265 self.register_provider_ext(GoogleFsOauthProvider("google"))
266
267 def _create_blueprint(self, app: flask.Flask, bp: flask.Blueprint) -> None:
268 # Routes for each type of oauth provider
269 start_url = cv("OAUTH_START_URL", app=app)
270 response_url = cv("OAUTH_RESPONSE_URL", app=app)
271 bp.route(
272 start_url + slash_url_suffix(start_url, "<name>"),
273 methods=["POST"],
274 endpoint="oauthstart",
275 )(oauthstart)
276 bp.route(
277 response_url + slash_url_suffix(response_url, "<name>"),
278 methods=["GET"],
279 endpoint="oauthresponse",
280 )(oauthresponse)
281
282 if cv("FRESHNESS", app=app).total_seconds() >= 0:
283 verify_start_url = cv("OAUTH_VERIFY_START_URL", app=app)
284 bp.route(
285 verify_start_url + slash_url_suffix(verify_start_url, "<name>"),
286 methods=["POST"],
287 endpoint="oauth_verify_start",
288 )(oauth_verify_start)
289 verify_response_url = cv("OAUTH_VERIFY_RESPONSE_URL", app=app)
290 bp.route(
291 verify_response_url + slash_url_suffix(verify_response_url, "<name>"),
292 methods=["GET"],
293 endpoint="oauth_verify_response",
294 )(oauth_verify_response)
295
296 def get_redirect(
297 self, name: str, endpoint: str, **values: t.Any
298 ) -> ResponseValue | t.NoReturn:
299 authlib_provider = self.authlib_provider(name)
300 if not authlib_provider:
301 abort(404)
302 start_uri = url_for_security(endpoint, name=name, _external=True, **values)
303 redirect_url = authlib_provider.authorize_redirect(start_uri)
304 return redirect_url
305
306 @property
307 def provider_names(self) -> list[str]:
308 return list(self.providers.keys())
309
310 @property
311 def oauth_app(self):
312 return self.oauth
313
314 def authlib_provider(self, name):
315 return getattr(self.oauth, name, None)
316
317 def register_provider(
318 self,
319 name: str,
320 registration_info: dict[str, t.Any] | None,
321 fetch_identity_cb: OauthCbType,
322 ) -> None:
323 """Add a provider to the list.
324
325 :param name: Name of provider. This is used as part of the
326 :py:data:`SECURITY_OAUTH_START_URL`.
327 :param registration_info: Sent directly to authlib. Set this to None
328 if you already have registered the provider directly with OAuth.
329 :param fetch_identity_cb: This callback is called when the oauth
330 redirect happens. It must take the response from the provider and return
331 a tuple of <user_model_field_name, value> - which will be used
332 to look up the user in the datastore.
333
334 The provider can be registered with OAuth here or already be done by the
335 application. If you register directly with OAuth make sure to use
336 the same `name`.
337
338 .. deprecated:: 5.4.0
339 Use :py:meth:`register_provider_ext` instead.
340
341 """
342 pcls = FsOAuthProvider(
343 name,
344 registration_info=registration_info,
345 fetch_identity_cb=fetch_identity_cb,
346 )
347 self.register_provider_ext(pcls)
348
349 def register_provider_ext(self, provider: FsOAuthProvider) -> None:
350 """Register a provider via an instance of subclass.
351 This is the new way - to provide more control for applications
352
353 The authlib provider can be registered here (by calling Oauth)
354 or already be done by the application.
355 If you register directly with OAuth make sure to use
356 the same `name` when instantiating the class.
357 """
358 self.providers[provider.name] = provider
359 if not self.authlib_provider(provider.name):
360 self.oauth.register(provider.name, **provider.authlib_config())