Files
37duAutomation/desktop/controlplane/apis/auth.py
T
puddy be1a2899ba feat: 重构控制面安全机制与分页规范
本次提交包含多项安全加固和体验优化:
1. 分离管理密钥与传输凭证,避免持 API Token 者伪造管理员票据
2. 钉钉回调地址增加白名单校验,防止开放重定向钓鱼
3. 初始管理员密码改为随机生成并日志记录,移除硬编码 123456
4. 新增登录防爆破计数表,支持 MySQL 多 worker 共享
5. 统一分页规范,新增 usePagedList composable 和 PagerBar 组件
6. 控制面 CORS 收敛为白名单,避免公网环境下任意站点跨域
7. 插件管理、凭证管理等列表接口支持分页和搜索
8. 强制初始密码修改,未改密前禁止使用管理功能
9. 定时任务触发被拒日志节流,避免授权失效时刷屏
10. 健康检查接口移除环境信息泄露,返回固定响应
2026-09-23 15:19:54 +08:00

184 lines
9.2 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""账号登录与身份路由:当前账号信息 / 可授权平台 / 账号密码登录 / 自助改密 / 员工端扫码换 token。
- 管理写操作(改他人账号/插件)统一走 apis.admin(_require_admin);
- 此处为"自助/登录"类只读或本账号操作。
"""
from __future__ import annotations
from fastapi import APIRouter, Header, HTTPException
from controlplane import config, schemas
from controlplane.core.auth import (
_auth_fail, _auth_gate, _auth_reset, _check_token,
_cloud_account, _identity, _issue_cloud_token,
_require_admin, _sign_admin_token,
)
from controlplane.core.crypto import _hash_password, _verify_password
from controlplane.core.db import _db
from controlplane.core.dingtalk import _dingtalk_userinfo
from controlplane.core.notify import notify_account_created
router = APIRouter()
_CONTROLPLANE_PLATFORMS = [
{"id": "hr", "label": "HR 系统"},
{"id": "oa", "label": "OA 系统"},
] # 需与 webhost/backend/auth.py `_LABELS` 保持一致;新增平台时两侧同步
@router.get("/api/admin/me")
def admin_me(authorization: str = Header(default="", alias="Authorization"),
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
x_api_token: str = Header(default="", alias="X-API-Token"),
x_admin_user: str = Header(default="", alias="X-Admin-User")) -> dict:
"""查询当前账号信息:管理员标识 + 部门 + 昵称 + 头像。
身份来源依次:登录时签发的用户云令牌(Bearer) → 签名票据(X-Admin-Token) →
底座注入的 X-Admin-User(仅当配了 CONTROLPLANE_TOKEN 时可信)。
"""
try:
account = _identity(authorization, x_admin_token, x_api_token, x_admin_user)
except Exception:
account = ""
if not account:
return {"account": "", "is_admin": False, "dept": "", "nickname": "", "avatar": "",
"must_change_pwd": False}
with _db() as conn:
row = conn.execute(
"SELECT is_admin, dept, nickname, status, avatar, must_change_pwd "
"FROM accounts WHERE account = %s",
(account,)).fetchone()
# 账号停用:视为未登录(执行机/控制面前端据此自动登出)
if not row or not row["status"]:
return {"account": "", "is_admin": False, "dept": "", "nickname": "", "avatar": "",
"must_change_pwd": False}
return {"account": account,
"is_admin": bool(row["is_admin"]),
"dept": (row["dept"] if row else "") or "",
"nickname": (row["nickname"] if row else "") or "",
"avatar": (row["avatar"] if row else "") or "",
"must_change_pwd": bool(row["must_change_pwd"])}
@router.get("/api/admin/platforms")
def admin_platforms(x_admin_token: str = Header(default="", alias="X-Admin-Token"),
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
"""可授权平台列表(只读,替代授权页写死 hr/oa)。"""
_require_admin(x_admin_token, x_api_token)
return {"platforms": _CONTROLPLANE_PLATFORMS}
@router.post("/api/admin/auth")
def admin_auth(a: schemas.AuthIn,
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
"""统一账户登录:所有账号均可登录(需密码正确);是否管理员由 is_admin 决定。
登录接口为公开入口,不要求 X-API-Token(否则未登录无法着装鉴权)。"""
account = a.account.strip()
if not account:
raise HTTPException(400, "account 不能为空")
_auth_gate(account)
with _db() as conn:
row = conn.execute(
"SELECT password_hash, salt, is_admin, dept, nickname, must_change_pwd, status, avatar "
"FROM accounts WHERE account = %s",
(account,)).fetchone()
if not row or not _verify_password(a.password, row["salt"], row["password_hash"]):
_auth_fail(account)
raise HTTPException(401, "账号或密码错误")
if not row["status"]:
raise HTTPException(403, "账号已停用,请联系管理员")
_auth_reset(account)
_nickname = (row["nickname"] or "")
return {"ok": True, "account": account, "is_admin": bool(row["is_admin"]),
"dept": (row["dept"] or ""), "nickname": _nickname,
"avatar": (row["avatar"] or ""),
"must_change_pwd": bool(row["must_change_pwd"]),
"token": _sign_admin_token(account),
"cloud_token": _issue_cloud_token(account, _nickname)}
@router.post("/api/admin/password")
def admin_password(p: schemas.PwdIn,
authorization: str = Header(default="", alias="Authorization"),
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
x_api_token: str = Header(default="", alias="X-API-Token"),
x_admin_user: str = Header(default="", alias="X-Admin-User")) -> dict:
"""自助修改密码:任何统一账号可改自己的密码(需旧密码校验通过)。"""
try:
login = _identity(authorization, x_admin_token, x_api_token, x_admin_user)
except Exception:
raise HTTPException(401, "登录态无效或已过期,请重新登录")
if not p.account.strip() or not p.new_password:
raise HTTPException(400, "account 与新密码不能为空")
if len(p.new_password) < 8:
raise HTTPException(400, "新密码至少 8 位")
if p.account != login:
raise HTTPException(403, "只能修改自己的密码")
with _db() as conn:
row = conn.execute(
"SELECT password_hash, salt, must_change_pwd FROM accounts WHERE account = %s",
(login,)).fetchone()
if not row:
raise HTTPException(401, "账号不存在")
# 旧密码校验(所有账号均带盐;首次改密的旧密码 = 钉钉通知下发的初始密码,同样必须输入)
if not row["salt"] or not _verify_password(p.old_password, row["salt"], row["password_hash"]):
raise HTTPException(401, "原密码错误")
_hex, _salt = _hash_password(p.new_password)
with _db() as conn:
conn.execute("UPDATE accounts SET password_hash = %s, salt = %s, must_change_pwd = 0 "
"WHERE account = %s", (_hex, _salt, login))
conn.commit()
return {"ok": True, "account": login}
# ==================== 员工端登录 /auth/exchange(v3 最简方案,壳本机直连接 code) ====================
# 壳 login 云端的唯一接口:壳把浏览器带回的钉钉 code POST 到此,用 AppSecret 换身份 → 找建账号
# (不存在则自动建号:空壳+默认密码+强制改密,并推送钉钉通知)→ 签发云端会话 token(供壳调
# /api/plugins 鉴权,见 apis/plugins §2.2)。token 存储统一在 core.auth(_issue_cloud_token 签发
# 落库 cloud_tokens 表、_cloud_account 解析),此处不再重复声明。
@router.post("/auth/exchange")
def auth_exchange(d: schemas.AuthExchangeIn) -> dict:
"""壳 → 云端:壳 POST 钉钉授权码 code,换取员工工号 + 云端会话 token(找建账号)。"""
code = (d.code or "").strip()
if not code:
raise HTTPException(400, "缺少 code")
if not config.DINGTALK_APP_KEY or not config.DINGTALK_APP_SECRET:
raise HTTPException(503, "未配置钉钉开放平台应用(DINGTALK_APP_KEY / DINGTALK_APP_SECRET)")
info = _dingtalk_userinfo(code)
account = (info.get("account") or "").strip()
if not account:
raise HTTPException(401, "扫码未解析到有效账号,请重新扫码")
nickname = (info.get("nickname") or "").strip()
unionid = (info.get("unionid") or "").strip()
# 找建账号(与 /api/admin/dingtalk/auth 同语义):已存在则同步昵称;不存在则自动建号并通知
with _db() as conn:
row = conn.execute(
"SELECT nickname, status, must_change_pwd, is_admin FROM accounts WHERE account = %s",
(account,)).fetchone()
if row:
if not row["status"]:
raise HTTPException(403, "账号已停用,请联系管理员")
if nickname and nickname != (row["nickname"] or ""):
conn.execute("UPDATE accounts SET nickname = %s WHERE account = %s",
(nickname, account))
conn.commit()
created, must_change = False, bool(row["must_change_pwd"])
is_admin = bool(row["is_admin"])
else:
# 自动建号(空壳):初始密码取默认值,强制首次改密
pwd = config.DINGTALK_DEFAULT_PASSWORD
_hex, _salt = _hash_password(pwd)
conn.execute(
"INSERT INTO accounts(account, password_hash, salt, is_admin, dept, nickname, "
"dingtalk_uid, must_change_pwd) VALUES (%s, %s, %s, 0, '', %s, %s, 1)",
(account, _hex, _salt, nickname, unionid))
conn.commit()
created, must_change, is_admin = True, True, False
notify_account_created(account, nickname, pwd, unionid, source="钉钉扫码")
token = _issue_cloud_token(account, nickname)
return {"token": token, "account": account, "nickname": nickname,
"exists": not created, "created": created, "must_change_pwd": must_change,
"is_admin": is_admin}