Add authentication features for admin access
- Introduce a new `auth` module with login, logout, and user verification endpoints for a single admin user. - Update backend routes to require admin authentication for sensitive operations, enhancing security. - Modify frontend components to include an authentication provider and gate, ensuring only authorized users can access the application. - Implement a login page for admin access, improving user experience and security management. - Update API request handling to redirect unauthorized users to the login page, ensuring proper access control.
This commit is contained in:
56
backend/routes/auth.py
Normal file
56
backend/routes/auth.py
Normal file
@@ -0,0 +1,56 @@
|
||||
"""Single-admin login endpoints."""
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Response, status
|
||||
from pydantic import BaseModel
|
||||
from services.auth import (
|
||||
AdminUser,
|
||||
authenticate_admin,
|
||||
clear_auth_cookie,
|
||||
create_admin_token,
|
||||
require_admin,
|
||||
set_auth_cookie,
|
||||
)
|
||||
|
||||
router = APIRouter(prefix="/api/auth", tags=["auth"])
|
||||
|
||||
|
||||
class LoginIn(BaseModel):
|
||||
username: str
|
||||
password: str
|
||||
|
||||
|
||||
class AdminUserOut(BaseModel):
|
||||
username: str
|
||||
displayName: str
|
||||
role: str
|
||||
|
||||
|
||||
def _to_out(user: AdminUser) -> AdminUserOut:
|
||||
return AdminUserOut(
|
||||
username=user.username,
|
||||
displayName=user.display_name,
|
||||
role=user.role,
|
||||
)
|
||||
|
||||
|
||||
@router.post("/login", response_model=AdminUserOut)
|
||||
async def login(body: LoginIn, response: Response):
|
||||
user = authenticate_admin(body.username, body.password)
|
||||
if not user:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="用户名或密码错误",
|
||||
)
|
||||
set_auth_cookie(response, create_admin_token())
|
||||
return _to_out(user)
|
||||
|
||||
|
||||
@router.post("/logout")
|
||||
async def logout(response: Response):
|
||||
clear_auth_cookie(response)
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@router.get("/me", response_model=AdminUserOut)
|
||||
async def me(user: AdminUser = Depends(require_admin)):
|
||||
return _to_out(user)
|
||||
Reference in New Issue
Block a user