78 lines
2.4 KiB
Python
78 lines
2.4 KiB
Python
import sys
|
|
from pathlib import Path
|
|
|
|
import jwt
|
|
|
|
ROOT = Path(__file__).resolve().parents[2]
|
|
API_ROOT = ROOT / "apps" / "api"
|
|
if str(API_ROOT) not in sys.path:
|
|
sys.path.insert(0, str(API_ROOT))
|
|
|
|
import importlib.util
|
|
|
|
spec = importlib.util.spec_from_file_location("auth_simple", API_ROOT / "app" / "api" / "routes" / "auth_simple.py")
|
|
auth_simple = importlib.util.module_from_spec(spec)
|
|
assert spec.loader is not None
|
|
spec.loader.exec_module(auth_simple)
|
|
|
|
_create_access_token = auth_simple._create_access_token
|
|
_verify_password_with_legacy_upgrade = auth_simple._verify_password_with_legacy_upgrade
|
|
from app.config import settings
|
|
|
|
from packages.adapters.sqlalchemy_impl.models import UserModel
|
|
from packages.domain.auth import password_hasher
|
|
|
|
|
|
class DummySession:
|
|
def __init__(self):
|
|
self.committed = False
|
|
self.refreshed = False
|
|
self.added = []
|
|
|
|
def add(self, item):
|
|
self.added.append(item)
|
|
|
|
def commit(self):
|
|
self.committed = True
|
|
|
|
def refresh(self, item):
|
|
self.refreshed = True
|
|
|
|
|
|
def test_create_access_token_returns_verifiable_jwt():
|
|
user = UserModel(id="user-1", email="user@example.com", username="user", display_name="User")
|
|
|
|
token, expires_in = _create_access_token(user)
|
|
payload = jwt.decode(token, settings.JWT_SECRET_KEY, algorithms=["HS256"])
|
|
|
|
assert expires_in == 1800
|
|
assert payload["sub"] == "user-1"
|
|
assert payload["email"] == "user@example.com"
|
|
assert payload["type"] == "user_auth"
|
|
|
|
|
|
def test_verify_password_accepts_bcrypt_hash():
|
|
db = DummySession()
|
|
user = UserModel(password_hash=password_hasher.hash_password("Password1"))
|
|
|
|
assert _verify_password_with_legacy_upgrade("Password1", user, db) is True
|
|
assert db.committed is False
|
|
|
|
|
|
def test_verify_password_upgrades_legacy_sha256_hash():
|
|
db = DummySession()
|
|
user = UserModel(password_hash="19513fdc9da4fb72a4a05eb66917548d3c90ff94d5419e1f2363eea89dfee1dd")
|
|
|
|
assert _verify_password_with_legacy_upgrade("Password1", user, db) is True
|
|
assert user.password_hash.startswith("$2")
|
|
assert db.committed is True
|
|
assert db.refreshed is True
|
|
|
|
|
|
def test_verify_password_rejects_wrong_password():
|
|
db = DummySession()
|
|
user = UserModel(password_hash=password_hasher.hash_password("Password1"))
|
|
|
|
assert _verify_password_with_legacy_upgrade("WrongPassword1", user, db) is False
|
|
assert db.committed is False
|