93 lines
1.6 KiB
Go
93 lines
1.6 KiB
Go
package middlewares
|
|
|
|
import (
|
|
"fmt"
|
|
"strings"
|
|
|
|
"git.readonly.ch/bouzoure/pop-camarades/helpers"
|
|
"git.readonly.ch/bouzoure/pop-camarades/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/") || c.Path() == "/logout" {
|
|
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 result.Error
|
|
}
|
|
|
|
if user.TotpSecret.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/") || c.Path() == "/logout" {
|
|
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()
|
|
}
|