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

@ -12,61 +12,62 @@ import (
)
func LoginForm(c *fiber.Ctx) error {
return c.Render("login", fiber.Map{
"PageTitle": "Connexion",
})
}
func LoginProcess(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")
}
db, err := helpers.GetDatabase()
if err != nil {
return err
}
email := c.FormValue("email")
password := c.FormValue("password")
var loginError string
if c.Method() == "POST" {
email := c.FormValue("email")
password := c.FormValue("password")
var user models.User
result := db.First(
&user,
"LOWER(email) = LOWER(?) AND (disabled_at IS NULL OR disabled_at <= ?)",
email,
time.Now(),
)
var user models.User
result := db.First(
&user,
"LOWER(email) = LOWER(?) AND (disabled_at IS NULL OR disabled_at <= ?)",
email,
time.Now(),
)
allowLogin := false
if result.Error != nil && !errors.Is(result.Error, gorm.ErrRecordNotFound) {
return err
} else {
allowLogin = helpers.CheckPasswordHash(password, user.Password)
}
if result.Error != nil && !errors.Is(result.Error, gorm.ErrRecordNotFound) {
return err
}
if !allowLogin {
return c.Render("login", fiber.Map{
"PageTitle": "Connexion",
"LoginError": "Email ou mot de passe incorrect",
})
}
if helpers.CheckPasswordHash(password, user.Password) {
sess.Set("userid", user.ID)
sess.Save()
sess.Set("userid", user.ID)
sess.Save()
redirectId := c.Query("redirect")
redirectUrl := "/"
redirectId := c.Query("redirect")
redirectUrl := "/"
if len(redirectId) > 0 {
redirectKey := fmt.Sprintf("redirect-%s", redirectId)
redirectVal := sess.Get(redirectKey)
if len(redirectId) > 0 {
redirectKey := fmt.Sprintf("redirect-%s", redirectId)
redirectVal := sess.Get(redirectKey)
if redirectVal != nil {
redirectUrl = redirectVal.(string)
}
}
if redirectVal != nil {
redirectUrl = redirectVal.(string)
return c.Redirect(redirectUrl)
} else {
loginError = "Email ou mot de passe incorrect"
}
}
return c.Redirect(redirectUrl)
return c.Render("login", fiber.Map{
"PageTitle": "Connexion",
"LoginError": loginError,
})
}