settings section
This commit is contained in:
68
internal/appresult/middleware.go
Executable file
68
internal/appresult/middleware.go
Executable file
@@ -0,0 +1,68 @@
|
||||
package appresult
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"online-back/internal/config"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/golang-jwt/jwt"
|
||||
)
|
||||
|
||||
func JwtTokenCheck() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
token := extractBearerToken(c.GetHeader("Authorization"))
|
||||
if token == "" {
|
||||
respondWithError(c, http.StatusForbidden, "authorization header is missing")
|
||||
return
|
||||
}
|
||||
|
||||
claims, err := TokenClaims(token, config.GetConfig().JwtKey)
|
||||
if err != nil {
|
||||
respondWithError(c, http.StatusUnauthorized, "invalid or expired token")
|
||||
return
|
||||
}
|
||||
|
||||
isAdmin, ok := claims["admin"].(bool)
|
||||
if !ok || !isAdmin {
|
||||
respondWithError(c, http.StatusForbidden, "unauthorized")
|
||||
return
|
||||
}
|
||||
|
||||
c.Set("id", fmt.Sprint(claims["id"]))
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
func TokenClaims(token, secretKey string) (jwt.MapClaims, error) {
|
||||
decoded, err := jwt.Parse(token, func(token *jwt.Token) (interface{}, error) {
|
||||
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
|
||||
}
|
||||
return []byte(secretKey), nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
claims, ok := decoded.Claims.(jwt.MapClaims)
|
||||
if !ok || !decoded.Valid {
|
||||
return nil, fmt.Errorf("invalid token claims")
|
||||
}
|
||||
|
||||
return claims, nil
|
||||
}
|
||||
|
||||
func extractBearerToken(header string) string {
|
||||
const prefix = "Bearer "
|
||||
if strings.HasPrefix(header, prefix) {
|
||||
return strings.TrimSpace(header[len(prefix):])
|
||||
}
|
||||
return strings.TrimSpace(header)
|
||||
}
|
||||
|
||||
func respondWithError(c *gin.Context, code int, message interface{}) {
|
||||
c.AbortWithStatusJSON(code, gin.H{"error": message})
|
||||
}
|
||||
Reference in New Issue
Block a user