Files
yellow-bank-soal/backend/tests/test_auth_scope.py
2026-06-20 01:43:39 +07:00

43 lines
1.4 KiB
Python

from pathlib import Path
import sys
import pytest
from fastapi import HTTPException
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from app.core.auth import ( # noqa: E402
AuthContext,
ensure_website_scope_matches,
require_website_auth,
)
def test_require_website_auth_returns_scoped_website_for_allowed_role():
auth = AuthContext(website_id=5, role="admin", wp_user_id=None)
website_id = require_website_auth(auth, allowed_roles={"admin", "system_admin"})
assert website_id == 5
def test_require_website_auth_allows_global_system_admin_scope():
auth = AuthContext(website_id=None, role="system_admin", wp_user_id=None)
website_id = require_website_auth(auth, allowed_roles={"admin", "system_admin"})
assert website_id is None
def test_require_website_auth_rejects_disallowed_role():
auth = AuthContext(website_id=5, role="student", wp_user_id="u1")
with pytest.raises(HTTPException) as exc_info:
require_website_auth(auth, allowed_roles={"admin", "system_admin"})
assert exc_info.value.status_code == 403
def test_cross_website_payload_mismatch_is_blocked():
with pytest.raises(HTTPException) as exc_info:
ensure_website_scope_matches(auth_website_id=10, payload_website_id=11)
assert exc_info.value.status_code == 403
def test_global_system_admin_scope_can_write_any_payload_website():
ensure_website_scope_matches(auth_website_id=None, payload_website_id=11)