perf(auth): 降低会话校验请求与重复查库
This commit is contained in:
@@ -217,6 +217,11 @@ func (h *Handler) Logout(c *gin.Context) {
|
||||
response.OK(c, gin.H{"logged_out": true})
|
||||
}
|
||||
|
||||
// Session 返回当前 access token 仍有效。数据库校验由 requireAuth 完成,这里不重复查询。
|
||||
func (h *Handler) Session(c *gin.Context) {
|
||||
response.OK(c, gin.H{"active": true})
|
||||
}
|
||||
|
||||
func (h *Handler) PasswordLogin(c *gin.Context) {
|
||||
var req PasswordLoginRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
|
||||
@@ -58,6 +58,15 @@ func (r *UserRepository) FindByID(ctx context.Context, id uint64) (*model.User,
|
||||
|
||||
// FindActiveForToken 校验用户仍可用且令牌版本未被撤销。
|
||||
func (r *UserRepository) FindActiveForToken(ctx context.Context, id uint64, tokenVersion int64) (*model.User, error) {
|
||||
return r.findActiveForToken(ctx, id, tokenVersion, false)
|
||||
}
|
||||
|
||||
// FindActiveForTokenWithProfile 校验令牌并一次加载完整用户资料,供 /api/me 使用。
|
||||
func (r *UserRepository) FindActiveForTokenWithProfile(ctx context.Context, id uint64, tokenVersion int64) (*model.User, error) {
|
||||
return r.findActiveForToken(ctx, id, tokenVersion, true)
|
||||
}
|
||||
|
||||
func (r *UserRepository) findActiveForToken(ctx context.Context, id uint64, tokenVersion int64, withProfile bool) (*model.User, error) {
|
||||
if r == nil || r.db == nil {
|
||||
return nil, ErrDependencyUnavailable
|
||||
}
|
||||
@@ -67,9 +76,10 @@ func (r *UserRepository) FindActiveForToken(ctx context.Context, id uint64, toke
|
||||
query = query.Where("tenant_id = ? AND distribution_site_id = 0", tenantID)
|
||||
}
|
||||
query = scopeUserQueryToBoundSite(ctx, query)
|
||||
if err := query.
|
||||
Select("users.id, users.phone, users.status, users.token_version").
|
||||
First(&user, id).Error; err != nil {
|
||||
if !withProfile {
|
||||
query = query.Select("users.id, users.phone, users.status, users.token_version")
|
||||
}
|
||||
if err := query.First(&user, id).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if user.Status != "active" {
|
||||
|
||||
@@ -11,7 +11,7 @@ import (
|
||||
func TestUserTokenVersionRevokesAccessAndRefreshTokens(t *testing.T) {
|
||||
db := database.NewTestDB()
|
||||
|
||||
user := model.User{Phone: "13900000001", Status: "active", TokenVersion: 1}
|
||||
user := model.User{Phone: "13900000001", Nickname: "完整资料", Status: "active", TokenVersion: 1}
|
||||
if err := db.Create(&user).Error; err != nil {
|
||||
t.Fatalf("创建用户失败:%v", err)
|
||||
}
|
||||
@@ -22,10 +22,20 @@ func TestUserTokenVersionRevokesAccessAndRefreshTokens(t *testing.T) {
|
||||
t.Fatalf("生成令牌失败:%v", err)
|
||||
}
|
||||
|
||||
_, err = repo.FindActiveForToken(t.Context(), user.ID, 1)
|
||||
minimal, err := repo.FindActiveForToken(t.Context(), user.ID, 1)
|
||||
if err != nil {
|
||||
t.Fatalf("有效令牌校验失败:%v", err)
|
||||
}
|
||||
if minimal.Nickname != "" {
|
||||
t.Fatalf("轻量令牌校验不应加载完整资料:%+v", minimal)
|
||||
}
|
||||
profile, err := repo.FindActiveForTokenWithProfile(t.Context(), user.ID, 1)
|
||||
if err != nil {
|
||||
t.Fatalf("完整资料令牌校验失败:%v", err)
|
||||
}
|
||||
if profile.Nickname != user.Nickname {
|
||||
t.Fatalf("完整资料昵称 = %q, want %q", profile.Nickname, user.Nickname)
|
||||
}
|
||||
|
||||
if err := db.Model(&model.User{}).Where("id = ?", user.ID).Updates(map[string]any{
|
||||
"status": "frozen",
|
||||
|
||||
@@ -26,6 +26,10 @@ func NewHandler(users *auth.UserRepository) *Handler {
|
||||
}
|
||||
|
||||
func (h *Handler) Me(c *gin.Context) {
|
||||
if cached, ok := middleware.AuthenticatedUser(c); ok {
|
||||
response.OK(c, cached)
|
||||
return
|
||||
}
|
||||
if h.users == nil {
|
||||
response.ServiceUnavailable(c, "数据库未连接")
|
||||
return
|
||||
@@ -35,7 +39,12 @@ func (h *Handler) Me(c *gin.Context) {
|
||||
response.Unauthorized(c, "缺少用户上下文")
|
||||
return
|
||||
}
|
||||
user, err := h.users.FindByID(c.Request.Context(), userID.(uint64))
|
||||
id, ok := userID.(uint64)
|
||||
if !ok {
|
||||
response.Unauthorized(c, "用户上下文无效")
|
||||
return
|
||||
}
|
||||
user, err := h.users.FindByID(c.Request.Context(), id)
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
response.Unauthorized(c, "用户不存在")
|
||||
return
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"hfb_sys/backend/internal/middleware"
|
||||
"hfb_sys/backend/internal/model"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func TestMeUsesUserLoadedByAuthMiddleware(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
engine := gin.New()
|
||||
engine.GET("/me", func(c *gin.Context) {
|
||||
c.Set(middleware.ContextUserID, uint64(7))
|
||||
c.Set(middleware.ContextUser, &model.User{
|
||||
ID: 7,
|
||||
Phone: "13900000007",
|
||||
Nickname: "已鉴权用户",
|
||||
Status: "active",
|
||||
})
|
||||
c.Next()
|
||||
}, NewHandler(nil).Me)
|
||||
|
||||
request := httptest.NewRequest(http.MethodGet, "/me", nil)
|
||||
response := httptest.NewRecorder()
|
||||
engine.ServeHTTP(response, request)
|
||||
|
||||
if response.Code != http.StatusOK {
|
||||
t.Fatalf("响应状态 = %d, want %d", response.Code, http.StatusOK)
|
||||
}
|
||||
if !strings.Contains(response.Body.String(), `"nickname":"已鉴权用户"`) {
|
||||
t.Fatalf("响应未复用鉴权用户:%s", response.Body.String())
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user