提交
This commit is contained in:
1 parent
afd517ce10
commit
eec61cb5dd
82 files changed
+16585
-9026
No files matched your search
+146
-26
@@ -1,7 +1,8 @@
|
||||
"""公共接口(Web 登录、刷新 Token、登出;用户模型对齐 docs/sql/zkxw.sql 基线)"""
|
||||
import os
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request, UploadFile, File
|
||||
from sqlalchemy.exc import OperationalError
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
@@ -22,16 +23,21 @@ from app.core.auth import (
|
||||
)
|
||||
from app.core.response import success_response, error_response
|
||||
from app.core.config import settings
|
||||
from app.core.storage import storage
|
||||
from app.core.avatar_url import extract_avatar_storage_key
|
||||
from app.models.models import SysUser
|
||||
from app.crud.user import user_crud
|
||||
from app.core.utils import generate_uuid
|
||||
from app.core import login_crypto
|
||||
from app.services.web_auth_roles import iter_user_menu_perm_codes, resolve_web_role_for_user
|
||||
from app.schemas.auth import ProfileUpdateRequest
|
||||
from app.crud.user import update_user, change_password
|
||||
|
||||
router = APIRouter(prefix="", tags=["公共接口"])
|
||||
|
||||
|
||||
def _avatar_url_field(user: SysUser) -> Optional[str]:
|
||||
"""返回库中原始头像路径,由前端按 VITE_MINIO_BASE_URL 拼展示 URL。"""
|
||||
raw = getattr(user, "avatar", None)
|
||||
if not raw:
|
||||
return None
|
||||
@@ -48,6 +54,8 @@ def _build_user_info_payload(user: SysUser, web_role: str) -> dict:
|
||||
"realName": user.nick_name,
|
||||
"phone": phone,
|
||||
"email": (getattr(user, "email", None) or "").strip() or None,
|
||||
"sex": getattr(user, "sex", None) or "0",
|
||||
"remark": (getattr(user, "remark", None) or "").strip() or None,
|
||||
"role": web_role,
|
||||
"regionId": user.dept_id,
|
||||
"regionName": None,
|
||||
@@ -55,6 +63,36 @@ def _build_user_info_payload(user: SysUser, web_role: str) -> dict:
|
||||
}
|
||||
|
||||
|
||||
def _build_current_user_payload(current_user: dict) -> dict:
|
||||
"""组装 current-user 接口响应。"""
|
||||
au = current_user.get("avatar_url")
|
||||
avatar_url = str(au).strip() if au else None
|
||||
return {
|
||||
"id": current_user.get("user_id"),
|
||||
"username": current_user.get("username"),
|
||||
"realName": current_user.get("real_name"),
|
||||
"phone": current_user.get("phone"),
|
||||
"email": current_user.get("email"),
|
||||
"sex": current_user.get("sex") or "0",
|
||||
"remark": current_user.get("remark"),
|
||||
"role": current_user.get("role"),
|
||||
"isSuperAdmin": current_user.get("role") == "super_admin",
|
||||
"regionId": current_user.get("region_id"),
|
||||
"regionName": None,
|
||||
"regionIds": [],
|
||||
"isActive": current_user.get("is_active"),
|
||||
"avatarUrl": avatar_url if avatar_url else None,
|
||||
}
|
||||
|
||||
|
||||
async def _resolve_current_user_from_request(request: Request, db: Session) -> dict:
|
||||
authorization = request.headers.get("Authorization", "")
|
||||
if not authorization.startswith("Bearer "):
|
||||
raise HTTPException(status_code=401, detail="未授权")
|
||||
token = authorization.replace("Bearer ", "")
|
||||
return await get_current_user_by_token(token=token, db=db)
|
||||
|
||||
|
||||
def _jwt_user_payload(user: SysUser, web_role: str) -> dict:
|
||||
return {
|
||||
"sub": user.id,
|
||||
@@ -214,36 +252,118 @@ async def logout(request: Request):
|
||||
@router.get("/web/auth/current-user", response_model=dict)
|
||||
async def get_current_user_profile(request: Request, db: Session = Depends(get_db)):
|
||||
"""获取当前用户信息(与 sys_user 字段对应)。"""
|
||||
authorization = request.headers.get("Authorization", "")
|
||||
if not authorization.startswith("Bearer "):
|
||||
return error_response(401, "未授权")
|
||||
|
||||
token = authorization.replace("Bearer ", "")
|
||||
try:
|
||||
current_user = await get_current_user_by_token(token=token, db=db)
|
||||
|
||||
au = current_user.get("avatar_url")
|
||||
avatar_url = str(au).strip() if au else None
|
||||
return success_response(
|
||||
{
|
||||
"id": current_user.get("user_id"),
|
||||
"username": current_user.get("username"),
|
||||
"realName": current_user.get("real_name"),
|
||||
"phone": current_user.get("phone"),
|
||||
"email": current_user.get("email"),
|
||||
"role": current_user.get("role"),
|
||||
"isSuperAdmin": current_user.get("role") == "super_admin",
|
||||
"regionId": current_user.get("region_id"),
|
||||
"regionName": None,
|
||||
"regionIds": [],
|
||||
"isActive": current_user.get("is_active"),
|
||||
"avatarUrl": avatar_url if avatar_url else None,
|
||||
}
|
||||
)
|
||||
current_user = await _resolve_current_user_from_request(request, db)
|
||||
return success_response(_build_current_user_payload(current_user))
|
||||
except HTTPException:
|
||||
return error_response(401, "Token无效或已过期")
|
||||
|
||||
|
||||
@router.put("/web/auth/profile", response_model=dict)
|
||||
async def update_current_user_profile(
|
||||
request: Request,
|
||||
body: ProfileUpdateRequest,
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""当前用户更新个人信息(手机号、邮箱、性别、备注)。"""
|
||||
try:
|
||||
current_user = await _resolve_current_user_from_request(request, db)
|
||||
user_id = current_user.get("user_id")
|
||||
if not user_id:
|
||||
return error_response(401, "未授权")
|
||||
|
||||
payload = body.model_dump(exclude_unset=True, by_alias=False)
|
||||
update_user(
|
||||
db,
|
||||
user_id,
|
||||
phone_no=payload.get("phone_no"),
|
||||
email=payload.get("email"),
|
||||
sex=payload.get("sex"),
|
||||
remark=payload.get("remark"),
|
||||
avatar=payload.get("avatar"),
|
||||
user_id_updater=user_id,
|
||||
)
|
||||
|
||||
user = user_crud.get(db, user_id)
|
||||
if not user:
|
||||
return error_response(404, "用户不存在")
|
||||
web_role = resolve_web_role_for_user(db, user.id)
|
||||
return success_response(_build_user_info_payload(user, web_role))
|
||||
except HTTPException:
|
||||
return error_response(401, "Token无效或已过期")
|
||||
except ValueError as exc:
|
||||
return error_response(400, str(exc))
|
||||
|
||||
|
||||
@router.post("/web/auth/change-password", response_model=dict)
|
||||
async def change_current_user_password(
|
||||
request: Request,
|
||||
body: dict,
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""当前用户修改密码。"""
|
||||
try:
|
||||
current_user = await _resolve_current_user_from_request(request, db)
|
||||
user_id = current_user.get("user_id")
|
||||
if not user_id:
|
||||
return error_response(401, "未授权")
|
||||
|
||||
old_password = (body.get("oldPassword") or body.get("old_password") or "").strip()
|
||||
new_password = (body.get("newPassword") or body.get("new_password") or "").strip()
|
||||
if not old_password:
|
||||
return error_response(400, "请输入原密码")
|
||||
if len(new_password) < 6:
|
||||
return error_response(400, "新密码长度不能少于6位")
|
||||
|
||||
change_password(db, user_id, old_password, new_password)
|
||||
return success_response({"message": "密码修改成功"})
|
||||
except HTTPException:
|
||||
return error_response(401, "Token无效或已过期")
|
||||
except ValueError as exc:
|
||||
return error_response(400, str(exc))
|
||||
|
||||
|
||||
_AVATAR_MAX_BYTES = 2 * 1024 * 1024
|
||||
_AVATAR_ALLOWED_EXT = {".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp"}
|
||||
|
||||
|
||||
@router.post("/web/auth/upload-avatar", response_model=dict)
|
||||
async def upload_current_user_avatar(
|
||||
request: Request,
|
||||
file: UploadFile = File(...),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""当前用户上传头像(仅图片,最大 2MB)。"""
|
||||
try:
|
||||
await _resolve_current_user_from_request(request, db)
|
||||
except HTTPException:
|
||||
return error_response(401, "Token无效或已过期")
|
||||
|
||||
if not file or not file.filename:
|
||||
return error_response(400, "请选择图片")
|
||||
|
||||
ext = os.path.splitext(file.filename)[1].lower()
|
||||
if ext not in _AVATAR_ALLOWED_EXT:
|
||||
return error_response(400, "仅支持 JPG、PNG、GIF、WEBP、BMP 格式")
|
||||
|
||||
content_type = (file.content_type or "").lower()
|
||||
if content_type and not content_type.startswith("image/"):
|
||||
return error_response(400, "仅支持上传图片文件")
|
||||
|
||||
try:
|
||||
file_content = await file.read()
|
||||
if not file_content:
|
||||
return error_response(400, "文件内容为空")
|
||||
if len(file_content) > _AVATAR_MAX_BYTES:
|
||||
return error_response(400, "头像大小不能超过 2MB")
|
||||
|
||||
url = storage.upload_file(file_content, file.filename, "avatar")
|
||||
stored_url = extract_avatar_storage_key(url)
|
||||
return success_response({"url": stored_url})
|
||||
except Exception as exc:
|
||||
return error_response(500, f"上传失败: {str(exc)}")
|
||||
|
||||
|
||||
@router.get("/web/auth/menu-codes", response_model=dict)
|
||||
async def get_web_auth_menu_codes(request: Request, db: Session = Depends(get_db)):
|
||||
"""获取当前用户菜单权限标识(sys_menu.perms,经角色继承)。"""
|
||||
|
||||
Reference in new issue
Block a user