2022-09-17 11:10:11 +00:00
|
|
|
import asyncio
|
|
|
|
|
2022-10-04 04:40:11 +00:00
|
|
|
from fastapi import APIRouter
|
2022-09-17 11:10:11 +00:00
|
|
|
from starlette.websockets import WebSocket
|
2022-10-04 04:40:11 +00:00
|
|
|
from websockets.exceptions import WebSocketException
|
2022-09-17 11:10:11 +00:00
|
|
|
|
2022-09-11 10:34:18 +00:00
|
|
|
from core.security import generate_token, verify_password
|
2022-09-17 11:10:11 +00:00
|
|
|
from core.utils import get_system_info
|
2022-09-11 10:34:18 +00:00
|
|
|
from dbhelper.user import get_user
|
2022-09-12 07:22:08 +00:00
|
|
|
from schemas import LoginForm, LoginResult, Response
|
2022-09-11 10:34:18 +00:00
|
|
|
|
2022-10-04 04:40:11 +00:00
|
|
|
router = APIRouter(tags=["公共"])
|
2022-09-11 10:34:18 +00:00
|
|
|
|
2022-10-04 04:40:11 +00:00
|
|
|
|
|
|
|
@router.post("/login", summary="登录", response_model=Response[LoginResult])
|
|
|
|
async def login(auth_data: LoginForm):
|
2022-09-12 15:22:18 +00:00
|
|
|
user_obj = await get_user({"username": auth_data.username, "status__not": 9})
|
2022-09-11 10:34:18 +00:00
|
|
|
if user_obj:
|
|
|
|
if verify_password(auth_data.password, user_obj.password):
|
2022-09-12 07:11:12 +00:00
|
|
|
return Response(
|
|
|
|
data=LoginResult(
|
|
|
|
id=user_obj.id, token=generate_token(auth_data.username)
|
|
|
|
)
|
|
|
|
)
|
2022-09-12 15:22:18 +00:00
|
|
|
return Response(code=400, msg="账号或密码错误")
|
|
|
|
|
|
|
|
|
2022-10-04 04:40:11 +00:00
|
|
|
@router.websocket("/ws", name="系统信息")
|
2022-09-17 11:10:11 +00:00
|
|
|
async def websocket(ws: WebSocket):
|
|
|
|
await ws.accept()
|
|
|
|
try:
|
|
|
|
while True:
|
|
|
|
await asyncio.sleep(1)
|
|
|
|
await ws.send_json(get_system_info())
|
2022-10-04 04:40:11 +00:00
|
|
|
except WebSocketException:
|
2022-09-17 11:10:11 +00:00
|
|
|
await ws.close()
|