1313from urllib .parse import quote_plus , urlencode
1414
1515from authlib .integrations .flask_client import OAuth
16- from flask import Blueprint , Response , current_app , redirect , session , url_for
16+ from flask import Blueprint , Response , current_app , redirect , request , session , url_for
1717from werkzeug .wrappers import Response as WerkzeugResponse
1818
1919auth_bp = Blueprint ("auth" , __name__ )
@@ -118,13 +118,16 @@ def requires_auth(f: F) -> F:
118118
119119 If Auth0 is not configured, the route is accessible without authentication.
120120 Redirects to login page if not authenticated.
121+ Saves the original URL to redirect back after login.
121122 """
122123
123124 @wraps (f )
124125 def decorated (* args : Any , ** kwargs : Any ) -> Any :
125126 auth_error = _check_auth ()
126127 if auth_error :
127- logger .info ("No user in session, redirecting to login" )
128+ # Save the original URL to redirect back after login
129+ session ["next_url" ] = request .url
130+ logger .info (f"No user in session, redirecting to login. Will return to: { request .url } " )
128131 return redirect (url_for ("auth.login" ))
129132
130133 return f (* args , ** kwargs )
@@ -175,8 +178,6 @@ def login() -> AnyResponse:
175178@auth_bp .route ("/callback" )
176179def callback () -> AnyResponse :
177180 """Handle Auth0 callback after login."""
178- from flask import request
179-
180181 logger .info (f"Auth0 callback received. Args: { request .args } " )
181182
182183 oauth = current_app .config .get ("OAUTH" )
@@ -244,6 +245,9 @@ def callback() -> AnyResponse:
244245 logger .info (f"Auth0 callback successful for user: { userinfo .get ('email' )} " )
245246 logger .info (f"Auth0 userinfo: { userinfo } " )
246247
248+ # Get the original URL before clearing it from session
249+ next_url = session .pop ("next_url" , "/" )
250+
247251 # Store only essential user info to avoid cookie size limits
248252 # Full token can be 4KB+ which exceeds browser cookie limits
249253 session ["user" ] = {
@@ -254,7 +258,8 @@ def callback() -> AnyResponse:
254258 }
255259 session .modified = True
256260 logger .info (f"Session after setting user - keys: { list (session .keys ())} " )
257- return redirect ("/" )
261+ logger .info (f"Redirecting to: { next_url } " )
262+ return redirect (next_url )
258263 except Exception as e :
259264 logger .exception (f"Auth0 callback failed: { e } " )
260265 return Response (
0 commit comments