Rework login process & implement MFA

This commit is contained in:
William Bouzourène 2024-12-22 16:54:42 +01:00
parent d41581aa47
commit 08c8f78328
Signed by: bouzoure
SSH key fingerprint: SHA256:19MbXpLua4rUtk8tunMesD8KUKb91LXLHg8E/qTooww
7 changed files with 297 additions and 56 deletions

View file

@ -55,17 +55,3 @@ func AuthMiddleware(c *fiber.Ctx) error {
return c.Next()
}
func DenyAuthMiddleware(c *fiber.Ctx) error {
sess, err := helpers.GetSessionStore(c)
if err != nil {
return err
}
userid := sess.Get("userid")
if userid != nil {
return fiber.NewError(fiber.StatusForbidden, "Forbidden")
}
return c.Next()
}

View file

@ -1 +1,93 @@
package middlewares
import (
"fmt"
"strings"
"git.readonly.ch/bouzoure/popvaud-people/helpers"
"git.readonly.ch/bouzoure/popvaud-people/models"
"github.com/gofiber/fiber/v2"
"github.com/google/uuid"
)
func MfaEnrollMiddleware(c *fiber.Ctx) error {
if c.Path() == "/login" || c.Path() == "/welcome" || strings.HasPrefix(c.Path(), "/totp/") {
return c.Next()
}
db, err := helpers.GetDatabase()
if err != nil {
return err
}
userid, err := helpers.GetSessionUserId(c)
if err != nil {
return err
}
var user models.User
result := db.First(&user, "id = ?", userid)
if result.Error != nil {
return err
}
if user.TotpSercet.Valid {
return c.Next()
}
if c.Path() == "/" {
return c.Redirect("/totp/enroll")
}
id := uuid.NewString()
key := fmt.Sprintf("redirect-%s", id)
sess, err := helpers.GetSessionStore(c)
if err != nil {
return err
}
sess.Set(key, c.Path())
sess.Save()
redirectUrl := fmt.Sprintf(
"/totp/enroll?redirect=%s",
id,
)
return c.Redirect(redirectUrl)
}
func MfaVerifyMiddleware(c *fiber.Ctx) error {
if c.Path() == "/login" || c.Path() == "/welcome" || strings.HasPrefix(c.Path(), "/totp/") {
return c.Next()
}
sess, err := helpers.GetSessionStore(c)
if err != nil {
return err
}
totpVerified := sess.Get("totp-verified")
if totpVerified == nil {
if c.Path() == "/" {
return c.Redirect("/totp/verify")
}
id := uuid.NewString()
key := fmt.Sprintf("redirect-%s", id)
sess.Set(key, c.Path())
sess.Save()
redirectUrl := fmt.Sprintf(
"/totp/verify?redirect=%s",
id,
)
return c.Redirect(redirectUrl)
}
return c.Next()
}