Phase 3 of Migration

This commit is contained in:
2026-04-17 15:39:29 +03:00
parent c7d5206d0c
commit 83361fad77
9 changed files with 481 additions and 198 deletions

View File

@@ -1,59 +1,57 @@
from fastapi import APIRouter
from shared.firebase import get_db
from fastapi import APIRouter, Depends
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from database.postgres import get_pg_session
from staff.orm import Staff
from auth.models import LoginRequest, TokenResponse
from auth.utils import verify_password, create_access_token
from shared.exceptions import AuthenticationError
router = APIRouter(prefix="/api/auth", tags=["auth"])
_ROLE_MAP = {
"superadmin": "sysadmin",
"melody_editor": "editor",
"device_manager": "editor",
"user_manager": "editor",
"viewer": "user",
"staff": "user",
}
@router.post("/login", response_model=TokenResponse)
async def login(body: LoginRequest):
db = get_db()
if not db:
raise AuthenticationError("Service unavailable")
async def login(body: LoginRequest, db: AsyncSession = Depends(get_pg_session)):
result = await db.execute(
select(Staff).where(Staff.email == body.email).limit(1)
)
staff = result.scalar_one_or_none()
users_ref = db.collection("admin_users")
query = users_ref.where("email", "==", body.email).limit(1).get()
if not query:
if staff is None:
raise AuthenticationError("Invalid email or password")
doc = query[0]
user_data = doc.to_dict()
if not user_data.get("is_active", True):
if not staff.is_active:
raise AuthenticationError("Account is disabled")
if not verify_password(body.password, user_data["hashed_password"]):
if not verify_password(body.password, staff.hashed_password):
raise AuthenticationError("Invalid email or password")
role = user_data["role"]
# Map legacy roles to new roles
role_mapping = {
"superadmin": "sysadmin",
"melody_editor": "editor",
"device_manager": "editor",
"user_manager": "editor",
"viewer": "user",
}
role = role_mapping.get(role, role)
role = _ROLE_MAP.get(staff.role, staff.role)
token = create_access_token({
"sub": doc.id,
"email": user_data["email"],
"role": role,
"name": user_data["name"],
"sub": staff.id,
"email": staff.email,
"role": role,
"name": staff.name,
})
# Get permissions for editor/user roles
permissions = None
if role in ("editor", "user"):
permissions = user_data.get("permissions")
permissions = staff.permissions
return TokenResponse(
access_token=token,
role=role,
name=user_data["name"],
name=staff.name,
permissions=permissions,
)