**账号密码登录与会话体系**
- 后端 handlers_auth.go:bcrypt 校验 + 进程内 session store (TTL 8h)
/api/v1/auth/{login,logout,me,change-password}
- access_control.go:principalFromRequest 优先识别 session cookie;
API KEY + session 双轨并存(dev 模式两个 KEY 都为空 → 跳过 loginRequired
保留旧开发体验,任一 KEY 设置后立即开启真实鉴权)
- handlers_mcp.go:所有受管接口复用 authMiddleware,过期 session 401
- handlers_connector.go:连接器读路径同样接入
- main.go:挂 /api/v1/auth/* + 新增 loginRequired() 中间件
- 启动时为 manager/connector/ingest 三个内置主体写 bcrypt('changeme')
首次登录后强制改密(前端 App.vue 弹修改密码对话框)
**前端登录 UI**
- LoginView.vue:账号+密码登录表单(默认密码 changeme)
- App.vue:登录守卫 + 顶栏用户菜单(修改密码 / 退出登录)
- api.js:所有 request 默认 credentials: include 携带 cookie
新增 authLogin/authLogout/authMe/changePassword + mcpCall (JSON-RPC over SSE)
**导入核对工作台 (manager-only)**
- ReviewView.vue + components/ReviewWorkbench.vue +
composables/useReviewWorkbench.js(多 tab:扫描 / 资料 / 核对 / 应用)
- import-review.html + entry-review.js 多入口(vite.config.js 加 rollup input)
- 对应 ssw-ontology-reviewer skill:本体差距自动扫描 + JSON 执行清单
→ 应用到 ontology
**依赖升级**
- go.mod:go 1.25.0 精确化 + golang.org/x/{crypto,net,sync,sys,text}
升级到 bcrypt 兼容版本
291 lines
8.2 KiB
Go
291 lines
8.2 KiB
Go
package main
|
||
|
||
// 账号密码登录与会话。
|
||
// POST /api/v1/auth/login { name, password } → 200 + Set-Cookie
|
||
// POST /api/v1/auth/logout 撤销 session
|
||
// GET /api/v1/auth/me 当前已登录主体(含 clearances/grants)
|
||
//
|
||
// 设计:进程内 session store(map[token]sessionEntry)+ TTL 8h;
|
||
// 适合单机部署。重启服务不会丢失密码(存 DB bcrypt),但所有已签发 session 会失效——
|
||
// 多副本 / 持久化场景可后续替换为 Redis。
|
||
|
||
import (
|
||
"context"
|
||
"crypto/rand"
|
||
"encoding/hex"
|
||
"fmt"
|
||
"net/http"
|
||
"strings"
|
||
"sync"
|
||
"time"
|
||
|
||
"github.com/gin-gonic/gin"
|
||
"golang.org/x/crypto/bcrypt"
|
||
)
|
||
|
||
const (
|
||
// SessionCookieName 浏览器 cookie 名
|
||
SessionCookieName = "ontology_session"
|
||
// SessionTTL 会话有效期
|
||
SessionTTL = 8 * time.Hour
|
||
// DefaultBuiltinPassword dev 模式三个内置主体的初始密码(首次启动时写入 hash)。
|
||
// ⚠️ 首次登录后请管理员立即在「用户管理 → 编辑 → 重置密码」改密。
|
||
DefaultBuiltinPassword = "changeme"
|
||
// MinPasswordLength 用户提交密码的最短长度
|
||
MinPasswordLength = 6
|
||
)
|
||
|
||
// ---------- session store ----------
|
||
|
||
type sessionEntry struct {
|
||
principal string
|
||
expires time.Time
|
||
}
|
||
|
||
var (
|
||
sessionStore = map[string]sessionEntry{}
|
||
sessionStoreMu sync.Mutex
|
||
)
|
||
|
||
func newSessionToken() string {
|
||
b := make([]byte, 32)
|
||
if _, err := rand.Read(b); err != nil {
|
||
// 极低概率 fallback;crypto/rand 失败时退到时间戳+盐
|
||
return fmt.Sprintf("s-%d", time.Now().UnixNano())
|
||
}
|
||
return hex.EncodeToString(b)
|
||
}
|
||
|
||
// issueSession 注册并返回 token
|
||
func issueSession(principal string) string {
|
||
tok := newSessionToken()
|
||
sessionStoreMu.Lock()
|
||
defer sessionStoreMu.Unlock()
|
||
sessionStore[tok] = sessionEntry{principal: principal, expires: time.Now().Add(SessionTTL)}
|
||
return tok
|
||
}
|
||
|
||
// revokeSession 撤销单个 token
|
||
func revokeSession(tok string) {
|
||
sessionStoreMu.Lock()
|
||
defer sessionStoreMu.Unlock()
|
||
delete(sessionStore, tok)
|
||
}
|
||
|
||
// principalFromSession 查 cookie token → principal;过期或不存在返回 ""
|
||
func principalFromSession(token string) string {
|
||
if token == "" {
|
||
return ""
|
||
}
|
||
sessionStoreMu.Lock()
|
||
defer sessionStoreMu.Unlock()
|
||
e, ok := sessionStore[token]
|
||
if !ok {
|
||
return ""
|
||
}
|
||
if time.Now().After(e.expires) {
|
||
delete(sessionStore, token)
|
||
return ""
|
||
}
|
||
return e.principal
|
||
}
|
||
|
||
// gcSessions 定期清理过期(粗粒度:每 30 分钟一次,启动时跑 goroutine)
|
||
func gcSessions() {
|
||
t := time.NewTicker(30 * time.Minute)
|
||
defer t.Stop()
|
||
for range t.C {
|
||
now := time.Now()
|
||
sessionStoreMu.Lock()
|
||
for k, e := range sessionStore {
|
||
if now.After(e.expires) {
|
||
delete(sessionStore, k)
|
||
}
|
||
}
|
||
sessionStoreMu.Unlock()
|
||
}
|
||
}
|
||
|
||
// ---------- bcrypt 帮手 ----------
|
||
|
||
// bcryptHashPassword 对密码做 bcrypt hash(cost=10)
|
||
func bcryptHashPassword(pw string) (string, error) {
|
||
h, err := bcrypt.GenerateFromPassword([]byte(pw), bcrypt.DefaultCost)
|
||
if err != nil {
|
||
return "", err
|
||
}
|
||
return string(h), nil
|
||
}
|
||
|
||
// bcryptVerifyPassword 校验密码与 hash;err=nil 表示匹配
|
||
func bcryptVerifyPassword(hash, pw string) error {
|
||
return bcrypt.CompareHashAndPassword([]byte(hash), []byte(pw))
|
||
}
|
||
|
||
// ---------- handlers ----------
|
||
|
||
type loginInput struct {
|
||
Name string `json:"name"`
|
||
Password string `json:"password"`
|
||
}
|
||
|
||
func (a *app) authLogin(c *gin.Context) {
|
||
var in loginInput
|
||
if err := c.ShouldBindJSON(&in); err != nil {
|
||
c.JSON(http.StatusBadRequest, gin.H{"error": "请求体无效: " + err.Error()})
|
||
return
|
||
}
|
||
name := strings.TrimSpace(in.Name)
|
||
pw := in.Password
|
||
if name == "" || pw == "" {
|
||
c.JSON(http.StatusBadRequest, gin.H{"error": "用户名 / 密码必填"})
|
||
return
|
||
}
|
||
|
||
// public 主体不允许密码登录
|
||
if name == "public" {
|
||
c.JSON(http.StatusUnauthorized, gin.H{"error": "public 主体不可登录"})
|
||
return
|
||
}
|
||
|
||
var hash string
|
||
err := a.pool.QueryRow(c, `SELECT COALESCE(password_hash,'') FROM principals WHERE name=$1`, name).Scan(&hash)
|
||
if err != nil {
|
||
c.JSON(http.StatusUnauthorized, gin.H{"error": "用户名或密码错误"})
|
||
return
|
||
}
|
||
if hash == "" {
|
||
c.JSON(http.StatusUnauthorized, gin.H{"error": "该主体未设置密码,请联系管理员"})
|
||
return
|
||
}
|
||
if err := bcryptVerifyPassword(hash, pw); err != nil {
|
||
c.JSON(http.StatusUnauthorized, gin.H{"error": "用户名或密码错误"})
|
||
return
|
||
}
|
||
|
||
tok := issueSession(name)
|
||
c.SetSameSite(http.SameSiteLaxMode)
|
||
c.SetCookie(SessionCookieName, tok, int(SessionTTL.Seconds()), "/", "", false, true)
|
||
c.JSON(http.StatusOK, gin.H{
|
||
"ok": true,
|
||
"principal": name,
|
||
"expires_in_seconds": int(SessionTTL.Seconds()),
|
||
})
|
||
}
|
||
|
||
func (a *app) authLogout(c *gin.Context) {
|
||
if tok, err := c.Cookie(SessionCookieName); err == nil {
|
||
revokeSession(tok)
|
||
}
|
||
c.SetCookie(SessionCookieName, "", -1, "/", "", false, true)
|
||
c.JSON(http.StatusOK, gin.H{"ok": true})
|
||
}
|
||
|
||
// authMe 返回当前已登录主体的会话/授权上下文。
|
||
// 任意已登录主体可调(不限 manager);未登录返回 401。
|
||
func (a *app) authMe(c *gin.Context) {
|
||
p := principalFromSession(c.Request.Header.Get("X-Session-Token"))
|
||
if p == "" {
|
||
if tok, err := c.Cookie(SessionCookieName); err == nil {
|
||
p = principalFromSession(tok)
|
||
}
|
||
}
|
||
if p == "" {
|
||
c.JSON(http.StatusUnauthorized, gin.H{"error": "未登录"})
|
||
return
|
||
}
|
||
authz, _ := a.authzFor(c, p)
|
||
cls := make([]string, 0, len(authz.Clearances))
|
||
for m := range authz.Clearances {
|
||
cls = append(cls, m)
|
||
}
|
||
c.JSON(http.StatusOK, gin.H{
|
||
"principal": p,
|
||
"is_manager": p == "manager",
|
||
"clearances": cls,
|
||
"grants": authz.Grants,
|
||
})
|
||
}
|
||
|
||
// ---------- password change(自助 / 管理员重置) ----------
|
||
|
||
type changePasswordInput struct {
|
||
OldPassword string `json:"old_password"` // 自助改密时必填
|
||
NewPassword string `json:"new_password"` // 必填
|
||
TargetPrincipal string `json:"target_principal"` // 管理员重置别人的密码时填;自助改密留空
|
||
}
|
||
|
||
func (a *app) changePassword(c *gin.Context) {
|
||
var in changePasswordInput
|
||
if err := c.ShouldBindJSON(&in); err != nil {
|
||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||
return
|
||
}
|
||
if len(in.NewPassword) < MinPasswordLength {
|
||
c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("新密码至少 %d 位", MinPasswordLength)})
|
||
return
|
||
}
|
||
|
||
actor := principalFromSession(c.Request.Header.Get("X-Session-Token"))
|
||
if actor == "" {
|
||
if tok, err := c.Cookie(SessionCookieName); err == nil {
|
||
actor = principalFromSession(tok)
|
||
}
|
||
}
|
||
if actor == "" {
|
||
c.JSON(http.StatusUnauthorized, gin.H{"error": "未登录"})
|
||
return
|
||
}
|
||
|
||
target := strings.TrimSpace(in.TargetPrincipal)
|
||
if target == "" {
|
||
target = actor
|
||
}
|
||
// 非 manager 改别人 → 403;admin 重置他人不需 old_password
|
||
if target != actor && actor != "manager" {
|
||
c.JSON(http.StatusForbidden, gin.H{"error": "只有管理员可以重置他人密码"})
|
||
return
|
||
}
|
||
if target == actor && in.OldPassword != "" {
|
||
// 自助改密:必须提供旧密码(双因素)
|
||
var hash string
|
||
if err := a.pool.QueryRow(c, `SELECT COALESCE(password_hash,'') FROM principals WHERE name=$1`, target).Scan(&hash); err != nil {
|
||
c.JSON(http.StatusNotFound, gin.H{"error": "主体不存在"})
|
||
return
|
||
}
|
||
if hash == "" || bcryptVerifyPassword(hash, in.OldPassword) != nil {
|
||
c.JSON(http.StatusUnauthorized, gin.H{"error": "旧密码错误"})
|
||
return
|
||
}
|
||
} else if target == actor && actor != "manager" {
|
||
// 自助且不是管理员,必须填旧密码
|
||
c.JSON(http.StatusBadRequest, gin.H{"error": "改自己的密码必须提供旧密码"})
|
||
return
|
||
}
|
||
|
||
newHash, err := bcryptHashPassword(in.NewPassword)
|
||
if err != nil {
|
||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||
return
|
||
}
|
||
tag, err := a.pool.Exec(c, `UPDATE principals SET password_hash=$1 WHERE name=$2`, newHash, target)
|
||
if err != nil {
|
||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||
return
|
||
}
|
||
if tag.RowsAffected() == 0 {
|
||
c.JSON(http.StatusNotFound, gin.H{"error": "主体不存在"})
|
||
return
|
||
}
|
||
a.InvalidateAuthzCache(target)
|
||
c.JSON(http.StatusOK, gin.H{"ok": true, "principal": target})
|
||
}
|
||
|
||
// ---------- 初始化 session 清理 goroutine ----------
|
||
|
||
func init() {
|
||
go gcSessions()
|
||
}
|
||
|
||
// ensureCtxAlive 仅占位,避免 unused import
|
||
var _ = context.Background |