From 6bb8eab3fcd83d1096fe63172b7fda2bd5346be5 Mon Sep 17 00:00:00 2001 From: LittleSheep Date: Thu, 31 Oct 2024 21:31:56 +0800 Subject: [PATCH] :sparkles: Add some directly callable functions into adaptor --- pkg/nex/sec/adaptor.go | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/pkg/nex/sec/adaptor.go b/pkg/nex/sec/adaptor.go index b0923c4..91b883a 100644 --- a/pkg/nex/sec/adaptor.go +++ b/pkg/nex/sec/adaptor.go @@ -1,6 +1,7 @@ package sec import ( + "fmt" "github.com/gofiber/fiber/v2" "strings" ) @@ -37,3 +38,22 @@ func ValidatorMiddleware(c *fiber.Ctx) error { return c.Next() } + +func EnsureAuthenticated(c *fiber.Ctx) error { + if _, ok := c.Locals("nex_user").(*UserInfo); !ok { + return fiber.NewError(fiber.StatusUnauthorized) + } + + return nil +} + +func EnsureGrantedPerm(c *fiber.Ctx, key string, val any) error { + if err := EnsureAuthenticated(c); err != nil { + return err + } + info := c.Locals("nex_user").(*UserInfo) + if !info.HasPermNode(key, val) { + return fiber.NewError(fiber.StatusForbidden, fmt.Sprintf("missing permission: %s", key)) + } + return nil +}