152 lines
4.6 KiB
Go
152 lines
4.6 KiB
Go
package handlers
|
|
|
|
import (
|
|
"database/sql"
|
|
"log"
|
|
"net/http"
|
|
"time"
|
|
|
|
httpHelpers "synlotto-website/internal/helpers/http"
|
|
securityHelpers "synlotto-website/internal/helpers/security"
|
|
templateHelpers "synlotto-website/internal/helpers/template"
|
|
"synlotto-website/internal/logging"
|
|
"synlotto-website/internal/models"
|
|
auditlogStorage "synlotto-website/internal/storage/auditlog"
|
|
usersStorage "synlotto-website/internal/storage/users"
|
|
|
|
"github.com/gorilla/csrf"
|
|
"github.com/justinas/nosurf"
|
|
)
|
|
|
|
func Login(db *sql.DB) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method == http.MethodGet {
|
|
session, _ := httpHelpers.GetSession(w, r)
|
|
if _, ok := session.Values["user_id"].(int); ok {
|
|
http.Redirect(w, r, "/", http.StatusSeeOther)
|
|
return
|
|
}
|
|
|
|
tmpl := templateHelpers.LoadTemplateFiles("login.html", "templates/account/login.html")
|
|
data := models.TemplateData{}
|
|
context := templateHelpers.TemplateContext(w, r, data)
|
|
context["CSRFToken"] = nosurf.Token(r)
|
|
|
|
if err := tmpl.ExecuteTemplate(w, "layout", context); err != nil {
|
|
logging.Info("❌ Template render error:", err)
|
|
http.Error(w, "Error rendering login page", http.StatusInternalServerError)
|
|
}
|
|
return
|
|
}
|
|
|
|
username := r.FormValue("username")
|
|
password := r.FormValue("password")
|
|
|
|
// ToDo: this outputs password in clear text remove or obscure!
|
|
logging.Info("🔐 Login attempt - Username: %s, Password: %s", username, password)
|
|
|
|
user := usersStorage.GetUserByUsername(db, username)
|
|
if user == nil {
|
|
logging.Info("❌ User not found: %s", username)
|
|
auditlogStorage.LogLoginAttempt(db, r, username, false)
|
|
|
|
session, _ := httpHelpers.GetSession(w, r)
|
|
session.Values["flash"] = "Invalid username or password."
|
|
session.Save(r, w)
|
|
http.Redirect(w, r, "/account/login", http.StatusSeeOther)
|
|
return
|
|
}
|
|
|
|
if !securityHelpers.CheckPasswordHash(user.PasswordHash, password) {
|
|
logging.Info("❌ Password mismatch for user: %s", username)
|
|
auditlogStorage.LogLoginAttempt(db, r, username, false)
|
|
|
|
session, _ := httpHelpers.GetSession(w, r)
|
|
session.Values["flash"] = "Invalid username or password."
|
|
session.Save(r, w)
|
|
log.Printf("login has did it")
|
|
http.Redirect(w, r, "/account/login", http.StatusSeeOther)
|
|
return
|
|
}
|
|
|
|
logging.Info("✅ Login successful for user: %s", username)
|
|
auditlogStorage.LogLoginAttempt(db, r, username, true)
|
|
|
|
session, _ := httpHelpers.GetSession(w, r)
|
|
for k := range session.Values {
|
|
delete(session.Values, k)
|
|
}
|
|
|
|
session.Values["user_id"] = user.Id
|
|
session.Values["last_activity"] = time.Now().UTC()
|
|
|
|
if r.FormValue("remember") == "on" {
|
|
session.Options.MaxAge = 60 * 60 * 24 * 30
|
|
} else {
|
|
session.Options.MaxAge = 0
|
|
}
|
|
|
|
if err := session.Save(r, w); err != nil {
|
|
logging.Info("❌ Failed to save session: %v", err)
|
|
} else {
|
|
logging.Info("✅ Session saved for user: %s", username)
|
|
}
|
|
|
|
http.Redirect(w, r, "/", http.StatusSeeOther)
|
|
}
|
|
}
|
|
|
|
func Logout(w http.ResponseWriter, r *http.Request) {
|
|
session, _ := httpHelpers.GetSession(w, r)
|
|
|
|
for k := range session.Values {
|
|
delete(session.Values, k)
|
|
}
|
|
|
|
session.Values["flash"] = "You've been logged out."
|
|
session.Options.MaxAge = 5
|
|
|
|
err := session.Save(r, w)
|
|
if err != nil {
|
|
logging.Error("❌ Logout session save failed:", err)
|
|
}
|
|
http.Redirect(w, r, "/account/login", http.StatusSeeOther)
|
|
}
|
|
|
|
// ToDo: opted to inject the repo which is better for tests/DI rather than taking the *sql.DB
|
|
func Signup(usersRepo *usersStorage.UsersRepo) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method == http.MethodGet {
|
|
tmpl := templateHelpers.LoadTemplateFiles("signup.html", "templates/account/signup.html")
|
|
if err := tmpl.ExecuteTemplate(w, "layout", map[string]interface{}{
|
|
"csrfField": csrf.TemplateField(r), // ToDo: this is the olf Gorilla thing
|
|
}); err != nil {
|
|
logging.Info("❌ Template render error: %v", err)
|
|
http.Error(w, "Error rendering signup page", http.StatusInternalServerError)
|
|
}
|
|
return
|
|
}
|
|
|
|
username := r.FormValue("username")
|
|
password := r.FormValue("password")
|
|
|
|
if username == "" || password == "" {
|
|
http.Error(w, "Username and password are required", http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
hashed, err := securityHelpers.HashPassword(password)
|
|
if err != nil {
|
|
http.Error(w, "Server error", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
if err := usersRepo.Create(r.Context(), username, hashed, false); err != nil {
|
|
http.Error(w, "Could not create user", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
http.Redirect(w, r, "/account/login", http.StatusSeeOther)
|
|
}
|
|
}
|