| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677 |
- # -*- coding: utf-8 -*-
- """认证路由:短信登录(用户)、账号密码登录(管理员)、当前用户信息。"""
- import time
- from fastapi import APIRouter, HTTPException, Request
- from pydantic import BaseModel
- import auth
- from db import db, user_row_to_dict
- router = APIRouter(prefix="/api/auth", tags=["auth"])
- class SmsSendBody(BaseModel):
- phone: str
- class SmsLoginBody(BaseModel):
- phone: str
- code: str
- class AdminLoginBody(BaseModel):
- username: str
- password: str
- @router.post("/sms/send")
- def sms_send(body: SmsSendBody):
- phone = body.phone.strip()
- if not phone.isdigit() or len(phone) != 11:
- raise HTTPException(status_code=400, detail="请输入正确的手机号")
- return auth.issue_sms_code(phone)
- @router.post("/sms/login")
- def sms_login(body: SmsLoginBody):
- phone = body.phone.strip()
- code = body.code.strip()
- if not auth.check_sms_code(phone, code):
- raise HTTPException(status_code=400, detail="验证码错误或已过期")
- with db() as cur:
- cur.execute("SELECT * FROM users WHERE phone = %s", (phone,))
- row = cur.fetchone()
- if not row:
- cur.execute(
- "INSERT INTO users (phone, username, name, role, status, password_hash, created_at)"
- " VALUES (%s, NULL, %s, 'user', 'active', NULL, %s)",
- (phone, "用户" + phone[-4:], int(time.time())),
- )
- cur.execute("SELECT * FROM users WHERE phone = %s", (phone,))
- row = cur.fetchone()
- if row["status"] != "active":
- raise HTTPException(status_code=403, detail="账号已被禁用,请联系客服")
- user = user_row_to_dict(row)
- return {"token": auth.make_token(row["id"], row["role"]), "user": user}
- @router.post("/admin/login")
- def admin_login(body: AdminLoginBody):
- """后台/工厂协作账号登录(同一入口,按角色分发界面权限)。"""
- with db() as cur:
- cur.execute(
- "SELECT * FROM users WHERE username = %s AND role IN ('admin', 'factory')",
- (body.username.strip(),),
- )
- row = cur.fetchone()
- if not row or not auth.verify_password(body.password, row["password_hash"] or ""):
- raise HTTPException(status_code=401, detail="用户名或密码错误")
- if row["status"] != "active":
- raise HTTPException(status_code=403, detail="账号已被禁用")
- return {"token": auth.make_token(row["id"], row["role"]), "user": user_row_to_dict(row)}
- @router.get("/me")
- def me(request: Request):
- return auth.user_from_request(request)
|