init project
This commit is contained in:
@@ -0,0 +1,63 @@
|
||||
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()
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user