From af486e5b48f68159e71d488c29ea2304646592d5 Mon Sep 17 00:00:00 2001 From: Shailaja kumari Date: Wed, 14 Feb 2024 13:30:23 +0530 Subject: [PATCH] created oauth url --- app/main.py | 61 ++++++++++++++++++++++++----------------------------- 1 file changed, 27 insertions(+), 34 deletions(-) diff --git a/app/main.py b/app/main.py index 6a8b1a8..1471104 100644 --- a/app/main.py +++ b/app/main.py @@ -2,10 +2,9 @@ import os from flask import Flask, render_template, request, redirect, abort, url_for, session import requests from datetime import datetime -from urllib.parse import quote_plus, urlencode +from urllib.parse import urlencode def get_env_variable(var_name): - """Get environment variable or raise an exception.""" value = os.environ.get(var_name) if not value: raise ValueError(f"Missing required environment variable: {var_name}") @@ -13,7 +12,7 @@ def get_env_variable(var_name): app = Flask(__name__) -# Reading environment variables +# Read environment variables outside the route function client_id = get_env_variable('CLIENT_ID') client_secret = get_env_variable('CLIENT_SECRET') redirect_uri = get_env_variable('REDIRECT_URI') @@ -24,50 +23,44 @@ secret_key = get_env_variable('APP_SECRET_KEY') # Set secret key to enable sessions app.secret_key = secret_key -# OAuth URL +# https://www.inoreader.com/oauth2/auth AUTH_URL = 'https://github.com/login/oauth/authorize' @app.route('/') def home(): - """Home route that either shows user info or initiates OAuth flow.""" - if 'token_id' in session: - try: - # Attempt to fetch user info using the stored access token - token_id = session['token_id'] - resp = requests.get(f'{database_url}/token/{token_id}') - resp.raise_for_status() # This will raise an exception for HTTP errors - token = resp.json()['token'] + if is_logged_in(): + token_id = session.get('token_id') + resp = requests.get(f'{database_url}/token/{token_id}') + raise_for_status(resp) + resp_json = resp.json() + token = resp_json['token'] - # Use the access token to fetch user info from GitHub - user_info_resp = requests.get('https://api.github.com/user', headers={'Authorization': f'token {token["access_token"]}'}) - user_info_resp.raise_for_status() - user_info = user_info_resp.json() + user_info = requests.get('https://api.github.com/user', headers={ + 'Authorization': f'Bearer {token.get("access_token")}' + }).json() - # Prepare user info and token details for rendering - last_synced = datetime.fromtimestamp(token['updated_at']).strftime('%Y-%m-%d %H:%M:%S') - next_sync = datetime.fromtimestamp(token['updated_at'] + token['expires_in']).strftime('%Y-%m-%d %H:%M:%S') + last_synced = datetime.fromtimestamp(token.get('updated_at')).strftime('%Y-%m-%d %H:%M:%S') + next_sync = datetime.fromtimestamp(token.get('updated_at') + token.get('expiration_seconds')).strftime('%Y-%m-%d %H:%M:%S') + return render_template('home.html', user_login=user_info.get('login'), user_email=user_info.get('email'), # for inoreader it's userName and userEmail + readwise_api_key=token.get('readwise_api_key') or '', + last_synced=last_synced, next_sync=next_sync) - return render_template('home.html', user_info=user_info, last_synced=last_synced, next_sync=next_sync) - except Exception as e: - # Handle errors (e.g., token expired) by clearing the session and redirecting to login - session.pop('token_id', None) - return redirect(url_for('home')) - - else: - # User not logged in; start OAuth flow - session['csrf_protection_string'] = os.urandom(16).hex() # CSRF protection - - # Construct OAuth URL - params = { + # Generate a CSRF protection string + session['csrf_protection_string'] = os.urandom(16).hex() + # Construct the OAuth URL with URL encoding + oauth_params = { 'client_id': client_id, 'redirect_uri': redirect_uri, 'response_type': 'code', 'scope': optional_scopes, 'state': session['csrf_protection_string'] - } - oauth_url = f'{AUTH_URL}?{urlencode(params)}' + } + # Use urlencode to properly encode the URL parameters + oauth_url = f'{AUTH_URL}?{urlencode(oauth_params)}' - return redirect(oauth_url) + + # Pass dynamic variables to the template + return render_template('login.html',oauth_url ) @app.route('/oauth-redirect')