2025-03-08 00:35:23 +07:00

83 lines
1.7 KiB
Go

package middlewares
import (
"enaklo-pos-be/internal/common/mycontext"
"net/http"
"strings"
"github.com/gin-gonic/gin"
"enaklo-pos-be/internal/repository"
)
func AuthorizationMiddleware(cryp repository.Crypto) gin.HandlerFunc {
return func(c *gin.Context) {
tokenString := c.GetHeader("Authorization")
if tokenString == "" {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Authorization header is required"})
c.Abort()
return
}
tokenString = strings.TrimPrefix(tokenString, "Bearer ")
claims, err := cryp.ParseAndValidateJWT(tokenString)
if err != nil {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid JWT token"})
c.Abort()
return
}
customCtx, err := mycontext.NewMyContext(c.Request.Context(), claims)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "error initialize context"})
c.Abort()
return
}
c.Set("myCtx", customCtx)
c.Next()
}
}
func SuperAdminMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
ctx, exists := c.Get("myCtx")
if !exists {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
c.Abort()
return
}
myCtx, ok := ctx.(*mycontext.MyContextImpl)
if !ok || !myCtx.IsSuperAdmin() {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
c.Abort()
return
}
c.Next()
}
}
func IsAdminMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
ctx, exists := c.Get("myCtx")
if !exists {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
c.Abort()
return
}
myCtx, ok := ctx.(*mycontext.MyContextImpl)
if !ok || !myCtx.IsAdmin() {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
c.Abort()
return
}
c.Next()
}
}