78 lines
1.6 KiB
Go
78 lines
1.6 KiB
Go
package handlers
|
|
|
|
import (
|
|
"fiber-sessions/app/templates"
|
|
"fmt"
|
|
"time"
|
|
|
|
"github.com/gofiber/fiber/v2"
|
|
)
|
|
|
|
var pcLogin templates.PageContext = templates.PageContext{
|
|
Title: "Login",
|
|
ActivePage: "login",
|
|
}
|
|
|
|
func checkUsernamePassword(username string, password string) bool {
|
|
return true
|
|
// return username == "pero" && password == "pero"
|
|
}
|
|
|
|
func Login(f *fiber.Ctx) error {
|
|
session, err := sessionStore.Get(f)
|
|
if err != nil {
|
|
panic("Error gettings sessionStore: " + err.Error())
|
|
}
|
|
|
|
userId := session.Get("userId")
|
|
fmt.Printf("userId: %+v\n", userId)
|
|
|
|
Render(f, templates.RenderLogin(pcLogin))
|
|
return nil
|
|
}
|
|
|
|
func LoginSubmit(f *fiber.Ctx) error {
|
|
session, err := sessionStore.Get(f)
|
|
if err != nil {
|
|
panic("Error gettings sessionStore: " + err.Error())
|
|
}
|
|
|
|
userId := session.Get("userId")
|
|
fmt.Printf("userId: %+v\n", userId)
|
|
|
|
content := templates.LoginFormValidationContent{
|
|
Validated: true,
|
|
Username: f.FormValue("username"),
|
|
Password: f.FormValue("password"),
|
|
}
|
|
hasError := false
|
|
|
|
if len(content.Username) == 0 {
|
|
content.UsernameError = "Username can not be empty."
|
|
hasError = true
|
|
}
|
|
|
|
if len(content.Password) == 0 {
|
|
content.PasswordError = "Password can not be empty."
|
|
hasError = true
|
|
}
|
|
|
|
if !hasError {
|
|
if checkUsernamePassword(content.Username, content.Password) {
|
|
session.Set("userId", "neki-user-id")
|
|
session.SetExpiry(time.Second * 60)
|
|
if err := session.Save(); err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
f.Set("HX-Location", "/")
|
|
return nil
|
|
} else {
|
|
content.LoginError = "Invalid username or password"
|
|
}
|
|
}
|
|
|
|
Render(f, templates.LoginFormContent(content))
|
|
return nil
|
|
}
|