forked from ShaerWare/AI_Secretary_System
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth_manager.py
More file actions
421 lines (295 loc) · 12.2 KB
/
auth_manager.py
File metadata and controls
421 lines (295 loc) · 12.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
"""
Authentication Manager for Admin Panel
Multi-user JWT-based authentication with DB-backed users and role-based access.
Roles: guest, user, admin.
Session-based token management with in-memory cache and revocation support.
"""
import hashlib
import logging
import os
import secrets
from datetime import datetime, timedelta
from typing import Dict, Optional
from uuid import uuid4
import jwt
from fastapi import Depends, HTTPException, status
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from pydantic import BaseModel
from utils.password import verify_password as _verify_legacy_password
logger = logging.getLogger(__name__)
# Configuration
JWT_SECRET = os.getenv("ADMIN_JWT_SECRET", secrets.token_hex(32))
JWT_ALGORITHM = "HS256"
JWT_EXPIRATION_HOURS = int(os.getenv("ADMIN_JWT_EXPIRATION_HOURS", "24"))
# Legacy env-var credentials (fallback when users table is empty)
_LEGACY_USERNAME = os.getenv("ADMIN_USERNAME", "admin")
_LEGACY_PASSWORD_HASH: str = os.getenv("ADMIN_PASSWORD_HASH", "") or ""
if not _LEGACY_PASSWORD_HASH:
_LEGACY_PASSWORD_HASH = hashlib.sha256(b"admin").hexdigest()
# ============== Pydantic Models ==============
class LoginRequest(BaseModel):
username: str
password: str
class LoginResponse(BaseModel):
access_token: str
token_type: str = "bearer"
expires_in: int
class ChangePasswordRequest(BaseModel):
old_password: str
new_password: str
class UpdateProfileRequest(BaseModel):
display_name: Optional[str] = None
class TokenPayload(BaseModel):
sub: str # username
user_id: int # database user id
role: str
exp: int # expiration timestamp
iat: int # issued at timestamp
jti: str = "" # JWT ID for session tracking
class User(BaseModel):
id: int
username: str
role: str
permissions: Dict[str, str] = {}
# ============== Security ==============
security = HTTPBearer(auto_error=False)
# ============== Session Cache ==============
class SessionCache:
"""In-memory cache mapping JTI → user_id for fast session validation."""
def __init__(self) -> None:
self._cache: Dict[str, int] = {} # jti → user_id
def get(self, jti: str) -> Optional[int]:
return self._cache.get(jti)
def put(self, jti: str, user_id: int) -> None:
self._cache[jti] = user_id
def remove(self, jti: str) -> None:
self._cache.pop(jti, None)
def remove_all_for_user(self, user_id: int) -> None:
to_remove = [jti for jti, uid in self._cache.items() if uid == user_id]
for jti in to_remove:
del self._cache[jti]
def size(self) -> int:
return len(self._cache)
_session_cache = SessionCache()
# ============== Permissions Cache ==============
class PermissionsCache:
"""In-memory cache mapping role_name → permissions dict."""
def __init__(self) -> None:
self._cache: Dict[str, Dict[str, str]] = {}
async def get(self, role_name: str) -> Dict[str, str]:
"""Get permissions for role, loading from DB on cache miss."""
if role_name in self._cache:
return self._cache[role_name]
from db.integration import async_role_manager
role = await async_role_manager.get_by_name(role_name)
perms = role.get("permissions", {}) if role else {}
self._cache[role_name] = perms
return perms
def invalidate(self, role_name: Optional[str] = None) -> None:
"""Clear cache. If role_name given, clear only that entry."""
if role_name:
self._cache.pop(role_name, None)
else:
self._cache.clear()
_permissions_cache = PermissionsCache()
# ============== Password Helpers ==============
# Centralized in utils/password.py. Legacy env-var fallback uses _verify_legacy_password.
# ============== Token Management ==============
def create_access_token(
username: str, role: str = "admin", user_id: int = 0
) -> tuple[str, int, str]:
"""Create a JWT access token with a unique JTI.
Returns:
tuple: (token, expires_in_seconds, jti)
"""
now = datetime.utcnow()
expires = now + timedelta(hours=JWT_EXPIRATION_HOURS)
expires_in = int((expires - now).total_seconds())
jti = str(uuid4())
payload = {
"sub": username,
"user_id": user_id,
"role": role,
"exp": int(expires.timestamp()),
"iat": int(now.timestamp()),
"jti": jti,
}
token = jwt.encode(payload, JWT_SECRET, algorithm=JWT_ALGORITHM)
return token, expires_in, jti
def decode_token(token: str) -> Optional[TokenPayload]:
"""Decode and validate a JWT token."""
try:
payload = jwt.decode(token, JWT_SECRET, algorithms=[JWT_ALGORITHM])
# Backward compat: old tokens may not have user_id
if "user_id" not in payload:
payload["user_id"] = 0
# Backward compat: old tokens may not have jti
if "jti" not in payload:
payload["jti"] = ""
return TokenPayload(**payload)
except jwt.ExpiredSignatureError:
logger.debug("Token expired")
return None
except jwt.InvalidTokenError as e:
logger.debug(f"Invalid token: {e}")
return None
# ============== Session Management ==============
async def create_session(
username: str,
role: str,
user_id: int,
ip: Optional[str],
user_agent: Optional[str],
) -> LoginResponse:
"""Create a new session: generate token, persist to DB, populate cache."""
from db.integration import async_session_manager
token, expires_in, jti = create_access_token(username, role, user_id)
expires_at = datetime.utcnow() + timedelta(seconds=expires_in)
await async_session_manager.create_session(
user_id=user_id,
jti=jti,
ip_address=ip,
user_agent=user_agent,
expires_at=expires_at,
)
_session_cache.put(jti, user_id)
return LoginResponse(access_token=token, token_type="bearer", expires_in=expires_in)
async def revoke_session(jti: str) -> bool:
"""Revoke a single session by JTI."""
from db.integration import async_session_manager
_session_cache.remove(jti)
return await async_session_manager.revoke_by_jti(jti)
async def revoke_all_user_sessions(user_id: int) -> int:
"""Revoke all sessions for a user."""
from db.integration import async_session_manager
_session_cache.remove_all_for_user(user_id)
return await async_session_manager.revoke_all_for_user(user_id)
# ============== Authentication ==============
async def authenticate_user(username: str, password: str) -> Optional[User]:
"""Authenticate user against DB. Falls back to env-var admin if no DB users."""
try:
from db.integration import async_user_manager
user_data = await async_user_manager.authenticate(username, password)
if user_data:
return User(
id=user_data["id"],
username=user_data["username"],
role=user_data["role"],
)
# If DB auth failed, check if DB has any users at all
user_count = await async_user_manager.get_user_count()
if user_count > 0:
# DB has users, this is a real auth failure
return None
except Exception as e:
logger.warning(f"DB auth failed, trying legacy: {e}")
# Fallback: legacy env-var admin (when no users in DB or DB unavailable)
if username == _LEGACY_USERNAME and _verify_legacy_password(password, _LEGACY_PASSWORD_HASH):
return User(id=0, username=username, role="admin")
return None
# ============== Session Validation Helpers ==============
async def _validate_session(token_payload: TokenPayload) -> Optional[User]:
"""Validate a decoded token against the session cache/DB.
Returns User if session is valid, None otherwise.
"""
jti = token_payload.jti
# Tokens without jti are pre-session-management tokens — reject
if not jti:
return None
user_id = token_payload.user_id
# Check in-memory cache first
cached_uid = _session_cache.get(jti)
if cached_uid is not None:
if cached_uid != user_id:
return None
return User(id=user_id, username=token_payload.sub, role=token_payload.role)
# Cache miss — check DB
from db.integration import async_session_manager
db_session = await async_session_manager.get_by_jti(jti)
if db_session is None:
return None
if db_session.revoked_at is not None:
return None
if db_session.user is None or not db_session.user.is_active:
return None
# Valid session — populate cache
_session_cache.put(jti, user_id)
return User(id=user_id, username=token_payload.sub, role=token_payload.role)
# ============== FastAPI Dependencies ==============
async def get_current_user(
credentials: Optional[HTTPAuthorizationCredentials] = Depends(security),
) -> User:
"""Dependency to get the current authenticated user."""
if credentials is None:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Not authenticated",
headers={"WWW-Authenticate": "Bearer"},
)
token_payload = decode_token(credentials.credentials)
if token_payload is None:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid or expired token",
headers={"WWW-Authenticate": "Bearer"},
)
user = await _validate_session(token_payload)
if user is None:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Session revoked or user deactivated",
headers={"WWW-Authenticate": "Bearer"},
)
return user
async def get_optional_user(
credentials: Optional[HTTPAuthorizationCredentials] = Depends(security),
) -> Optional[User]:
"""Dependency to get the current user if authenticated, None otherwise."""
if credentials is None:
return None
token_payload = decode_token(credentials.credentials)
if token_payload is None:
return None
return await _validate_session(token_payload)
def require_permission(module: str, min_level: str):
"""FastAPI Depends factory: checks user has >= min_level for module."""
async def _dependency(user: User = Depends(get_current_user)) -> User:
role_name = get_role_for_legacy(user.role)
perms = await _permissions_cache.get(role_name)
user.permissions = perms
user_level = perms.get(module, "")
if not level_gte(user_level, min_level):
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail=f"Permission denied: requires {module}:{min_level}",
)
return user
return _dependency
# ============== RBAC Helpers ==============
_LEVEL_ORDER = {"view": 1, "edit": 2, "manage": 3}
def level_gte(user_level: str, required_level: str) -> bool:
"""Check if user_level is >= required_level in the permission hierarchy."""
return _LEVEL_ORDER.get(user_level, 0) >= _LEVEL_ORDER.get(required_level, 0)
_LEGACY_ROLE_MAP = {"admin": "admin", "user": "operator", "web": "operator", "guest": "viewer"}
def get_role_for_legacy(legacy_role: str) -> str:
"""Map legacy role string to new RBAC role name."""
return _LEGACY_ROLE_MAP.get(legacy_role, "viewer")
def user_has_level(user: User, module: str, min_level: str) -> bool:
"""Check if user has >= min_level for module. Requires permissions pre-loaded."""
return level_gte(user.permissions.get(module, ""), min_level)
async def get_user_permissions(user: User) -> Dict[str, str]:
"""Get permissions dict for user. Uses cache."""
role_name = get_role_for_legacy(user.role)
return await _permissions_cache.get(role_name)
def invalidate_permissions_cache(role_name: Optional[str] = None) -> None:
"""Clear permissions cache. Called when roles are modified."""
_permissions_cache.invalidate(role_name)
# ============== Status ==============
AUTH_ENABLED = os.getenv("ADMIN_AUTH_ENABLED", "true").lower() in ("true", "1", "yes")
def get_auth_status() -> Dict:
"""Get current auth configuration status."""
return {
"enabled": AUTH_ENABLED,
"jwt_expiration_hours": JWT_EXPIRATION_HOURS,
"active_sessions": _session_cache.size(),
}