summaryrefslogtreecommitdiff
path: root/nexus/utils/auth/auth.go
diff options
context:
space:
mode:
Diffstat (limited to 'nexus/utils/auth/auth.go')
-rw-r--r--nexus/utils/auth/auth.go54
1 files changed, 54 insertions, 0 deletions
diff --git a/nexus/utils/auth/auth.go b/nexus/utils/auth/auth.go
new file mode 100644
index 0000000..4e44d5e
--- /dev/null
+++ b/nexus/utils/auth/auth.go
@@ -0,0 +1,54 @@
+package auth
+
+import (
+ "nexus/repositories/account"
+ "nexus/repositories/session"
+ "nexus/utils/meta"
+ "strings"
+
+ "github.com/gofiber/fiber/v2"
+)
+
+func APIAuth(handler fiber.Handler) fiber.Handler {
+ return func(context *fiber.Ctx) error {
+ authHeader := context.Get("Authorization")
+ if authHeader == "" {
+ return fiber.ErrUnauthorized
+ }
+
+ parts := strings.SplitN(authHeader, " ", 2)
+ if len(parts) != 2 || parts[0] != "Bearer" {
+ return fiber.ErrUnauthorized
+ }
+
+ s, err := session.FindByAuthToken(parts[1])
+ if err != nil || s == nil {
+ return fiber.ErrUnauthorized
+ }
+
+ if s.IsAuthExpired() {
+ return fiber.ErrUnauthorized
+ }
+
+ a, err := account.FindByID(s.AccountID)
+ if err != nil || a == nil {
+ return fiber.ErrUnauthorized
+ }
+
+ if !a.IsActive {
+ return fiber.ErrUnauthorized
+ }
+
+ context.Locals(meta.AccountKey, a)
+ return handler(context)
+ }
+}
+
+func WebAuth(handler fiber.Handler) fiber.Handler {
+ return func(context *fiber.Ctx) error {
+ if meta.Account(context) == nil {
+ return context.Redirect("/login")
+ }
+ return handler(context)
+ }
+}