56 lines
1.2 KiB
Go
56 lines
1.2 KiB
Go
package handler
|
|
|
|
import (
|
|
"net/http"
|
|
"strings"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
adminservice "wx_service/internal/admin/service"
|
|
"wx_service/internal/model"
|
|
)
|
|
|
|
const ContextAdminClaimsKey = "adminClaims"
|
|
|
|
func AuthMiddleware(svc *adminservice.Service) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
token := extractBearerToken(c.GetHeader("Authorization"))
|
|
if token == "" {
|
|
c.AbortWithStatusJSON(http.StatusUnauthorized, model.Error(http.StatusUnauthorized, "missing authorization header"))
|
|
return
|
|
}
|
|
|
|
claims, err := svc.ParseToken(token)
|
|
if err != nil {
|
|
c.AbortWithStatusJSON(http.StatusUnauthorized, model.Error(http.StatusUnauthorized, "invalid admin token"))
|
|
return
|
|
}
|
|
|
|
c.Set(ContextAdminClaimsKey, claims)
|
|
c.Next()
|
|
}
|
|
}
|
|
|
|
func CurrentAdminClaims(c *gin.Context) (*adminservice.Claims, bool) {
|
|
value, ok := c.Get(ContextAdminClaimsKey)
|
|
if !ok {
|
|
return nil, false
|
|
}
|
|
claims, ok := value.(*adminservice.Claims)
|
|
return claims, ok
|
|
}
|
|
|
|
func extractBearerToken(authHeader string) string {
|
|
if authHeader == "" {
|
|
return ""
|
|
}
|
|
parts := strings.SplitN(authHeader, " ", 2)
|
|
if len(parts) != 2 {
|
|
return ""
|
|
}
|
|
if !strings.EqualFold(parts[0], "Bearer") {
|
|
return ""
|
|
}
|
|
return strings.TrimSpace(parts[1])
|
|
}
|