app: fix logic to save/create token

This commit is contained in:
Swapnil 2024-01-30 22:17:08 +05:30
parent 48564e1461
commit a20231769c
Signed by: swapnil
GPG Key ID: 58029C48BB100574
1 changed files with 36 additions and 16 deletions

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,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