feat: 引入依赖注入模式

- 创建Repository接口定义(UserRepository、ProfileRepository、TextureRepository等)
- 创建Repository接口实现
- 创建依赖注入容器(container.Container)
- 改造Handler层使用依赖注入(AuthHandler、UserHandler、TextureHandler)
- 创建新的路由注册方式(RegisterRoutesWithDI)
- 提供main.go示例文件展示如何使用依赖注入

同时包含之前的安全修复:
- CORS配置安全加固
- 头像URL验证安全修复
- JWT algorithm confusion漏洞修复
- Recovery中间件增强
- 敏感错误信息泄露修复
- 类型断言安全修复
This commit is contained in:
lan
2025-12-02 17:40:39 +08:00
parent 373c61f625
commit f7589ebbb8
25 changed files with 2029 additions and 139 deletions

View File

@@ -1,16 +1,48 @@
package middleware
import (
"carrotskin/pkg/config"
"github.com/gin-gonic/gin"
)
// CORS 跨域中间件
func CORS() gin.HandlerFunc {
// 获取配置,如果配置未初始化则使用默认值
var allowedOrigins []string
if cfg, err := config.GetConfig(); err == nil {
allowedOrigins = cfg.Security.AllowedOrigins
} else {
// 默认允许所有来源(向后兼容)
allowedOrigins = []string{"*"}
}
return gin.HandlerFunc(func(c *gin.Context) {
c.Header("Access-Control-Allow-Origin", "*")
c.Header("Access-Control-Allow-Credentials", "true")
origin := c.GetHeader("Origin")
// 检查是否允许该来源
allowOrigin := "*"
if len(allowedOrigins) > 0 && allowedOrigins[0] != "*" {
allowOrigin = ""
for _, allowed := range allowedOrigins {
if allowed == origin || allowed == "*" {
allowOrigin = origin
break
}
}
}
if allowOrigin != "" {
c.Header("Access-Control-Allow-Origin", allowOrigin)
// 只有在非通配符模式下才允许credentials
if allowOrigin != "*" {
c.Header("Access-Control-Allow-Credentials", "true")
}
}
c.Header("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
c.Header("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT, DELETE")
c.Header("Access-Control-Max-Age", "86400") // 缓存预检请求结果24小时
if c.Request.Method == "OPTIONS" {
c.AbortWithStatus(204)