hostname-service/middleware/middleware.go

51 lines
1.4 KiB
Go

package middleware
import (
"fmt"
"net/http"
"git.beisel.it/florian/hostname-service/config"
"github.com/dgrijalva/jwt-go"
"github.com/gin-gonic/gin"
)
func Authenticate() gin.HandlerFunc {
return func(c *gin.Context) {
const Bearer_schema = "Bearer "
header := c.GetHeader("Authorization")
if header == "" {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "No token provided"})
return
}
tokenString := header[len(Bearer_schema):]
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method")
}
jwtKeyBytes := []byte(config.GlobalConfig.JwtKey)
return jwtKeyBytes, nil
})
if err != nil {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Invalid token: " + err.Error()})
return
}
if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
// Extract the username from the MapClaims
if username, ok := claims["sub"].(string); ok {
c.Set("username", username)
} else {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Invalid token claims"})
return
}
} else {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Invalid token"})
return
}
c.Next()
}
}