Finally get login working.
This commit is contained in:
@@ -2,6 +2,7 @@ package handlers
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"html/template"
|
"html/template"
|
||||||
|
"log"
|
||||||
"net/http"
|
"net/http"
|
||||||
"synlotto-website/helpers"
|
"synlotto-website/helpers"
|
||||||
"synlotto-website/models"
|
"synlotto-website/models"
|
||||||
@@ -26,7 +27,11 @@ func Login(w http.ResponseWriter, r *http.Request) {
|
|||||||
context := helpers.TemplateContext(w, r)
|
context := helpers.TemplateContext(w, r)
|
||||||
context["csrfField"] = csrf.TemplateField(r)
|
context["csrfField"] = csrf.TemplateField(r)
|
||||||
|
|
||||||
tmpl.ExecuteTemplate(w, "layout", context)
|
err := tmpl.ExecuteTemplate(w, "layout", context)
|
||||||
|
if err != nil {
|
||||||
|
log.Println("❌ Template render error:", err)
|
||||||
|
http.Error(w, "Error rendering login page", http.StatusInternalServerError)
|
||||||
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -40,34 +45,55 @@ func Login(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
session, _ := helpers.GetSession(w, r)
|
session, _ := helpers.GetSession(w, r)
|
||||||
session.Options.MaxAge = -1
|
|
||||||
session.Save(r, w)
|
|
||||||
|
|
||||||
remember := r.FormValue("remember") == "on"
|
for k := range session.Values {
|
||||||
|
delete(session.Values, k)
|
||||||
newSession, _ := helpers.GetSession(w, r)
|
|
||||||
newSession.Values["user_id"] = user.Id
|
|
||||||
newSession.Values["last_activity"] = time.Now()
|
|
||||||
|
|
||||||
if remember {
|
|
||||||
newSession.Options.MaxAge = 60 * 60 * 24 * 30 // 30 days
|
|
||||||
} else {
|
|
||||||
newSession.Options.MaxAge = 0
|
|
||||||
}
|
}
|
||||||
|
|
||||||
newSession.Save(r, w)
|
session.Values["user_id"] = user.Id
|
||||||
|
session.Values["last_activity"] = time.Now()
|
||||||
|
|
||||||
|
remember := r.FormValue("remember") == "on"
|
||||||
|
if remember {
|
||||||
|
session.Options.MaxAge = 60 * 60 * 24 * 30
|
||||||
|
} else {
|
||||||
|
session.Options.MaxAge = 0
|
||||||
|
}
|
||||||
|
|
||||||
|
err := session.Save(r, w)
|
||||||
|
if err != nil {
|
||||||
|
log.Println("❌ Failed to save session:", err)
|
||||||
|
} else {
|
||||||
|
log.Printf("✅ Login saved: user_id=%d, maxAge=%d", user.Id, session.Options.MaxAge)
|
||||||
|
for _, c := range r.Cookies() {
|
||||||
|
log.Printf("🍪 Cookie after login: %s = %s", c.Name, c.Value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if user == nil || !helpers.CheckPasswordHash(user.PasswordHash, password) {
|
||||||
|
models.LogLoginAttempt(username, false)
|
||||||
|
http.Error(w, "Invalid credentials", http.StatusUnauthorized)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
models.LogLoginAttempt(username, true)
|
||||||
|
|
||||||
http.Redirect(w, r, "/", http.StatusSeeOther)
|
http.Redirect(w, r, "/", http.StatusSeeOther)
|
||||||
}
|
}
|
||||||
|
|
||||||
func Logout(w http.ResponseWriter, r *http.Request) {
|
func Logout(w http.ResponseWriter, r *http.Request) {
|
||||||
session, _ := helpers.GetSession(w, r)
|
session, _ := helpers.GetSession(w, r)
|
||||||
session.Options.MaxAge = -1
|
|
||||||
session.Save(r, w)
|
|
||||||
|
|
||||||
newSession, _ := helpers.GetSession(w, r)
|
for k := range session.Values {
|
||||||
newSession.Values["flash"] = "You’ve been logged out"
|
delete(session.Values, k)
|
||||||
newSession.Save(r, w)
|
}
|
||||||
|
|
||||||
|
session.Values["flash"] = "You've been logged out."
|
||||||
|
session.Options.MaxAge = 5
|
||||||
|
|
||||||
|
err := session.Save(r, w)
|
||||||
|
if err != nil {
|
||||||
|
log.Println("❌ Logout session save failed:", err)
|
||||||
|
}
|
||||||
|
|
||||||
http.Redirect(w, r, "/login", http.StatusSeeOther)
|
http.Redirect(w, r, "/login", http.StatusSeeOther)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,27 +1,34 @@
|
|||||||
package helpers
|
package helpers
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"encoding/gob"
|
||||||
"net/http"
|
"net/http"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/gorilla/sessions"
|
"github.com/gorilla/sessions"
|
||||||
)
|
)
|
||||||
|
|
||||||
var store = sessions.NewCookieStore([]byte("super-secret-key")) // //ToDo make key global
|
var authKey = []byte("12345678901234567890123456789012") // ToDo: Make env var
|
||||||
|
var encryptKey = []byte("abcdefghijklmnopqrstuvwx12345678") // ToDo: Make env var
|
||||||
|
var sessionName = "synlotto-session"
|
||||||
|
var store = sessions.NewCookieStore(authKey, encryptKey)
|
||||||
|
|
||||||
const SessionTimeout = 30 * time.Minute
|
const SessionTimeout = 30 * time.Minute
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
|
gob.Register(time.Time{})
|
||||||
|
|
||||||
store.Options = &sessions.Options{
|
store.Options = &sessions.Options{
|
||||||
Path: "/",
|
Path: "/",
|
||||||
MaxAge: 86400 * 1,
|
MaxAge: 86400 * 1,
|
||||||
HttpOnly: true,
|
HttpOnly: true,
|
||||||
Secure: true,
|
Secure: false, // TODO: make env-configurable
|
||||||
SameSite: http.SameSiteStrictMode,
|
SameSite: http.SameSiteLaxMode,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func GetSession(w http.ResponseWriter, r *http.Request) (*sessions.Session, error) {
|
func GetSession(w http.ResponseWriter, r *http.Request) (*sessions.Session, error) {
|
||||||
return store.Get(r, "session-name")
|
return store.Get(r, sessionName)
|
||||||
}
|
}
|
||||||
|
|
||||||
func IsSessionExpired(session *sessions.Session) bool {
|
func IsSessionExpired(session *sessions.Session) bool {
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package helpers
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"html/template"
|
"html/template"
|
||||||
|
"log"
|
||||||
"net/http"
|
"net/http"
|
||||||
"synlotto-website/models"
|
"synlotto-website/models"
|
||||||
)
|
)
|
||||||
@@ -37,10 +38,18 @@ func TemplateContext(w http.ResponseWriter, r *http.Request) map[string]interfac
|
|||||||
}
|
}
|
||||||
|
|
||||||
var currentUser *models.User
|
var currentUser *models.User
|
||||||
if userId, ok := session.Values["user_id"].(int); ok {
|
|
||||||
currentUser = models.GetUserByID(userId)
|
switch v := session.Values["user_id"].(type) {
|
||||||
|
case int:
|
||||||
|
currentUser = models.GetUserByID(v)
|
||||||
|
case int64:
|
||||||
|
currentUser = models.GetUserByID(int(v))
|
||||||
|
default:
|
||||||
|
currentUser = nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
log.Printf("🧪 TemplateContext user: %#v", currentUser)
|
||||||
|
|
||||||
return map[string]interface{}{
|
return map[string]interface{}{
|
||||||
"Flash": flash,
|
"Flash": flash,
|
||||||
"User": currentUser,
|
"User": currentUser,
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ package models
|
|||||||
import (
|
import (
|
||||||
"database/sql"
|
"database/sql"
|
||||||
"log"
|
"log"
|
||||||
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
type User struct {
|
type User struct {
|
||||||
@@ -47,5 +48,21 @@ func GetUserByID(id int) *User {
|
|||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
log.Printf("📦 Looking up user ID %d", id)
|
||||||
return &user
|
return &user
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func LogLoginAttempt(username string, success bool) {
|
||||||
|
_, err := db.Exec("INSERT INTO login_audit (username, success, timestamp) VALUES (?, ?, ?)",
|
||||||
|
username, boolToInt(success), time.Now().Format(time.RFC3339))
|
||||||
|
if err != nil {
|
||||||
|
log.Println("❌ Failed to log login:", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func boolToInt(b bool) int {
|
||||||
|
if b {
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|||||||
@@ -62,5 +62,17 @@ func InitDB(filepath string) *sql.DB {
|
|||||||
log.Fatal("❌ Failed to create Users table:", err)
|
log.Fatal("❌ Failed to create Users table:", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
createAuditLogTable := `
|
||||||
|
CREATE TABLE IF NOT EXISTS auditlog (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
username TEXT,
|
||||||
|
success INTEGER,
|
||||||
|
timestamp TEXT
|
||||||
|
);`
|
||||||
|
|
||||||
|
if _, err := db.Exec(createAuditLogTable); err != nil {
|
||||||
|
log.Fatal("❌ Failed to create Users table:", err)
|
||||||
|
}
|
||||||
|
|
||||||
return db
|
return db
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,4 @@
|
|||||||
{{ define "content" }}
|
{{ define "content" }}
|
||||||
{{ if .Flash }}
|
|
||||||
<p style="color: green;">{{ .Flash }}</p>
|
|
||||||
{{ end }}
|
|
||||||
<h2>Login</h2>
|
<h2>Login</h2>
|
||||||
<form method="POST" action="/login">
|
<form method="POST" action="/login">
|
||||||
{{ .csrfField }}
|
{{ .csrfField }}
|
||||||
|
|||||||
Reference in New Issue
Block a user