Skip to content

Commit

Permalink
Merge pull request #99 from jjjermiah/19-authpy-logout-functionality
Browse files Browse the repository at this point in the history
feat: Implement logout functionality and add context manager support
  • Loading branch information
jjjermiah committed Feb 5, 2024
2 parents 79f7eda + 67968fc commit 528d1a7
Show file tree
Hide file tree
Showing 5 changed files with 91 additions and 4 deletions.
56 changes: 53 additions & 3 deletions src/nbiatoolkit/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,8 @@ def __init__(
self.client_id = client_id

self._fernet_key: bytes = Fernet.generate_key()
self.username: str
self.password: str
self.username, self.password = encrypt_credentials(key=self.fernet_key, username=username, password=password)

if isinstance(base_url, NBIA_ENDPOINTS):
Expand All @@ -127,8 +129,14 @@ def __init__(
def fernet_key(self) -> bytes:
return self._fernet_key

def is_logged_out(self) -> bool:
return (self._access_token is "" and self.username == "" and self.password == "" and self.client_id == "" and self.base_url == "")

@property
def access_token(self) -> str | None:
if self.is_logged_out():
return None

# Check if access token is not set or it's expired
if not self._access_token or self.is_token_expired():
self.refresh_token_or_request_new()
Expand Down Expand Up @@ -229,9 +237,51 @@ def refresh_expiration_time(self):
def token_scope(self):
return self.scope

def __repr__(self):
return f"OAuth2(username={self.username}, client_id={self.client_id})"
def __repr__(self) -> Union[str, None]:
if self.username:
return f"OAuth2(username={self.username}, client_id={self.client_id})"
else:
return ""

def __str__(self):
return f"OAuth2(username={self.username}, client_id={self.client_id})"
if self.username:
return f"OAuth2(username={self.username}, client_id={self.client_id})"
else:
return ""


def logout(self) -> None:
"""
Logs out the user and revokes the access token.
This method sends a request to the NBIA API to revoke the access token
and logs out the user.
Notes
-----
This method is not yet implemented in the NBIA API.
"""
if not self.access_token:
return None

query_url = NBIA_ENDPOINTS.LOGOUT_URL.value
response = requests.get(query_url, headers=self.api_headers)
response.raise_for_status()

# set the entire object to None
self.__dict__.clear()
self.username = ""
self.password = ""
self.client_id = ""
self.base_url = ""
self._access_token = ""
self.expiry_time = None
self.refresh_expiry = None
self.refresh_token = ""
self.scope = None
self._fernet_key = b''
self = None
return None



10 changes: 10 additions & 0 deletions src/nbiatoolkit/nbia.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,16 @@ def __init__(
raise e
self._base_url : NBIA_ENDPOINTS = NBIA_ENDPOINTS.BASE_URL

def __enter__(self):
return self

def __exit__(self, exc_type, exc_value, traceback) -> None:
self._oauth2_client.logout()

@property
def OAuth_client(self) -> OAuth2:
return self._oauth2_client

@property
def headers(self):
return self._api_headers
Expand Down
1 change: 1 addition & 0 deletions src/nbiatoolkit/utils/nbia_endpoints.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ class NBIA_ENDPOINTS(Enum):

BASE_URL = "https://services.cancerimagingarchive.net/nbia-api/services/"
NLST_URL = "https://nlst.cancerimagingarchive.net/nbia-api/services/"
LOGOUT_URL = "https://services.cancerimagingarchive.net/nbia-api/logout"

GET_COLLECTIONS = "v2/getCollectionValues"
GET_COLLECTION_PATIENT_COUNT = "getCollectionValuesAndCounts"
Expand Down
19 changes: 19 additions & 0 deletions tests/test_auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,3 +67,22 @@ def test_request_new_access_token(oauth: OAuth2) -> None:
assert oauth.expiry_time is not None
assert oauth.is_token_expired() == False

def test_logout(oauth: OAuth2) -> None:
oauth.logout()
assert oauth.access_token is None
assert oauth.refresh_token is ""
assert oauth.refresh_expiry is None
assert oauth.expiry_time is None
assert oauth.api_headers == {
"Authorization": "Bearer None",
"Content-Type": "application/json",
}
assert oauth.token_expiration_time == None
assert oauth.refresh_expiration_time == None
assert oauth.token_scope == None
assert oauth.__repr__() == ""
assert oauth.__str__() == ""
assert oauth.username == ""
assert oauth.client_id == ""
assert oauth.password == ""
assert oauth.base_url == ""
9 changes: 8 additions & 1 deletion tests/test_nbia.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import os
import requests


@pytest.fixture(scope="session")
def nbia_client():
nbia = NBIAClient()
Expand Down Expand Up @@ -245,4 +246,10 @@ def test_getSeriesMetadata_invalid_input(nbia_client):
with pytest.raises(requests.exceptions.RequestException):
seriesUIDs = ["12345", 67890]
metadata = nbia_client.getSeriesMetadata(seriesUIDs)
assert metadata is None
assert metadata is None

def test_nbiaclient_exit(nbia_client):
with nbia_client:
collections = nbia_client.getCollections()
assert not nbia_client._oauth2_client.is_logged_out()
assert nbia_client._oauth2_client.is_logged_out() # Assuming there is a method to check if the client is logged out

0 comments on commit 528d1a7

Please sign in to comment.