From 91543c8a79f142278ae0bd561949e5b411014ca7 Mon Sep 17 00:00:00 2001 From: Logan Date: Sun, 29 Sep 2024 19:05:16 -0500 Subject: [PATCH] Fixed session cookie not saving --- server.go | 1 + static/index.html | 3 +++ users.go | 17 +++++++++++++++-- 3 files changed, 19 insertions(+), 2 deletions(-) diff --git a/server.go b/server.go index 3a89495..6b9f195 100644 --- a/server.go +++ b/server.go @@ -38,6 +38,7 @@ func main() { server.handle_logout(w, r) http.Redirect(w, r, "/", http.StatusFound) }) + http.HandleFunc("/secret", server.secret) // Start web server at 127.0.0.1:8080 fmt.Printf("Listening to %s on port %s...\n", ADDRESS, PORT) err := http.ListenAndServe(ADDRESS+":"+PORT, nil) diff --git a/static/index.html b/static/index.html index af83bfb..194bfda 100644 --- a/static/index.html +++ b/static/index.html @@ -23,6 +23,9 @@
  • Log Out
  • +
  • + Secret +
  • diff --git a/users.go b/users.go index ea0834d..450be15 100644 --- a/users.go +++ b/users.go @@ -72,7 +72,7 @@ func (s *Server) handle_login(w http.ResponseWriter, r *http.Request) { } now := time.Now() session.Values[SESSION_AUTH] = true - session.Values[SESSION_STARTED] = now + session.Values[SESSION_STARTED] = now.String() session.Save(r, w) // Update last-login on DB user.LastLogin = now @@ -125,7 +125,7 @@ func (s *Server) handle_register(w http.ResponseWriter, r *http.Request) { } // Make session valid session.Values[SESSION_AUTH] = true - session.Values[SESSION_STARTED] = now + session.Values[SESSION_STARTED] = now.String() // Send session token to browser session.Save(r, w) // Redirect to index.html @@ -136,6 +136,19 @@ func (s *Server) handle_register(w http.ResponseWriter, r *http.Request) { } } +func (s *Server) secret(w http.ResponseWriter, r *http.Request) { + session, _ := s.Sessions.Get(r, SESSION_COOKIE_NAME) + + // Check if user is authenticated + if auth, ok := session.Values[SESSION_AUTH].(bool); !ok || !auth { + http.Error(w, "Not logged in", http.StatusForbidden) + return + } + + // Print secret message + fmt.Fprintln(w, "Successfully logged in!") +} + func (s *Server) handle_logout(w http.ResponseWriter, r *http.Request) { // If session exists if session, err := s.Sessions.Get(r, SESSION_COOKIE_NAME); err == nil {