refactor(server): decouple services and improve architecture
- Introduce interfaces for all major services (JWT, PostAI, Comment, Message, Notification, QRCodeLogin, Upload, Vote, etc.) to support dependency inversion. - Move query parameters from `internal/dto` to a new `internal/query` package to separate request payloads from data transfer objects. - Refactor `internal/router` to use embedded `RouterDeps` for cleaner dependency management. - Decouple handlers from repositories by injecting services instead of direct repository access, ensuring proper layering. - Improve database initialization by moving it from `internal/model` to `internal/database`. - Optimize message decryption by implementing a more efficient `BatchDecrypt` method in `MessageEncryptor` using a worker pool. - Enhance error handling and security by implementing fail-fast checks for encryption key length during startup. - Clean up unused code, including the `avatar` package and several unused DTOs.
This commit is contained in:
@@ -10,7 +10,7 @@ import (
|
||||
)
|
||||
|
||||
// Auth 认证中间件
|
||||
func Auth(jwtService *service.JWTService) gin.HandlerFunc {
|
||||
func Auth(jwtService service.JWTService) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
authHeader := c.GetHeader("Authorization")
|
||||
|
||||
@@ -45,7 +45,7 @@ func Auth(jwtService *service.JWTService) gin.HandlerFunc {
|
||||
}
|
||||
|
||||
// OptionalAuth 可选认证中间件
|
||||
func OptionalAuth(jwtService *service.JWTService) gin.HandlerFunc {
|
||||
func OptionalAuth(jwtService service.JWTService) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
authHeader := c.GetHeader("Authorization")
|
||||
if authHeader == "" {
|
||||
|
||||
@@ -9,63 +9,6 @@ import (
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// CasbinAuth Casbin 权限中间件
|
||||
// 需要在 Auth 中间件之后使用
|
||||
func CasbinAuth(casbinService service.CasbinService) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
// 获取请求路径和方法
|
||||
path := c.Request.URL.Path
|
||||
method := c.Request.Method
|
||||
|
||||
// 从上下文获取用户ID (由 Auth 中间件设置)
|
||||
userID, exists := c.Get("user_id")
|
||||
|
||||
// 如果用户未登录,检查是否是公开路由
|
||||
if !exists {
|
||||
// 对于未登录用户,使用匿名角色检查权限
|
||||
allowed, err := casbinService.Enforce(c.Request.Context(), "anonymous", path, method)
|
||||
if err != nil {
|
||||
c.AbortWithStatusJSON(500, gin.H{
|
||||
"code": "INTERNAL_ERROR",
|
||||
"message": "权限检查失败",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
if !allowed {
|
||||
c.AbortWithStatusJSON(401, gin.H{
|
||||
"code": "UNAUTHORIZED",
|
||||
"message": "请先登录",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
|
||||
// 检查用户权限
|
||||
allowed, err := casbinService.EnforceForUser(c.Request.Context(), userID.(string), path, method)
|
||||
if err != nil {
|
||||
c.AbortWithStatusJSON(500, gin.H{
|
||||
"code": "INTERNAL_ERROR",
|
||||
"message": "权限检查失败",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
if !allowed {
|
||||
c.AbortWithStatusJSON(403, gin.H{
|
||||
"code": "FORBIDDEN",
|
||||
"message": "权限不足",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
// RequireRole 要求特定角色的中间件
|
||||
func RequireRole(casbinService service.CasbinService, requiredRoles ...string) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
|
||||
@@ -1,16 +1,20 @@
|
||||
package middleware
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"with_you/internal/model"
|
||||
"with_you/internal/pkg/response"
|
||||
"with_you/internal/repository"
|
||||
"with_you/internal/service"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func RequireVerified(userRepo repository.UserRepository) gin.HandlerFunc {
|
||||
// RequireVerified 要求用户已通过身份认证。
|
||||
// 通过 service.UserService 查询用户(而非直接访问 repository),保持分层一致:
|
||||
//
|
||||
// middleware → service → repository
|
||||
func RequireVerified(userService service.UserService) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
userID, exists := c.Get("user_id")
|
||||
if !exists {
|
||||
@@ -19,7 +23,7 @@ func RequireVerified(userRepo repository.UserRepository) gin.HandlerFunc {
|
||||
return
|
||||
}
|
||||
|
||||
user, err := userRepo.GetByID(userID.(string))
|
||||
user, err := userService.GetUserByID(c.Request.Context(), userID.(string))
|
||||
if err != nil {
|
||||
response.InternalServerError(c, "获取用户信息失败")
|
||||
c.Abort()
|
||||
|
||||
110
internal/middleware/verification_test.go
Normal file
110
internal/middleware/verification_test.go
Normal file
@@ -0,0 +1,110 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"with_you/internal/model"
|
||||
"with_you/internal/service"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// stubUserService 通过嵌入 service.UserService 接口(nil)仅覆盖 GetUserByID。
|
||||
// 未覆盖方法若被调用会 panic,可在测试中暴露非预期的依赖调用。
|
||||
type stubUserService struct {
|
||||
service.UserService // nil 嵌入
|
||||
|
||||
user *model.User
|
||||
err error
|
||||
}
|
||||
|
||||
func (s *stubUserService) GetUserByID(ctx context.Context, id string) (*model.User, error) {
|
||||
if s.err != nil {
|
||||
return nil, s.err
|
||||
}
|
||||
return s.user, nil
|
||||
}
|
||||
|
||||
// runMiddleware 构造一个 gin 引擎,挂载 RequireVerified + 一个标记 handler,
|
||||
// 发起请求并返回 (status, body, nextCalled)。
|
||||
func runMiddleware(t *testing.T, svc service.UserService, setUserID bool, userID any) (int, bool) {
|
||||
t.Helper()
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
nextCalled := false
|
||||
r := gin.New()
|
||||
r.Use(func(c *gin.Context) {
|
||||
if setUserID {
|
||||
c.Set("user_id", userID)
|
||||
}
|
||||
c.Next()
|
||||
})
|
||||
r.GET("/test", RequireVerified(svc), func(c *gin.Context) {
|
||||
nextCalled = true
|
||||
c.JSON(http.StatusOK, gin.H{"ok": true})
|
||||
})
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodGet, "/test", nil)
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
return w.Code, nextCalled
|
||||
}
|
||||
|
||||
// TestRequireVerified_Approved 已认证用户 → 放行(200,next 被调用)。
|
||||
func TestRequireVerified_Approved(t *testing.T) {
|
||||
svc := &stubUserService{
|
||||
user: &model.User{ID: "u1", VerificationStatus: model.VerificationStatusApproved},
|
||||
}
|
||||
code, next := runMiddleware(t, svc, true, "u1")
|
||||
if code != http.StatusOK {
|
||||
t.Errorf("status = %d, want %d", code, http.StatusOK)
|
||||
}
|
||||
if !next {
|
||||
t.Error("next handler should be called for verified user")
|
||||
}
|
||||
}
|
||||
|
||||
// TestRequireVerified_NotApproved 未通过认证用户 → 403 VERIFICATION_REQUIRED。
|
||||
func TestRequireVerified_NotApproved(t *testing.T) {
|
||||
svc := &stubUserService{
|
||||
user: &model.User{ID: "u1", VerificationStatus: model.VerificationStatusPending},
|
||||
}
|
||||
code, next := runMiddleware(t, svc, true, "u1")
|
||||
if code != http.StatusForbidden {
|
||||
t.Errorf("status = %d, want %d", code, http.StatusForbidden)
|
||||
}
|
||||
if next {
|
||||
t.Error("next handler should NOT be called for unverified user")
|
||||
}
|
||||
}
|
||||
|
||||
// TestRequireVerified_UserLookupError 查询用户失败 → 500。
|
||||
func TestRequireVerified_UserLookupError(t *testing.T) {
|
||||
svc := &stubUserService{err: errors.New("db down")}
|
||||
code, next := runMiddleware(t, svc, true, "u1")
|
||||
if code != http.StatusInternalServerError {
|
||||
t.Errorf("status = %d, want %d", code, http.StatusInternalServerError)
|
||||
}
|
||||
if next {
|
||||
t.Error("next handler should NOT be called on lookup error")
|
||||
}
|
||||
}
|
||||
|
||||
// TestRequireVerified_NoUserID 未登录(无 user_id)→ 401。
|
||||
func TestRequireVerified_NoUserID(t *testing.T) {
|
||||
svc := &stubUserService{
|
||||
user: &model.User{ID: "u1", VerificationStatus: model.VerificationStatusApproved},
|
||||
}
|
||||
code, next := runMiddleware(t, svc, false, nil)
|
||||
if code != http.StatusUnauthorized {
|
||||
t.Errorf("status = %d, want %d", code, http.StatusUnauthorized)
|
||||
}
|
||||
if next {
|
||||
t.Error("next handler should NOT be called when user_id missing")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user