Skip to content

Commit

Permalink
feat: Add automatic token refresh (#46)
Browse files Browse the repository at this point in the history
  • Loading branch information
thinkJD authored Jun 14, 2023
1 parent 4cd7e23 commit 8232fd2
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 53 deletions.
28 changes: 17 additions & 11 deletions bibli_o_mat/credential_helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,29 +19,35 @@ def get_token(self, card_number: str, password: str, lib_id: int = 8726):
print(f'Other error occurred: {err}')
return r.json()['token']

def refresh_token(self, card_number: str):
def refresh_token(self, user_id: str):
cred = Query()
result = self.db.search(cred.id == card_number)
token = self.get_token(card_number=card_number,
result = self.db.search(cred.id == user_id)
token = self.get_token(card_number=user_id,
password=result[0]['password'])
self.db.update({'token': token, 'last_refresh': str(
time.time())}, cred.id == card_number)
time.time())}, cred.id == user_id)

def get_user_id_by_name(self, name: str):
cred = Query()
result = self.db.search(cred.name == name)
if result:
return result[0]['id']

def get_user_list(self):
cred = Query()
result = self.db.search(cred.id.exists())
return result

def get_credentials(self, user_id: str = None):
cred = Query()
if user_id:
# Return credentials for one id
result = self.db.search(cred.id == user_id)
return result[0]
else:
# Return all credentials
return self.db.search(cred.id.exists())
user = self.db.search(cred.id == user_id)[0]
# Refresh token if it is older than 14 days or empty
if ((time.time() - float(user['last_refresh']) > 14 * 24 * 60 * 60) or
user['token'] == ''):
print('refreshing access token')
self.refresh_token(user_id)
user = self.db.search(cred.id == user_id)[0]
return user

def add_user(self, name, mail, id, password):
token = self.get_token(card_number=id, password=password)
Expand Down
2 changes: 1 addition & 1 deletion bibli_o_mat/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ def list_users():
"""list all bibli-o-mat users.
"""
table = Table('Name', 'Email', 'ID')
for user in ch.get_credentials():
for user in ch.get_user_list():
table.add_row(user['name'], user['mail'], user['id'])
console.print(table)

Expand Down
61 changes: 20 additions & 41 deletions poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 8232fd2

Please sign in to comment.