70 lines
2.2 KiB
Python
70 lines
2.2 KiB
Python
"""Auth routes."""
|
|
|
|
from fastapi import APIRouter, Depends, HTTPException
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.core.database import get_db
|
|
from app.core.auth import get_current_user
|
|
from app.core.security import verify_password, create_local_token
|
|
from app.models.user import User
|
|
|
|
router = APIRouter(tags=["Authentication"])
|
|
|
|
|
|
def _get_user_roles(user: User) -> list:
|
|
"""Get user role names."""
|
|
return [ur.role.name for ur in user.user_roles if ur.role]
|
|
|
|
|
|
@router.post("/login")
|
|
async def login(data: dict, db: Session = Depends(get_db)):
|
|
"""Local login with email/password (standalone mode)."""
|
|
email = data.get("email")
|
|
password = data.get("password")
|
|
|
|
if not email or not password:
|
|
raise HTTPException(status_code=400, detail="Email and password required")
|
|
|
|
user = db.query(User).filter(User.email == email).first()
|
|
if not user:
|
|
raise HTTPException(status_code=401, detail="Invalid email or password")
|
|
|
|
if not user.is_active:
|
|
raise HTTPException(status_code=403, detail="User is deactivated")
|
|
|
|
# For local users - verify password
|
|
# For platform users - they should use platform login
|
|
if user.source == "platform":
|
|
raise HTTPException(status_code=400, detail="Platform users must login via platform")
|
|
|
|
if not verify_password(password, user.password_hash or ""):
|
|
raise HTTPException(status_code=401, detail="Invalid email or password")
|
|
|
|
token = create_local_token(user.id, user.email)
|
|
return {
|
|
"access_token": token,
|
|
"token_type": "bearer",
|
|
"user": {
|
|
"id": user.id,
|
|
"email": user.email,
|
|
"first_name": user.first_name,
|
|
"last_name": user.last_name,
|
|
"is_active": user.is_active,
|
|
"roles": _get_user_roles(user),
|
|
},
|
|
}
|
|
|
|
|
|
@router.get("/me")
|
|
async def get_me(current_user: User = Depends(get_current_user)):
|
|
"""Get current authenticated user."""
|
|
return {
|
|
"id": current_user.id,
|
|
"email": current_user.email,
|
|
"first_name": current_user.first_name,
|
|
"last_name": current_user.last_name,
|
|
"is_active": current_user.is_active,
|
|
"source": current_user.source,
|
|
"roles": _get_user_roles(current_user),
|
|
}
|