first commit
This commit is contained in:
41
backend/user/Middleware.go
Normal file
41
backend/user/Middleware.go
Normal 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"})
|
||||
}
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user