Files
Ydisks-Xianyu-Helper/internal/auth/auth.go
T
2026-06-28 11:54:39 +08:00

164 lines
4.5 KiB
Go
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.
// Package auth 实现 HttpOnly Cookie 会话认证,沿用 Fork 版安全基线:
// - 无默认口令(管理员必须经 init-admin CLI 初始化)
// - 会话存 DB(sessions 表),HttpOnly + SameSite=Lax Cookie 传递
// - bcrypt 哈希,兼容老库无盐 SHA-26(首次登录静默升级)
//
// 中间件基于 net/http,兼容 chi。
package auth
import (
"context"
"errors"
"log/slog"
"net/http"
"xianyu-go/internal/db"
)
// CookieName 会话 Cookie 名(与 Python 端 SESSION_COOKIE_NAME 一致)。
const CookieName = "session"
// CookieMaxAge 会话有效期(24 小时)。
const CookieMaxAge = 24 * 60 * 60
// ctxKey 上下文键类型,避免冲突。
type ctxKey int
const (
ctxKeyUser ctxKey = iota
)
// Service 认证服务。
type Service struct {
Store *db.Store
Logger *slog.Logger
Secure bool // HTTPS 下应为 true,Cookie 加 Secure 标记
}
// LoginResult 登录结果。
type LoginResult struct {
Success bool
User *db.User
Message string
}
// Login 用户名密码登录。成功时返回会话 ID(由调用方写入 Cookie)。
func (s *Service) Login(ctx context.Context, username, password string) (string, *db.User, error) {
user, ok, err := s.Store.Users.VerifyAndUpgrade(ctx, username, password)
if err != nil {
return "", nil, err
}
if !ok {
return "", nil, nil // 密码错误或用户不存在/未激活
}
sid, err := s.Store.Sessions.Create(ctx, user)
if err != nil {
return "", nil, err
}
return sid, user, nil
}
// CreateSessionForUser 为已加载的 user 创建会话,返回 session ID。
func (s *Service) CreateSessionForUser(user *db.User) string {
sid, err := s.Store.Sessions.Create(context.Background(), user)
if err != nil {
s.Logger.Error("创建会话失败", "err", err)
return ""
}
return sid
}
// Logout 删除会话并返回清 Cookie 所需操作。
func (s *Service) Logout(ctx context.Context, sessionID string) {
if sessionID != "" {
_ = s.Store.Sessions.Delete(ctx, sessionID)
}
}
// SetSessionCookie 把会话 ID 写入响应 Cookie(HttpOnly + SameSite=Lax)。
func (s *Service) SetSessionCookie(w http.ResponseWriter, sessionID string) {
http.SetCookie(w, &http.Cookie{
Name: CookieName,
Value: sessionID,
Path: "/",
MaxAge: CookieMaxAge,
HttpOnly: true,
SameSite: http.SameSiteLaxMode,
Secure: s.Secure,
})
}
// ClearSessionCookie 清除会话 Cookie。
func (s *Service) ClearSessionCookie(w http.ResponseWriter) {
http.SetCookie(w, &http.Cookie{
Name: CookieName,
Value: "",
Path: "/",
MaxAge: -1,
HttpOnly: true,
SameSite: http.SameSiteLaxMode,
Secure: s.Secure,
})
}
// SessionFromRequest 从请求 Cookie 取会话。无效返回 nil。
func (s *Service) SessionFromRequest(ctx context.Context, r *http.Request) (*db.Session, error) {
c, err := r.Cookie(CookieName)
if err != nil || c.Value == "" {
return nil, nil
}
sess, err := s.Store.Sessions.Get(ctx, c.Value)
if err != nil {
if errors.Is(err, db.ErrNotFound) {
return nil, nil
}
return nil, err
}
return sess, nil
}
// Middleware 解析会话并把 *db.Session 放入请求上下文。不强制登录(公开路由也可用)。
func (s *Service) Middleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
sess, err := s.SessionFromRequest(r.Context(), r)
if err != nil {
s.Logger.Warn("读取会话失败", "err", err)
}
ctx := WithSession(r.Context(), sess)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
// RequireAuth 要求已登录,否则 401。
func RequireAuth(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if SessionFromContext(r.Context()) == nil {
http.Error(w, `{"detail":"未授权访问"}`, http.StatusUnauthorized)
return
}
next.ServeHTTP(w, r)
})
}
// RequireAdmin 要求管理员,否则 403(须在 RequireAuth 之后)。
func RequireAdmin(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
sess := SessionFromContext(r.Context())
if sess == nil || !sess.IsAdmin {
http.Error(w, `{"detail":"需要管理员权限"}`, http.StatusForbidden)
return
}
next.ServeHTTP(w, r)
})
}
// WithSession / SessionFromContext 上下文存取。
func WithSession(ctx context.Context, sess *db.Session) context.Context {
return context.WithValue(ctx, ctxKeyUser, sess)
}
func SessionFromContext(ctx context.Context) *db.Session {
v, _ := ctx.Value(ctxKeyUser).(*db.Session)
return v
}