From a43479276b651b08fb0556c7081ca17d1482d9ce Mon Sep 17 00:00:00 2001 From: Swapnil Date: Wed, 7 Feb 2024 12:43:26 +0530 Subject: [PATCH] fixes: constant AUTH_URL & better csrf handeling --- app/main.py | 14 +++++++------- app/templates/login.html | 3 +-- 2 files changed, 8 insertions(+), 9 deletions(-) diff --git a/app/main.py b/app/main.py index 05e7c37..505d265 100644 --- a/app/main.py +++ b/app/main.py @@ -22,7 +22,8 @@ secret_key = get_env_variable('APP_SECRET_KEY') # Set secret key to enable sessions app.secret_key = secret_key -csrf_protection_string = None +# https://www.inoreader.com/oauth2/auth +AUTH_URL = 'https://github.com/login/oauth/authorize' @app.route('/') def home(): @@ -44,12 +45,11 @@ def home(): last_synced=last_synced, next_sync=next_sync) # Generate a CSRF protection string - global csrf_protection_string - csrf_protection_string = os.urandom(16).hex() + session['csrf_protection_string'] = os.urandom(16).hex() # Pass dynamic variables to the template - return render_template('login.html', client_id=client_id, redirect_uri=redirect_uri, - optional_scopes=optional_scopes, csrf_protection_string=csrf_protection_string) + return render_template('login.html', auth_url=AUTH_URL, client_id=client_id, redirect_uri=redirect_uri, + optional_scopes=optional_scopes, csrf_protection_string=session.get('csrf_protection_string')) @app.route('/oauth-redirect') def oauth_redirect(): @@ -57,8 +57,8 @@ def oauth_redirect(): csrf_token = request.args.get('state') # Verify the CSRF protection string - if csrf_token != csrf_protection_string: - abort(400, 'Invalid CSRF token. Please try again.') + if csrf_token != session.get('csrf_protection_string'): + abort(403, 'Invalid CSRF token. Please try again.') # Exchange authorization code for access and refresh tokens # response = requests.post( diff --git a/app/templates/login.html b/app/templates/login.html index 5ed3901..e5f8e26 100644 --- a/app/templates/login.html +++ b/app/templates/login.html @@ -15,8 +15,7 @@ var encodedOptionalScopes = encodeURIComponent('{{ optional_scopes }}'); // Construct the URL using Jinja variables - // var oauthUrl = `https://www.inoreader.com/oauth2/auth?client_id={{ client_id }}&redirect_uri=${encodedRedirectUri}&response_type=code&scope=${encodedOptionalScopes}&state={{ csrf_protection_string }}`; - var oauthUrl = `https://github.com/login/oauth/authorize?client_id={{ client_id }}&redirect_uri=${encodedRedirectUri}&response_type=code&scope=${encodedOptionalScopes}&state={{ csrf_protection_string }}`; + var oauthUrl = `{{ auth_url }}?client_id={{ client_id }}&redirect_uri=${encodedRedirectUri}&response_type=code&scope=${encodedOptionalScopes}&state={{ csrf_protection_string }}`; // Redirect to the constructed URL window.location.href = oauthUrl;