first commit
This commit is contained in:
69
internal/middleware/auth.go
Normal file
69
internal/middleware/auth.go
Normal file
@@ -0,0 +1,69 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"cardverse/internal/pkg/response"
|
||||
"cardverse/internal/pkg/utils"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func AuthRequired() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
authHeader := c.GetHeader("Authorization")
|
||||
if authHeader == "" {
|
||||
response.Error(c, http.StatusUnauthorized, "token tidak ditemukan", nil)
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
parts := strings.SplitN(authHeader, " ", 2)
|
||||
if len(parts) != 2 || strings.ToLower(parts[0]) != "bearer" {
|
||||
response.Error(c, http.StatusUnauthorized, "format token tidak valid", nil)
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
claims, err := utils.ValidateToken(parts[1])
|
||||
if err != nil {
|
||||
response.Error(c, http.StatusUnauthorized, "token tidak valid atau kedaluwarsa", err.Error())
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
c.Set("user_id", claims.UserID)
|
||||
c.Set("email", claims.Email)
|
||||
c.Set("role", claims.Role)
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
func RequireRoles(allowedRoles ...string) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
roleVal, exists := c.Get("role")
|
||||
if !exists {
|
||||
response.Error(c, http.StatusUnauthorized, "akses ditolak: autentikasi diperlukan", nil)
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
userRole, ok := roleVal.(string)
|
||||
if !ok {
|
||||
response.Error(c, http.StatusForbidden, "akses ditolak: role tidak valid", nil)
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
for _, role := range allowedRoles {
|
||||
if strings.EqualFold(userRole, role) {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
response.Error(c, http.StatusForbidden, "akses ditolak: anda tidak memiliki hak akses", nil)
|
||||
c.Abort()
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user