Skip to content

Commit

Permalink
Merge pull request googleapis#356 from riptusk331/file_lock
Browse files Browse the repository at this point in the history
Atomic file operations
  • Loading branch information
Alejandro Casanovas authored Nov 11, 2019
2 parents cd46e6c + 07027e8 commit 66f1399
Showing 1 changed file with 29 additions and 6 deletions.
35 changes: 29 additions & 6 deletions O365/utils/token.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
log = logging.getLogger(__name__)


EXPIRES_ON_THRESHOLD = 2 * 60 # 2 minutes
EXPIRES_ON_THRESHOLD = 1 * 60 # 1 minute


class Token(dict):
Expand Down Expand Up @@ -35,15 +35,33 @@ def expiration_datetime(self):
Returns the expiration datetime
:return datetime: The datetime this token expires
"""
expires_at = self.get('expires_at')
if expires_at is None:
# consider it is expired
return dt.datetime.now() - dt.timedelta(seconds=10)
expires_on = dt.datetime.fromtimestamp(expires_at) - dt.timedelta(seconds=EXPIRES_ON_THRESHOLD)
access_expires_at = self.access_expiration_datetime
expires_on = access_expires_at - dt.timedelta(seconds=EXPIRES_ON_THRESHOLD)
if self.is_long_lived:
expires_on = expires_on + dt.timedelta(days=90)
return expires_on

@property
def access_expiration_datetime(self):
"""
Returns the token's access expiration datetime
:return datetime: The datetime the token's access expires
"""
expires_at = self.get('expires_at')
if expires_at:
return dt.datetime.fromtimestamp(expires_at)
else:
# consider the token expired, add 10 second buffer to current dt
return dt.datetime.now() - dt.timedelta(seconds=10)

@property
def is_access_expired(self):
"""
Returns whether or not the token's access is expired.
:return bool: True if the token's access is expired, False otherwise
"""
return dt.datetime.now() > self.access_expiration_datetime


class BaseTokenBackend(ABC):
""" A base token storage class """
Expand Down Expand Up @@ -154,6 +172,9 @@ def __init__(self, token_path=None, token_filename=None):
else:
token_filename = token_filename or 'o365_token.txt'
self.token_path = token_path / token_filename

# is this backend waiting on the filesystem
self.fs_wait = False

def __repr__(self):
return str(self.token_path)
Expand Down Expand Up @@ -207,6 +228,8 @@ def check_token(self):
"""
return self.token_path.exists()

def should_refresh_token(self):
return not self.fs_wait

class FirestoreBackend(BaseTokenBackend):
""" A Google Firestore database backend to store tokens """
Expand Down

0 comments on commit 66f1399

Please sign in to comment.