Skip to content
Snippets Groups Projects
Commit 0fd3ca90 authored by Sebastian Mohr's avatar Sebastian Mohr
Browse files

Removed token isvalid method.

parent 5224e500
No related branches found
No related tags found
No related merge requests found
from typing import Optional
from typing import Iterable, Optional
from keyring import get_keyring
......@@ -9,7 +9,7 @@ from .token import Token
def get_all_tokens(
keyring: Optional[keyring_store.KeyringBackend] = None,
files: Optional[file_store.Files] = None,
) -> tuple[list[Token], list[file_store.File]]:
) -> tuple[list[Token], Iterable[file_store.File]]:
"""
Get all tokens from all sources.
......@@ -25,7 +25,7 @@ def get_all_tokens(
# Get tokens from keyring
tokens += keyring_store.get_all_tokens(keyring)
sources = ["keyring"] * len(tokens)
sources: list[file_store.File] = ["keyring"] * len(tokens)
# Get tokens from file
tokens_from_file, sources_from_file = file_store.get_all_tokens(files)
......
......@@ -21,7 +21,7 @@ If not files are given we retrieve the tokens from the default locations.
import os
from collections import defaultdict
from configparser import ConfigParser
from typing import Dict, Optional, Sequence, Union
from typing import Optional, Sequence, Union
from snip.logger import log
......@@ -70,14 +70,14 @@ def get_all_tokens(
section, "token"
):
book_id = conf.get(section, "book_id")
token = conf.get(section, "token")
token_str = conf.get(section, "token")
deployment_url = conf.get(
section, "deployment", fallback=Token.deployment_url
)
token = Token.from_unsafe(
section,
book_id,
token,
token_str,
deployment_url,
)
sources.append(file)
......@@ -174,9 +174,9 @@ def __parse_files(
return files
def __duplicates_value_index(lst: list) -> Dict[str, list[int]]:
def __duplicates_value_index(lst: list) -> dict:
"""Find duplicates in a list including indexes."""
D = defaultdict(list)
D: dict = defaultdict(list)
for i, item in enumerate(lst):
D[item].append(i)
D = {k: v for k, v in D.items() if len(v) > 1}
......
......@@ -132,7 +132,7 @@ def save_token(token: Token, kr: KeyringBackend, overwrite: bool = False):
raise ValueError(f"Token with name {token.name} already exists.")
# Insert token
kr.set_password(SNIP_KR_IDENTIFIER, f"{hex_name}:book_id", token.book_id)
kr.set_password(SNIP_KR_IDENTIFIER, f"{hex_name}:book_id", str(token.book_id))
kr.set_password(SNIP_KR_IDENTIFIER, f"{hex_name}:token", token.token)
if token.deployment_url != Token.deployment_url:
kr.set_password(
......
from dataclasses import dataclass
from typing import Optional, Union
import requests
from snip.logger import log
@dataclass
class Token:
......@@ -35,40 +31,3 @@ class Token:
def __repr__(self):
"""Return a string representation of the token."""
return f"Token(name={self.name}, book_id={self.book_id}, deployment_url={self.deployment_url})"
@property
def is_valid(self, secure=True) -> bool:
"""Check if the token is valid.
Quick query to the deployment to check if the
current token is valid.
Returns
-------
bool
True if the token is valid, False otherwise.
"""
# curl -X POST -H "Authorization: Bearer asd" https://localhost:4000/testAuth/1 --insecure
headers = {"Authorization": f"Bearer {self.token}"}
try:
response = requests.post(
f"{self.deployment_url}/testAuth/{self.book_id}",
headers=headers,
verify=secure,
)
# Check if reponse is json type
data = None
if response.headers.get("content-type") == "application/json":
data = response.json()
# Check if response is not 200
if response.status_code != 200:
log.debug(f"Got status code {response.status_code} with {data}")
return False
return True
except requests.exceptions.RequestException as e:
log.warning("Request failed. Deployment might be inaccessible.")
log.debug(e)
return False
import pytest
import requests
from snip.token.storage import file_store, keyring_store
from snip.token.token import Token
......@@ -162,58 +161,3 @@ class TestToken:
token = Token.from_unsafe("test", "123", "asd", Token.deployment_url)
assert token.deployment_url == Token.deployment_url
def test_is_valid(self, monkeypatch):
# Mock requests
def mock_post(url, headers, verify):
return type("Response", (), {"status_code": 200, "headers": {}})
monkeypatch.setattr("requests.post", mock_post)
token = Token("test", 123, "asd")
assert token.is_valid
def test_is_invalid(self, monkeypatch):
# Invalid request i.e. 400/500
def mock_post(url, headers, verify):
class MockResponse:
def __init__(self, status_code, headers):
self.status_code = status_code
self.headers = headers
def json(self):
return {"some_key": "some_value"} # Return a mock JSON response
return MockResponse(
status_code=500, headers={"content-type": "application/json"}
)
monkeypatch.setattr("requests.post", mock_post)
token = Token("test", 123, "asd")
assert not token.is_valid
# Not a JSON response
def mock_post_not_json(url, headers, verify):
class MockResponse:
def __init__(self, status_code, headers):
self.status_code = status_code
self.headers = headers
def json(self):
raise ValueError("Not a JSON response")
return MockResponse(status_code=500, headers={"content-type": "text/html"})
monkeypatch.setattr("requests.post", mock_post_not_json)
token = Token("test", 123, "asd")
assert not token.is_valid
# Raise requests exception
def mock_post_exception(url, headers, verify):
raise requests.exceptions.RequestException("Some error")
monkeypatch.setattr("requests.post", mock_post_exception)
token = Token("test", 123, "asd")
assert not token.is_valid
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment