Skip to content

Commit

Permalink
Fix auth token saving (#753)
Browse files Browse the repository at this point in the history
resolve a bug in file saving 

The environment variable `XDG_CONFIG_HOME` contains a directory not a
file path. So adding a file name in front of directory path to get a
writable location
  • Loading branch information
ZohebShaikh authored Dec 12, 2024
1 parent 211bb49 commit 2d77d61
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 12 deletions.
16 changes: 8 additions & 8 deletions src/blueapi/service/authentication.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
from blueapi.config import OIDCConfig
from blueapi.service.model import Cache

BLUEAPI_CACHE_LOCATION = "~/.cache/blueapi_cache"
DEFAULT_CAHCE_DIR = "~/.cache/"
SCOPES = "openid offline_access"


Expand All @@ -33,7 +33,9 @@ def delete_cache(self) -> None: ...

class SessionCacheManager(CacheManager):
def __init__(self, token_path: Path | None) -> None:
self._token_path: Path = token_path if token_path else self._get_xdg_cache_dir()
self._token_path: Path = (
token_path if token_path else self._default_token_cache_path()
)

@cached_property
def _file_path(self) -> str:
Expand All @@ -54,14 +56,12 @@ def load_cache(self) -> Cache:
def delete_cache(self) -> None:
Path(self._file_path).unlink(missing_ok=True)

def _get_xdg_cache_dir(self) -> Path:
def _default_token_cache_path(self) -> Path:
"""
Return the XDG cache directory.
Return the default cache file path.
"""
cache_dir = os.environ.get("XDG_CACHE_HOME")
if not cache_dir:
cache_dir = os.path.expanduser(BLUEAPI_CACHE_LOCATION)
return Path(cache_dir)
cache_path = os.environ.get("XDG_CACHE_HOME", DEFAULT_CAHCE_DIR)
return Path(cache_path).expanduser() / "blueapi_cache"


class SessionManager:
Expand Down
13 changes: 9 additions & 4 deletions tests/unit_tests/service/test_authentication.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,7 @@

from blueapi.config import OIDCConfig
from blueapi.service import main
from blueapi.service.authentication import (
SessionCacheManager,
SessionManager,
)
from blueapi.service.authentication import SessionCacheManager, SessionManager


@pytest.fixture
Expand Down Expand Up @@ -132,3 +129,11 @@ def test_processes_valid_token(
):
inner = main.verify_access_token(oidc_config)
inner(access_token=valid_token_with_jwt["access_token"])


def test_session_cache_manager_returns_writable_file_path(tmp_path):
os.environ["XDG_CACHE_HOME"] = str(tmp_path)
cache = SessionCacheManager(token_path=None)
Path(cache._file_path).touch()
assert os.path.isfile(cache._file_path)
assert cache._file_path == f"{tmp_path}/blueapi_cache"

0 comments on commit 2d77d61

Please sign in to comment.