Files
memberApp/backend/user/Middleware.go
Adrian Zürcher a908db4f38 first commit
2025-10-12 14:56:18 +02:00

42 lines
949 B
Go

package user
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5"
)
func AuthMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
// Read access token from cookie
cookie, err := c.Cookie("access_token")
if err != nil {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"message": "not logged in"})
return
}
token, err := jwt.Parse(cookie, func(t *jwt.Token) (any, error) {
return JWT_SECRET, nil
})
if err != nil || !token.Valid {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"message": "invalid token"})
return
}
c.Next()
}
}
func AuthorizeRole(roles ...string) gin.HandlerFunc {
return func(c *gin.Context) {
userRole := c.GetString("role")
for _, role := range roles {
if userRole == role {
c.Next()
return
}
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"message": "Forbidden"})
}
}
}