A token backend based on files on the filesystem
| 333 | |
| 334 | |
| 335 | class FileSystemTokenBackend(BaseTokenBackend): |
| 336 | """ A token backend based on files on the filesystem """ |
| 337 | |
| 338 | def __init__(self, token_path=None, token_filename=None): |
| 339 | """ |
| 340 | Init Backend |
| 341 | :param str or Path token_path: the path where to store the token |
| 342 | :param str token_filename: the name of the token file |
| 343 | """ |
| 344 | super().__init__() |
| 345 | if not isinstance(token_path, Path): |
| 346 | token_path = Path(token_path) if token_path else Path() |
| 347 | |
| 348 | if token_path.is_file(): |
| 349 | self.token_path = token_path |
| 350 | else: |
| 351 | token_filename = token_filename or 'o365_token.txt' |
| 352 | self.token_path = token_path / token_filename |
| 353 | |
| 354 | def __repr__(self): |
| 355 | return str(self.token_path) |
| 356 | |
| 357 | def load_token(self) -> bool: |
| 358 | """ |
| 359 | Retrieves the token from the File System and stores it in the cache |
| 360 | :return bool: Success / Failure |
| 361 | """ |
| 362 | if self.token_path.exists(): |
| 363 | with self.token_path.open('r') as token_file: |
| 364 | token_dict = self.deserialize(token_file.read()) |
| 365 | if 'access_token' in token_dict: |
| 366 | raise ValueError('The token you are trying to load is not valid anymore. ' |
| 367 | 'Please delete the token and proceed to authenticate again.') |
| 368 | self._cache = token_dict |
| 369 | log.debug(f'Token loaded from {self.token_path}') |
| 370 | return True |
| 371 | return False |
| 372 | |
| 373 | def save_token(self, force=False) -> bool: |
| 374 | """ |
| 375 | Saves the token cache dict in the specified file |
| 376 | Will create the folder if it doesn't exist |
| 377 | :param bool force: Force save even when state has not changed |
| 378 | :return bool: Success / Failure |
| 379 | """ |
| 380 | if not self._cache: |
| 381 | return False |
| 382 | |
| 383 | if force is False and self._has_state_changed is False: |
| 384 | return True |
| 385 | |
| 386 | try: |
| 387 | if not self.token_path.parent.exists(): |
| 388 | self.token_path.parent.mkdir(parents=True) |
| 389 | except Exception as e: |
| 390 | log.error('Token could not be saved: {}'.format(str(e))) |
| 391 | return False |
| 392 |