refactor: Update service and repository methods to use context
- Refactored multiple service and repository methods to accept context as a parameter, enhancing consistency and enabling better control over request lifecycles. - Updated handlers to utilize context in method calls, improving error handling and performance. - Cleaned up Dockerfile by removing unnecessary whitespace.
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"carrotskin/internal/model"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
@@ -9,17 +10,16 @@ import (
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// AuthMiddleware JWT认证中间件
|
||||
func AuthMiddleware() gin.HandlerFunc {
|
||||
// AuthMiddleware JWT认证中间件(注入JWT服务版本)
|
||||
func AuthMiddleware(jwtService *auth.JWTService) gin.HandlerFunc {
|
||||
return gin.HandlerFunc(func(c *gin.Context) {
|
||||
jwtService := auth.MustGetJWTService()
|
||||
|
||||
authHeader := c.GetHeader("Authorization")
|
||||
if authHeader == "" {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{
|
||||
"code": 401,
|
||||
"message": "缺少Authorization头",
|
||||
})
|
||||
c.JSON(http.StatusUnauthorized, model.NewErrorResponse(
|
||||
model.CodeUnauthorized,
|
||||
"缺少Authorization头",
|
||||
nil,
|
||||
))
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
@@ -27,10 +27,11 @@ func AuthMiddleware() gin.HandlerFunc {
|
||||
// Bearer token格式
|
||||
tokenParts := strings.SplitN(authHeader, " ", 2)
|
||||
if len(tokenParts) != 2 || tokenParts[0] != "Bearer" {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{
|
||||
"code": 401,
|
||||
"message": "无效的Authorization头格式",
|
||||
})
|
||||
c.JSON(http.StatusUnauthorized, model.NewErrorResponse(
|
||||
model.CodeUnauthorized,
|
||||
"无效的Authorization头格式",
|
||||
nil,
|
||||
))
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
@@ -38,10 +39,11 @@ func AuthMiddleware() gin.HandlerFunc {
|
||||
token := tokenParts[1]
|
||||
claims, err := jwtService.ValidateToken(token)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{
|
||||
"code": 401,
|
||||
"message": "无效的token",
|
||||
})
|
||||
c.JSON(http.StatusUnauthorized, model.NewErrorResponse(
|
||||
model.CodeUnauthorized,
|
||||
"无效的token",
|
||||
err,
|
||||
))
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
@@ -55,11 +57,9 @@ func AuthMiddleware() gin.HandlerFunc {
|
||||
})
|
||||
}
|
||||
|
||||
// OptionalAuthMiddleware 可选的JWT认证中间件
|
||||
func OptionalAuthMiddleware() gin.HandlerFunc {
|
||||
// OptionalAuthMiddleware 可选的JWT认证中间件(注入JWT服务版本)
|
||||
func OptionalAuthMiddleware(jwtService *auth.JWTService) gin.HandlerFunc {
|
||||
return gin.HandlerFunc(func(c *gin.Context) {
|
||||
jwtService := auth.MustGetJWTService()
|
||||
|
||||
authHeader := c.GetHeader("Authorization")
|
||||
if authHeader != "" {
|
||||
tokenParts := strings.SplitN(authHeader, " ", 2)
|
||||
|
||||
Reference in New Issue
Block a user