From 43a40df901b94f80296287375ef25ecc8d31a528 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?William=20Bouzour=C3=A8ne?= Date: Sat, 21 Dec 2024 11:00:32 +0100 Subject: [PATCH] Handle redirection on login page --- go.mod | 2 +- go.sum | 2 ++ middlewares/authentication.go | 37 ++++++++++++++++++++++++++++------- 3 files changed, 33 insertions(+), 8 deletions(-) diff --git a/go.mod b/go.mod index 25a8f6f..b5119b9 100644 --- a/go.mod +++ b/go.mod @@ -21,7 +21,7 @@ require ( github.com/gofiber/template v1.8.3 // indirect github.com/gofiber/utils v1.1.0 // indirect github.com/golobby/cast v1.3.3 // indirect - github.com/google/uuid v1.5.0 // indirect + github.com/google/uuid v1.6.0 // indirect github.com/jinzhu/inflection v1.0.0 // indirect github.com/jinzhu/now v1.1.5 // indirect github.com/klauspost/compress v1.17.2 // indirect diff --git a/go.sum b/go.sum index 92dac93..5d6fb74 100644 --- a/go.sum +++ b/go.sum @@ -31,6 +31,8 @@ github.com/google/pprof v0.0.0-20221118152302-e6195bd50e26 h1:Xim43kblpZXfIBQsbu github.com/google/pprof v0.0.0-20221118152302-e6195bd50e26/go.mod h1:dDKJzRmX4S37WGHujM7tX//fmj1uioxKzKxz3lo4HJo= github.com/google/uuid v1.5.0 h1:1p67kYwdtXjb0gL0BPiP1Av9wiZPo5A8z2cWkTZ+eyU= github.com/google/uuid v1.5.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E= github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc= github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ= diff --git a/middlewares/authentication.go b/middlewares/authentication.go index 3b3a50a..2ff373b 100644 --- a/middlewares/authentication.go +++ b/middlewares/authentication.go @@ -1,8 +1,11 @@ package middlewares import ( + "fmt" + "git.readonly.ch/bouzoure/popvaud-people/helpers" "github.com/gofiber/fiber/v2" + "github.com/google/uuid" ) func AuthMiddleware(c *fiber.Ctx) error { @@ -15,19 +18,39 @@ func AuthMiddleware(c *fiber.Ctx) error { return err } + denyAccess := false userid := sess.Get("userid") if userid == nil { - return c.Redirect("/login") + denyAccess = true + } else { + active, err := helpers.UserExistsAndIsActive(userid.(int)) + if err != nil { + return err + } + + if !active { + denyAccess = true + } } - active, err := helpers.UserExistsAndIsActive(userid.(int)) - if err != nil { - return err - } + if denyAccess { + if c.Path() == "/" { + return c.Redirect("/login") + } - if !active { - return c.Redirect("/login") + id := uuid.NewString() + key := fmt.Sprintf("redirect-%s", id) + + sess.Set(key, c.Path()) + sess.Save() + + redirectUrl := fmt.Sprintf( + "/login?redirect=%s", + id, + ) + + return c.Redirect(redirectUrl) } return c.Next()