59 lines
2.1 KiB
Python
59 lines
2.1 KiB
Python
"""认证接口。"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from fastapi import APIRouter
|
|
|
|
from app.core.deps import AdminAccount, CurrentAccount, DbSession
|
|
from app.core.response import Resp, ok
|
|
from app.dao.account_dao import AccountDao
|
|
from app.schema.auth_schema import AccountCreate, AccountOut, LoginParams, PasswordChange, TokenOut
|
|
from app.service.auth_service import AuthService
|
|
|
|
router = APIRouter(prefix="/auth", tags=["2.9 登录认证"])
|
|
|
|
|
|
@router.post("/login", response_model=Resp[TokenOut], summary="登录获取 token")
|
|
def login(db: DbSession, payload: LoginParams):
|
|
account, token, expires_in = AuthService.login(db, payload.username, payload.password)
|
|
db.commit()
|
|
return ok(
|
|
{
|
|
"access_token": token,
|
|
"token_type": "Bearer",
|
|
"expires_in": expires_in,
|
|
"account": AccountOut.model_validate(account),
|
|
},
|
|
msg=f"欢迎回来,{account.real_name}",
|
|
)
|
|
|
|
|
|
@router.get("/me", response_model=Resp[AccountOut], summary="当前登录用户")
|
|
def me(account: CurrentAccount):
|
|
return ok(AccountOut.model_validate(account))
|
|
|
|
|
|
@router.post("/password", summary="修改自己的密码")
|
|
def change_password(db: DbSession, account: CurrentAccount, payload: PasswordChange):
|
|
AuthService.change_password(db, account, payload)
|
|
db.commit()
|
|
return ok(msg="密码修改成功,请重新登录")
|
|
|
|
|
|
@router.get("/accounts", summary="账号列表(管理员)")
|
|
def list_accounts(db: DbSession, _: AdminAccount):
|
|
from sqlalchemy import select
|
|
|
|
from app.model import Account
|
|
|
|
accounts = db.scalars(select(Account).where(Account.alive()).order_by(Account.id.asc())).unique().all()
|
|
return ok([AccountOut.model_validate(a) for a in accounts])
|
|
|
|
|
|
@router.post("/accounts", response_model=Resp[AccountOut], summary="新增账号(管理员)")
|
|
def create_account(db: DbSession, _: AdminAccount, payload: AccountCreate):
|
|
account = AuthService.create_account(db, payload)
|
|
db.commit()
|
|
db.refresh(account)
|
|
return ok(AccountOut.model_validate(account), msg=f"账号 {account.username} 创建成功")
|