udated code for testing
This commit is contained in:
parent
f3a096e8c1
commit
916828a05c
122
app/main.py
122
app/main.py
|
@ -24,32 +24,35 @@ secret_key = get_env_variable('APP_SECRET_KEY')
|
||||||
app.secret_key = secret_key
|
app.secret_key = secret_key
|
||||||
|
|
||||||
# https://www.inoreader.com/oauth2/auth
|
# https://www.inoreader.com/oauth2/auth
|
||||||
|
# Corrected URL for Inoreader OAuth
|
||||||
|
# AUTH_URL = 'https://www.inoreader.com/oauth2/auth'
|
||||||
AUTH_URL = 'https://github.com/login/oauth/authorize'
|
AUTH_URL = 'https://github.com/login/oauth/authorize'
|
||||||
|
#defining constant
|
||||||
|
# TOKEN_URL = 'https://www.inoreader.com/oauth2/token'
|
||||||
|
# USER_INFO_URL = 'https://www.inoreader.com/reader/api/0/user-info'
|
||||||
|
|
||||||
@app.route('/')
|
@app.route('/')
|
||||||
def home():
|
def home():
|
||||||
if is_logged_in():
|
if is_logged_in():
|
||||||
|
return main_menu()
|
||||||
|
else:
|
||||||
|
return generate_login_page()
|
||||||
|
|
||||||
|
def main_menu():
|
||||||
token_id = session.get('token_id')
|
token_id = session.get('token_id')
|
||||||
resp = requests.get(f'{database_url}/token/{token_id}')
|
token = get_token_from_database(token_id)
|
||||||
raise_for_status(resp)
|
|
||||||
resp_json = resp.json()
|
|
||||||
token = resp_json['token']
|
|
||||||
|
|
||||||
user_info = requests.get('https://api.github.com/user', headers={
|
user_info = get_user_info(token['access_token'])
|
||||||
'Authorization': f'Bearer {token.get("access_token")}'
|
last_synced, next_sync = format_sync_times(token)
|
||||||
}).json()
|
|
||||||
|
|
||||||
last_synced = datetime.fromtimestamp(token.get('updated_at')).strftime('%Y-%m-%d %H:%M:%S')
|
return render_template('home.html', user_login=user_info.get('userName'),
|
||||||
next_sync = datetime.fromtimestamp(token.get('updated_at') + token.get('expiration_seconds')).strftime('%Y-%m-%d %H:%M:%S')
|
user_email=user_info.get('userEmail'),
|
||||||
return render_template('home.html',
|
readwise_api_key=token.get('readwise_api_key', ''),
|
||||||
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)
|
last_synced=last_synced, next_sync=next_sync)
|
||||||
|
|
||||||
# Generate a CSRF protection string
|
def generate_login_page():
|
||||||
session['csrf_protection_string'] = os.urandom(16).hex()
|
session['csrf_protection_string'] = os.urandom(16).hex()
|
||||||
# Construct the OAuth URL with URL encoding
|
|
||||||
oauth_params = {
|
oauth_params = {
|
||||||
'client_id': client_id,
|
'client_id': client_id,
|
||||||
'redirect_uri': redirect_uri,
|
'redirect_uri': redirect_uri,
|
||||||
|
@ -57,16 +60,10 @@ def home():
|
||||||
'scope': optional_scopes,
|
'scope': optional_scopes,
|
||||||
'state': session['csrf_protection_string']
|
'state': session['csrf_protection_string']
|
||||||
}
|
}
|
||||||
# Use urlencode to properly encode the URL parameters
|
|
||||||
oauth_url = f'{AUTH_URL}?{urlencode(oauth_params)}'
|
oauth_url = f'{AUTH_URL}?{urlencode(oauth_params)}'
|
||||||
|
|
||||||
|
|
||||||
# Pass dynamic variables to the template
|
|
||||||
# return render_template('login.html',oauth_url)
|
|
||||||
return render_template('login.html', oauth_url=oauth_url)
|
return render_template('login.html', oauth_url=oauth_url)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@app.route('/oauth-redirect')
|
@app.route('/oauth-redirect')
|
||||||
def oauth_redirect():
|
def oauth_redirect():
|
||||||
auth_code = request.args.get('code')
|
auth_code = request.args.get('code')
|
||||||
|
@ -76,57 +73,28 @@ def oauth_redirect():
|
||||||
if csrf_token != session.get('csrf_protection_string'):
|
if csrf_token != session.get('csrf_protection_string'):
|
||||||
abort(403, 'Invalid CSRF token. Please try again.')
|
abort(403, 'Invalid CSRF token. Please try again.')
|
||||||
|
|
||||||
# Exchange authorization code for access and refresh tokens
|
# Exchange authorization code for access and refresh tokens using the Inoreader API
|
||||||
# response = requests.post(
|
|
||||||
# 'https://www.inoreader.com/oauth2/token',
|
|
||||||
# headers={
|
|
||||||
# 'Content-Type': 'application/x-www-form-urlencoded',
|
|
||||||
# },
|
|
||||||
# data={
|
|
||||||
# 'code': auth_code,
|
|
||||||
# 'redirect_uri': redirect_uri,
|
|
||||||
# 'client_id': client_id,
|
|
||||||
# 'client_secret': client_secret,
|
|
||||||
# 'scope': '',
|
|
||||||
# 'grant_type': 'authorization_code'
|
|
||||||
# }
|
|
||||||
# )
|
|
||||||
|
|
||||||
# TEST: Github OAuth - REMOVE
|
|
||||||
response = requests.post(
|
response = requests.post(
|
||||||
'https://github.com/login/oauth/access_token',
|
https://github.com/login/oauth/access_token',
|
||||||
headers={
|
headers={'Accept': 'application/json'},
|
||||||
'Accept': 'application/json'
|
|
||||||
},
|
|
||||||
data={
|
data={
|
||||||
'code': auth_code,
|
'code': auth_code,
|
||||||
'redirect_uri': redirect_uri,
|
'redirect_uri': redirect_uri,
|
||||||
'client_id': client_id,
|
'client_id': client_id,
|
||||||
'client_secret': client_secret,
|
'client_secret': client_secret,
|
||||||
|
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
raise_for_status(response)
|
raise_for_status(response)
|
||||||
|
|
||||||
token = response.json()
|
token = response.json()
|
||||||
|
|
||||||
# TEST: Github OAuth - REMOVE
|
# Fetch user information from Inoreader
|
||||||
token['refresh_token'] = 'N/A'
|
user_info = requests.get(https://api.github.com/user', headers={
|
||||||
token['expires_in'] = 3600
|
|
||||||
|
|
||||||
# REPLACE user API call with inoreader API call
|
|
||||||
# https://www.inoreader.com/reader/api/0/user-info
|
|
||||||
user_info = requests.get('https://api.github.com/user', headers={
|
|
||||||
'Authorization': f'Bearer {token.get("access_token")}'
|
'Authorization': f'Bearer {token.get("access_token")}'
|
||||||
}).json()
|
}).json()
|
||||||
|
|
||||||
# Save tokens for later use
|
# Save tokens for later use
|
||||||
token_id = save_token(
|
token_id = save_or_update_token(user_info.get('userEmail'), token)
|
||||||
user_info.get('email'), # for inoreader it's userEmail
|
|
||||||
token.get('access_token'),
|
|
||||||
token.get('refresh_token'),
|
|
||||||
token.get('expires_in')
|
|
||||||
)
|
|
||||||
|
|
||||||
set_session_token_id(token_id)
|
set_session_token_id(token_id)
|
||||||
return redirect(url_for('home'))
|
return redirect(url_for('home'))
|
||||||
|
@ -179,17 +147,19 @@ def is_logged_in():
|
||||||
|
|
||||||
return token.get('active', False)
|
return token.get('active', False)
|
||||||
|
|
||||||
def save_token(email, access_token, refresh_token, expiration_seconds):
|
def save_or_update_token(email, access_token, refresh_token, expiration_seconds):
|
||||||
# check if an active token with this email already exists
|
response = requests.get(f'{database_url}/token?email={email}')
|
||||||
token_by_email_resp = requests.get(f'{database_url}/token?email={email}')
|
raise_for_status(response)
|
||||||
raise_for_status(token_by_email_resp)
|
|
||||||
|
|
||||||
if token_by_email_resp.status_code != 200:
|
if response.status_code == 200:
|
||||||
|
update_login(response.json()['token']['id'], access_token, refresh_token, expiration_seconds)
|
||||||
|
else:
|
||||||
|
add_login(email, access_token, refresh_token, expiration_seconds)
|
||||||
|
|
||||||
|
def add_login(email, access_token, refresh_token, expiration_seconds):
|
||||||
response = requests.post(
|
response = requests.post(
|
||||||
f'{database_url}/token',
|
f'{database_url}/token',
|
||||||
headers={
|
headers={'Content-Type': 'application/json'},
|
||||||
'Content-Type': 'application/json'
|
|
||||||
},
|
|
||||||
json={
|
json={
|
||||||
'email': email,
|
'email': email,
|
||||||
'access_token': access_token,
|
'access_token': access_token,
|
||||||
|
@ -199,34 +169,30 @@ def save_token(email, access_token, refresh_token, expiration_seconds):
|
||||||
)
|
)
|
||||||
raise_for_status(response)
|
raise_for_status(response)
|
||||||
return response.json().get('id')
|
return response.json().get('id')
|
||||||
else:
|
|
||||||
token_by_email_resp_json = token_by_email_resp.json()
|
def update_login(token_id, access_token, refresh_token, expiration_seconds):
|
||||||
token = token_by_email_resp_json['token']
|
|
||||||
response = requests.put(
|
response = requests.put(
|
||||||
f'{database_url}/token/{token["id"]}',
|
f'{database_url}/token/{token_id}',
|
||||||
headers={
|
headers={'Content-Type': 'application/json'},
|
||||||
'Content-Type': 'application/json'
|
|
||||||
},
|
|
||||||
json={
|
json={
|
||||||
'access_token': access_token,
|
'access_token': access_token,
|
||||||
'refresh_token': refresh_token,
|
'refresh_token': refresh_token,
|
||||||
'expiration_seconds': expiration_seconds,
|
'expiration_seconds': expiration_seconds
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
raise_for_status(response)
|
raise_for_status(response)
|
||||||
return token['id']
|
return token_id
|
||||||
|
|
||||||
def set_session_token_id(token_id):
|
def set_session_token_id(token_id):
|
||||||
session['token_id'] = token_id
|
session['token_id'] = token_id
|
||||||
|
|
||||||
def raise_for_status(response):
|
def raise_for_status(response):
|
||||||
if response.status_code not in range(200, 300):
|
if response.status_code not in range(200, 300):
|
||||||
msg = None
|
|
||||||
try:
|
try:
|
||||||
msg = response.json().get('error', '')
|
msg = response.json().get('error', 'No error message provided')
|
||||||
except:
|
except Exception:
|
||||||
msg = response.text
|
msg = response.text
|
||||||
raise Exception(f'HTTPError: {response.status_code} \n Message: {msg}')
|
raise Exception(f'HTTPError: {response.status_code} - Message: {msg}')
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
app.run(host='0.0.0.0', debug=True, port=5000)
|
app.run(host='0.0.0.0', debug=True, port=5000)
|
Loading…
Reference in New Issue
Block a user