38 lines
855 B
Go
38 lines
855 B
Go
package auth
|
|
|
|
import (
|
|
"net/http"
|
|
"strings"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
func Middleware(secret string) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
header := c.GetHeader("Authorization")
|
|
if !strings.HasPrefix(header, "Bearer ") {
|
|
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "missing token"})
|
|
return
|
|
}
|
|
claims, err := ValidateToken(strings.TrimPrefix(header, "Bearer "), secret)
|
|
if err != nil {
|
|
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "invalid token"})
|
|
return
|
|
}
|
|
c.Set("userID", claims.UserID)
|
|
c.Set("email", claims.Email)
|
|
c.Set("role", claims.Role)
|
|
c.Next()
|
|
}
|
|
}
|
|
|
|
func AdminOnly() gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
if c.GetString("role") != "admin" {
|
|
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "admin only"})
|
|
return
|
|
}
|
|
c.Next()
|
|
}
|
|
}
|