mirror of
https://github.com/derrod/legendary.git
synced 2024-12-22 01:45:28 +00:00
[api/core] Overhaul session resume and verify session validity
This commit is contained in:
parent
5eb51dfd11
commit
0031e5908a
|
@ -33,8 +33,19 @@ class EPCAPI:
|
||||||
self.user = None
|
self.user = None
|
||||||
|
|
||||||
def resume_session(self, session):
|
def resume_session(self, session):
|
||||||
|
self.session.headers['Authorization'] = f'bearer {session["access_token"]}'
|
||||||
|
r = self.session.get(f'https://{self._oauth_host}/account/api/oauth/verify')
|
||||||
|
if r.status_code >= 500:
|
||||||
|
r.raise_for_status()
|
||||||
|
|
||||||
|
j = r.json()
|
||||||
|
if 'errorMessage' in j:
|
||||||
|
self.log.warning(f'Login to EGS API failed with errorCode: {j["errorCode"]}')
|
||||||
|
raise InvalidCredentialsError(j['errorCode'])
|
||||||
|
|
||||||
|
# update other data
|
||||||
|
session.update(j)
|
||||||
self.user = session
|
self.user = session
|
||||||
self.session.headers['Authorization'] = f'bearer {self.user["access_token"]}'
|
|
||||||
return self.user
|
return self.user
|
||||||
|
|
||||||
def start_session(self, refresh_token: str = None, exchange_token: str = None) -> dict:
|
def start_session(self, refresh_token: str = None, exchange_token: str = None) -> dict:
|
||||||
|
|
|
@ -93,15 +93,22 @@ class LegendaryCore:
|
||||||
raise ValueError('No saved credentials')
|
raise ValueError('No saved credentials')
|
||||||
|
|
||||||
if self.lgd.userdata['expires_at']:
|
if self.lgd.userdata['expires_at']:
|
||||||
dt_old = datetime.fromisoformat(self.lgd.userdata['expires_at'][:-1])
|
dt_exp = datetime.fromisoformat(self.lgd.userdata['expires_at'][:-1])
|
||||||
dt_now = datetime.utcnow()
|
dt_now = datetime.utcnow()
|
||||||
td = dt_now - dt_old
|
td = dt_now - dt_exp
|
||||||
|
|
||||||
# if session still has at least 10 minutes left we can re-use it.
|
# if session still has at least 10 minutes left we can re-use it.
|
||||||
if dt_old > dt_now and td.total_seconds() < (self.lgd.userdata['expires_in'] - 600):
|
if dt_exp > dt_now and abs(td.total_seconds()) > 600:
|
||||||
self.log.debug('Reusing existing login session...')
|
self.log.debug('Trying to re-use existing login session...')
|
||||||
self.egs.resume_session(self.lgd.userdata)
|
try:
|
||||||
return True
|
self.egs.resume_session(self.lgd.userdata)
|
||||||
|
return True
|
||||||
|
except InvalidCredentialsError as e:
|
||||||
|
self.log.warning(f'Resuming failed due to invalid credentials: {e!r}')
|
||||||
|
except Exception as e:
|
||||||
|
self.log.warning(f'Resuming failed for unknown reason: {e!r}')
|
||||||
|
# If verify fails just continue the normal authentication process
|
||||||
|
self.log.info('Falling back to using refresh token...')
|
||||||
|
|
||||||
try:
|
try:
|
||||||
userdata = self.egs.start_session(self.lgd.userdata['refresh_token'])
|
userdata = self.egs.start_session(self.lgd.userdata['refresh_token'])
|
||||||
|
|
Loading…
Reference in a new issue