app: fix logic to save/create token

This commit is contained in:
Swapnil 2024-01-30 22:17:08 +05:30
parent 0c1e18cad9
commit c1b216dd11
Signed by: swapnil
GPG Key ID: 58029C48BB100574

View File

@ -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,6 +161,11 @@ def is_logged_in():
return token.get('active', False)
def save_token(email, access_token, refresh_token, expiration_seconds):
# 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)
if token_by_email_resp.status_code != 200:
response = requests.post(
f'{database_url}/token',
headers={
@ -174,8 +179,23 @@ def save_token(email, access_token, refresh_token, 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