From c1b216dd115932eb5523f2a71cda15ffe09d1cb4 Mon Sep 17 00:00:00 2001 From: Swapnil Date: Tue, 30 Jan 2024 22:17:08 +0530 Subject: [PATCH] app: fix logic to save/create token --- app/main.py | 52 ++++++++++++++++++++++++++++++++++++---------------- 1 file changed, 36 insertions(+), 16 deletions(-) diff --git a/app/main.py b/app/main.py index 808fa0a..3b0ff7a 100644 --- a/app/main.py +++ b/app/main.py @@ -36,8 +36,8 @@ def home(): 'Authorization': f'Bearer {token.get("access_token")}' }).json() - last_synced = datetime.fromtimestamp(token.get('timestamp')).strftime('%Y-%m-%d %H:%M:%S') - next_sync = datetime.fromtimestamp(token.get('timestamp') + token.get('expiration_seconds')).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_info=user_info, readwise_api_key=token.get('readwise_api_key', ''), last_synced=last_synced, next_sync=next_sync) @@ -161,21 +161,41 @@ def is_logged_in(): return token.get('active', False) def save_token(email, access_token, refresh_token, expiration_seconds): - response = requests.post( - f'{database_url}/token', - headers={ - 'Content-Type': 'application/json' - }, - json={ - 'email': email, - 'access_token': access_token, - 'refresh_token': refresh_token, - 'expiration_seconds': expiration_seconds - } - ) - raise_for_status(response) + # check if an active token with this email already exists + token_by_email_resp = requests.get(f'{database_url}/token?email={email}') + raise_for_status(token_by_email_resp) - return response.json().get('id') + if token_by_email_resp.status_code != 200: + response = requests.post( + f'{database_url}/token', + headers={ + 'Content-Type': 'application/json' + }, + json={ + 'email': email, + 'access_token': access_token, + 'refresh_token': refresh_token, + 'expiration_seconds': expiration_seconds + } + ) + raise_for_status(response) + return response.json().get('id') + else: + token_by_email_resp_json = token_by_email_resp.json() + token = token_by_email_resp_json['token'] + response = requests.put( + f'{database_url}/token/{token["id"]}', + headers={ + 'Content-Type': 'application/json' + }, + json={ + 'access_token': access_token, + 'refresh_token': refresh_token, + 'expiration_seconds': expiration_seconds, + } + ) + raise_for_status(response) + return token['id'] def set_session_token_id(token_id): session['token_id'] = token_id