Add session management for user authentication

This commit is contained in:
bronku 2025-03-21 23:13:14 +01:00
parent e235e3d8a8
commit ab662bd4b8
3 changed files with 45 additions and 4 deletions

View file

@ -4,6 +4,7 @@ import (
_ "embed"
"fmt"
"net/http"
"time"
)
//go:embed login.html
@ -13,6 +14,11 @@ var loginPage string
var wrongPassword string
type Authenticator struct {
sessions map[string]token
}
func New() Authenticator {
return Authenticator{sessions: make(map[string]token)}
}
func (a *Authenticator) login(w http.ResponseWriter, r *http.Request) {
@ -34,9 +40,16 @@ func (a *Authenticator) login(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, wrongPassword)
return
}
key := generateKey()
a.sessions[key] = token{userName: login, created: time.Now(), lastAccess: time.Now()}
c := http.Cookie{
Name: "token",
Value: "good",
Name: "token",
Value: key,
HttpOnly: true,
// #todo (in prod) uncomment this line
//Secure: true,
SameSite: http.SameSiteStrictMode,
Path: "/",
}
http.SetCookie(w, &c)
http.Redirect(w, r, "/", http.StatusFound)
@ -48,11 +61,18 @@ func (a *Authenticator) Authenticate(in http.HandlerFunc) http.HandlerFunc {
a.login(w, r)
return
}
if _, err := r.Cookie("token"); err != nil {
fmt.Println("user not logged in")
c, err := r.Cookie("token")
if err != nil {
http.Redirect(w, r, "/login", http.StatusSeeOther)
return
}
value, ok := a.sessions[c.Value]
if !ok || time.Since(value.lastAccess) > time.Hour*24 || time.Since(value.lastAccess) > time.Hour*240 {
http.Redirect(w, r, "/login", http.StatusSeeOther)
return
}
value.lastAccess = time.Now()
a.sessions[c.Value] = value
in(w, r)
}
}

19
auth/token.go Normal file
View file

@ -0,0 +1,19 @@
package auth
import (
"crypto/rand"
"encoding/base64"
"time"
)
type token struct {
userName string
created time.Time
lastAccess time.Time
}
func generateKey() string {
key := [32]byte{}
rand.Read(key[:])
return base64.StdEncoding.EncodeToString(key[:])
}

View file

@ -25,6 +25,8 @@ func main() {
log.Fatal("can't open the databse", err)
}
a = auth.New()
http.HandleFunc("GET /order/", logger(a.Authenticate(h.form)))
http.HandleFunc("GET /", logger(a.Authenticate(h.index)))
http.HandleFunc("POST /", logger(a.Authenticate(h.addOrder)))