introduce mutex to avoid multiple token refresh when using threads.
This commit is contained in:
parent
8ee220137f
commit
35defa39a6
@ -4,12 +4,16 @@ from mdrsclient.exceptions import UnauthorizedException
|
||||
|
||||
|
||||
def token_check(connection: MDRSConnection) -> None:
|
||||
if connection.token is not None:
|
||||
if connection.token.is_refresh_required:
|
||||
user_api = UserApi(connection)
|
||||
try:
|
||||
connection.token = user_api.refresh(connection.token)
|
||||
except UnauthorizedException:
|
||||
try:
|
||||
connection.lock.acquire()
|
||||
if connection.token is not None:
|
||||
if connection.token.is_refresh_required:
|
||||
user_api = UserApi(connection)
|
||||
try:
|
||||
connection.token = user_api.refresh(connection.token)
|
||||
except UnauthorizedException:
|
||||
connection.logout()
|
||||
elif connection.token.is_expired:
|
||||
connection.logout()
|
||||
elif connection.token.is_expired:
|
||||
connection.logout()
|
||||
finally:
|
||||
connection.lock.release()
|
||||
|
@ -1,3 +1,5 @@
|
||||
import threading
|
||||
|
||||
import requests
|
||||
|
||||
from mdrsclient.cache import CacheFile
|
||||
@ -8,12 +10,14 @@ from mdrsclient.models import Laboratories, Token, User
|
||||
class MDRSConnection:
|
||||
url: str
|
||||
session: requests.Session
|
||||
lock: threading.Lock
|
||||
__cache: CacheFile
|
||||
|
||||
def __init__(self, remote: str, url: str) -> None:
|
||||
super().__init__()
|
||||
self.url = url
|
||||
self.session = requests.Session()
|
||||
self.lock = threading.Lock()
|
||||
self.__cache = CacheFile(remote)
|
||||
self.__prepare_headers()
|
||||
|
||||
|
@ -26,16 +26,16 @@ class Token:
|
||||
|
||||
@property
|
||||
def is_expired(self) -> bool:
|
||||
now = int(time.time()) + 10
|
||||
now = int(time.time())
|
||||
refresh_decoded = self.__decode(self.refresh)
|
||||
return now > refresh_decoded.exp
|
||||
return (now - 10) > refresh_decoded.exp
|
||||
|
||||
@property
|
||||
def is_refresh_required(self) -> bool:
|
||||
now = int(time.time()) + 10
|
||||
now = int(time.time())
|
||||
access_decoded = self.__decode(self.access)
|
||||
refresh_decoded = self.__decode(self.refresh)
|
||||
return now > access_decoded.exp and now < refresh_decoded.exp
|
||||
return (now + 10) > access_decoded.exp and (now - 10) < refresh_decoded.exp
|
||||
|
||||
def __decode(self, token: str) -> DecodedJWT:
|
||||
data = jwt.decode(token, options={"verify_signature": False})
|
||||
|
Loading…
Reference in New Issue
Block a user