make better login and admin session server side smooth
This commit is contained in:
@@ -75,12 +75,42 @@ func main() {
|
||||
mux.HandleFunc("GET /42", func(w http.ResponseWriter, r *http.Request) { http.ServeFile(w, r, "./static/42.html") })
|
||||
mux.HandleFunc("GET /secret", func(w http.ResponseWriter, r *http.Request) { http.ServeFile(w, r, "./static/secret.html") })
|
||||
mux.HandleFunc("GET /favicon.ico", func(w http.ResponseWriter, r *http.Request) { http.ServeFile(w, r, "./static/icon.png") })
|
||||
mux.HandleFunc("GET /login", func(w http.ResponseWriter, r *http.Request) { http.ServeFile(w, r, "./static/login.html") })
|
||||
mux.HandleFunc("GET /login", func(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
cookie, err := r.Cookie("session")
|
||||
if err == nil {
|
||||
sessionMu.RLock()
|
||||
expiry, ok := sessionStore[cookie.Value]
|
||||
sessionMu.RUnlock()
|
||||
// had session, but invalid
|
||||
if !ok || time.Now().After(expiry) {
|
||||
sessionMu.Lock()
|
||||
delete(sessionStore, cookie.Value)
|
||||
sessionMu.Unlock()
|
||||
} else { // valid session
|
||||
http.Redirect(w, r, "/admin", http.StatusSeeOther)
|
||||
}
|
||||
}
|
||||
|
||||
http.ServeFile(w, r, "./static/login.html")
|
||||
})
|
||||
|
||||
mux.HandleFunc("GET /admin", requireAuth(func(w http.ResponseWriter, r *http.Request) {
|
||||
http.ServeFile(w, r, "./static/admin.html")
|
||||
}))
|
||||
|
||||
mux.HandleFunc("GET /logout", requireAuth(func(w http.ResponseWriter, r *http.Request) {
|
||||
cookie, err := r.Cookie("session")
|
||||
if err == nil {
|
||||
// delete session cookie token
|
||||
sessionMu.Lock()
|
||||
delete(sessionStore, cookie.Value)
|
||||
sessionMu.Unlock()
|
||||
}
|
||||
|
||||
http.Redirect(w, r, "/", http.StatusSeeOther)
|
||||
}))
|
||||
|
||||
mux.HandleFunc("POST /newsletter/subscribe", func(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
Email string `json:"email"`
|
||||
@@ -149,7 +179,7 @@ func main() {
|
||||
HttpOnly: true,
|
||||
Secure: true,
|
||||
SameSite: http.SameSiteLaxMode,
|
||||
Expires: time.Now().Add(12 * time.Hour),
|
||||
Expires: time.Now().Add(48 * time.Hour),
|
||||
})
|
||||
|
||||
// htmx reads this header and does the redirect client-side
|
||||
|
||||
Reference in New Issue
Block a user