Fixed session cookie not saving

This commit is contained in:
Logan 2024-09-29 19:05:16 -05:00
parent 7b3499558c
commit 91543c8a79
3 changed files with 19 additions and 2 deletions

View file

@ -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)

View file

@ -23,6 +23,9 @@
<li>
<a href="/logout"> Log Out </a>
</li>
<li>
<a href="/secret"> Secret </a>
</li>
</ul>
</body>
</html>

View file

@ -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 {