zuleleee commited on
Commit
5f90824
·
verified ·
1 Parent(s): 3c54610

Create admin_roles.py

Browse files
Files changed (1) hide show
  1. admin_roles.py +52 -0
admin_roles.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Admin Role-Based Access Control
3
+ Defines roles and permission checking for admin users
4
+ """
5
+
6
+ from fastapi import HTTPException, Depends
7
+ from typing import Optional
8
+ import logging
9
+
10
+ logger = logging.getLogger(__name__)
11
+
12
+ # Admin Roles
13
+ ADMIN_ROLE_SYLLABUS = "admin" # Can upload syllabus only
14
+ ADMIN_ROLE_ENROLLMENT = "school_admin" # Can enroll students only
15
+
16
+ def check_admin_role(admin, required_role: str, action: str = "perform this action"):
17
+ """Check if admin has the required role"""
18
+ # Get role from admin object (works with both SQLAlchemy and MongoDB)
19
+ admin_role = None
20
+
21
+ if hasattr(admin, 'role'):
22
+ admin_role = admin.role
23
+ elif isinstance(admin, dict):
24
+ admin_role = admin.get('role', 'admin')
25
+ else:
26
+ # Default to 'admin' if role not found
27
+ admin_role = 'admin'
28
+
29
+ if admin_role != required_role:
30
+ logger.warning(f"Access denied: Admin {admin.username if hasattr(admin, 'username') else admin.get('username', 'unknown')} (role: {admin_role}) attempted {action} requiring role: {required_role}")
31
+ raise HTTPException(
32
+ status_code=403,
33
+ detail=f"Access denied. This action requires '{required_role}' role. Your role is '{admin_role}'."
34
+ )
35
+
36
+ return True
37
+
38
+ def require_syllabus_admin(admin):
39
+ """Require admin role (syllabus upload only)"""
40
+ return check_admin_role(admin, ADMIN_ROLE_SYLLABUS, "upload syllabus")
41
+
42
+ def require_enrollment_admin(admin):
43
+ """Require school_admin role (student enrollment only)"""
44
+ return check_admin_role(admin, ADMIN_ROLE_ENROLLMENT, "enroll students")
45
+
46
+ def get_admin_role(admin) -> str:
47
+ """Get admin role"""
48
+ if hasattr(admin, 'role'):
49
+ return admin.role
50
+ elif isinstance(admin, dict):
51
+ return admin.get('role', 'admin')
52
+ return 'admin'