Create login form & handle auth

This commit is contained in:
William Bouzourène 2024-12-21 18:39:09 +01:00
parent cd783fb546
commit af5528f60c
Signed by: bouzoure
SSH key fingerprint: SHA256:19MbXpLua4rUtk8tunMesD8KUKb91LXLHg8E/qTooww
6 changed files with 112 additions and 7 deletions

View file

@ -1,10 +1,72 @@
package controllers
import "github.com/gofiber/fiber/v2"
import (
"errors"
"fmt"
"time"
"git.readonly.ch/bouzoure/popvaud-people/helpers"
"git.readonly.ch/bouzoure/popvaud-people/models"
"github.com/gofiber/fiber/v2"
"gorm.io/gorm"
)
func LoginForm(c *fiber.Ctx) error {
return c.Render("index", fiber.Map{
return c.Render("login", fiber.Map{
"PageTitle": "Connexion",
"Title": "Hello, World!",
}, "layouts/main")
}
func LoginProcess(c *fiber.Ctx) error {
sess, err := helpers.GetSessionStore(c)
if err != nil {
return err
}
db, err := helpers.GetDatabase()
if err != nil {
return err
}
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(),
)
allowLogin := false
if result.Error != nil && !errors.Is(result.Error, gorm.ErrRecordNotFound) {
return err
} else {
allowLogin = helpers.CheckPasswordHash(password, user.Password)
}
if !allowLogin {
return c.Render("login", fiber.Map{
"PageTitle": "Connexion",
"LoginError": "Email ou mot de passe incorrect",
}, "layouts/main")
}
sess.Set("userid", user.ID)
sess.Save()
redirectId := c.Query("redirect")
redirectUrl := "/"
if len(redirectId) > 0 {
redirectKey := fmt.Sprintf("redirect-%s", redirectId)
redirectVal := sess.Get(redirectKey)
if redirectVal != nil {
redirectUrl = redirectVal.(string)
}
}
return c.Redirect(redirectUrl)
}