aditya.siregar f645f23fd4 Add License
2024-07-29 22:30:29 +07:00

84 lines
1.7 KiB
Go

package middlewares
import (
"furtuna-be/internal/common/mycontext"
"net/http"
"strings"
"github.com/gin-gonic/gin"
"furtuna-be/internal/repository"
)
func AuthorizationMiddleware(cryp repository.Crypto) gin.HandlerFunc {
return func(c *gin.Context) {
// Get the JWT token from the header
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()
}
}