first commit

This commit is contained in:
Adrian Zürcher
2025-10-12 14:56:18 +02:00
parent a9f2e11fe6
commit a908db4f38
92 changed files with 13273 additions and 0 deletions

View File

@@ -0,0 +1,41 @@
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"})
}
}
}