From 15200782f33f0f1f64d6686a8c00c79165257d0c Mon Sep 17 00:00:00 2001 From: Alexander_Kabui Date: Wed, 18 Sep 2024 12:12:06 +0300 Subject: feat(auth): implement redirect to login page and save current endpoint to session * Redirect users to the login page when authentication is required. * Save the current endpoint in the session for post-login redirection. --- gn2/wqflask/oauth2/checks.py | 21 ++++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/gn2/wqflask/oauth2/checks.py b/gn2/wqflask/oauth2/checks.py index 944760ad..6e90e7a3 100644 --- a/gn2/wqflask/oauth2/checks.py +++ b/gn2/wqflask/oauth2/checks.py @@ -2,7 +2,7 @@ from functools import wraps from urllib.parse import urljoin -from flask import flash, request, redirect +from flask import flash, request, redirect, url_for from authlib.integrations.requests_client import OAuth2Session from . import session @@ -20,10 +20,21 @@ def require_oauth2(func): @wraps(func) def __token_valid__(*args, **kwargs): """Check that the user is logged in and their token is valid.""" - def __clear_session__(_no_token): session.clear_session_info() - # redirect to the login page + flash("You need to be logged in.", "alert-warning") + return redirect("/") + + def __redirect_to_login__(_token): + """ + Save the current user request to session then + redirect to the login page. + """ + if request.method == "GET": + redirect_url = url_for(request.endpoint, **request.args) + else: + redirect_url = "/" + session.set_redirect_url(redirect_url, **request.args) return redirect(authserver_authorise_uri()) def __with_token__(token): @@ -33,9 +44,9 @@ def require_oauth2(func): if not user_details.get("error", False): return func(*args, **kwargs) - return __clear_session__(token) + return __redirect_to_login__(token) - return session.user_token().either(__clear_session__, __with_token__) + return session.user_token().either(__redirect_to_login__, __with_token__) return __token_valid__ -- cgit v1.2.3