feat: enforce api permissions
This commit is contained in:
67
backend/apps/accounts/tests/test_permission_enforcement.py
Normal file
67
backend/apps/accounts/tests/test_permission_enforcement.py
Normal file
@@ -0,0 +1,67 @@
|
||||
from django.contrib.auth import get_user_model
|
||||
from django.contrib.auth.models import Group
|
||||
from django.core.management import call_command
|
||||
|
||||
from apps.audit.models import OperationAuditLog
|
||||
from apps.tickets.models import Ticket
|
||||
|
||||
|
||||
def user_with_role(role_name: str):
|
||||
call_command("bootstrap_governance")
|
||||
user = get_user_model().objects.create_user(username=f"user-{role_name}", password="pass")
|
||||
user.groups.add(Group.objects.get(name=role_name))
|
||||
return user
|
||||
|
||||
|
||||
def test_anonymous_ticket_list_is_denied(client, db):
|
||||
response = client.get("/api/tickets")
|
||||
|
||||
assert response.status_code == 401
|
||||
|
||||
|
||||
def test_user_with_ticket_view_can_list_tickets(client, db):
|
||||
Ticket.objects.create(ticket_no="TK202607010001", title="A", description="A")
|
||||
client.force_login(user_with_role("普通建单人"))
|
||||
|
||||
response = client.get("/api/tickets")
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.json()[0]["ticket_no"] == "TK202607010001"
|
||||
|
||||
|
||||
def test_user_without_ticket_create_cannot_create_ticket(client, db):
|
||||
client.force_login(user_with_role("只读审计员"))
|
||||
|
||||
response = client.post(
|
||||
"/api/tickets",
|
||||
data={"title": "A", "description": "A"},
|
||||
content_type="application/json",
|
||||
)
|
||||
|
||||
assert response.status_code == 403
|
||||
|
||||
|
||||
def test_user_with_solution_view_can_list_solutions(client, db):
|
||||
client.force_login(user_with_role("普通建单人"))
|
||||
|
||||
response = client.get("/api/solutions")
|
||||
|
||||
assert response.status_code == 200
|
||||
|
||||
|
||||
def test_audit_log_requires_audit_permission(client, db):
|
||||
OperationAuditLog.objects.create(
|
||||
module="system",
|
||||
action="health_check",
|
||||
target_type="system",
|
||||
target_id="health",
|
||||
result="success",
|
||||
)
|
||||
client.force_login(user_with_role("普通建单人"))
|
||||
|
||||
denied = client.get("/api/audit/operation-logs")
|
||||
assert denied.status_code == 403
|
||||
|
||||
client.force_login(user_with_role("只读审计员"))
|
||||
allowed = client.get("/api/audit/operation-logs")
|
||||
assert allowed.status_code == 200
|
||||
Reference in New Issue
Block a user