Fixed bug with session handling

This commit is contained in:
Logan 2024-09-27 14:37:49 -05:00
parent 0e7d1a43e2
commit c0b826afa8
9 changed files with 132 additions and 95 deletions

1
db.json Normal file
View file

@ -0,0 +1 @@
{"xterminate18181@gmail.com":{"email":"xterminate18181@gmail.com","password":"123","account-created":"2024-09-27T05:39:11.331520582-05:00","last-login":"2024-09-27T05:39:11.331520621-05:00"}}

5
go.mod
View file

@ -4,4 +4,7 @@ go 1.23
require github.com/gorilla/sessions v1.4.0
require github.com/gorilla/securecookie v1.1.2 // indirect
require (
github.com/gorilla/mux v1.8.1 // indirect
github.com/gorilla/securecookie v1.1.2 // indirect
)

2
go.sum
View file

@ -1,5 +1,7 @@
github.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0=
github.com/google/gofuzz v1.2.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY=
github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ=
github.com/gorilla/securecookie v1.1.2 h1:YCIWL56dvtr73r6715mJs5ZvhtnY73hBvEF8kXD8ePA=
github.com/gorilla/securecookie v1.1.2/go.mod h1:NfCASbcHqRSY+3a8tlWJwsQap2VX5pwzwo4h3eOamfo=
github.com/gorilla/sessions v1.4.0 h1:kpIYOp/oi6MG/p5PgxApU8srsSw9tuFbt46Lt7auzqQ=

View file

@ -1,10 +1,10 @@
package main
import (
"crypto/rand"
"fmt"
"log"
"net/http"
"strings"
"github.com/gorilla/sessions"
)
@ -18,17 +18,8 @@ type Server struct {
}
func main() {
// Set up encryption for session tokens
fmt.Print("Generating encryption key... ")
secret := make([]byte, 32)
_, err := rand.Read(secret)
if err != nil {
fmt.Println("Error generating key:")
log.Fatal(err)
return
}
fmt.Println("Done!")
// Create server object
secret := []byte("super-secret-key")
server := Server{
Users: make(map[string]UserData),
Sessions: sessions.NewCookieStore(secret),
@ -36,10 +27,16 @@ func main() {
// Host static files
static_files := http.FileServer(http.Dir("static/"))
http.Handle("/", static_files)
// Response generated by code
http.HandleFunc("/handle-register", server.handle_register)
http.HandleFunc("/handle-login", server.handle_login)
// Redirect .html to clean URL
http.Handle("/register.html", http.RedirectHandler("/register", 301))
http.Handle("/login.html", http.RedirectHandler("/login", 301))
// Handle user authentication
http.HandleFunc("/register", server.handle_register)
http.HandleFunc("/login", server.handle_login)
http.HandleFunc("/logout", func(w http.ResponseWriter, r *http.Request) {
server.handle_logout(w, r)
http.Redirect(w, r, "/", http.StatusFound)
})
// Start web server at 127.0.0.1:8080
fmt.Printf("Listening to %s on port %s...\n", ADDRESS, PORT)
e := http.ListenAndServe(ADDRESS+":"+PORT, nil)

View file

@ -20,6 +20,9 @@
<li>
<a href="/login.html"> Login </a>
</li>
<li>
<a href="/logout"> Log Out </a>
</li>
</ul>
</body>
</html>

View file

@ -10,15 +10,15 @@
</head>
<body>
<div class="d-flex p-2 justify-content-center">
<form action = "/handle-login" method = "post">
<form method = "post">
<div class="mb-3">
<label for="exampleInputEmail1" class="form-label">Email address</label>
<input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp">
<input type="email" name="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp">
<div id="emailHelp" class="form-text">We'll never share your email with anyone else.</div>
</div>
<div class="mb-3">
<label for="exampleInputPassword1" class="form-label">Password</label>
<input type="password" class="form-control" id="exampleInputPassword1">
<input type="password" name="password" class="form-control" id="exampleInputPassword1">
</div>
<div class="mb-3 form-check">
<input type="checkbox" class="form-check-input" id="exampleCheck1">

View file

@ -10,18 +10,18 @@
</head>
<body>
<div class="d-flex p-2 justify-content-center align-items-center">
<form action="/handle-register" method="post">
<form method="post">
<div class="mb-3">
<label for="exampleInputEmail1" class="form-label">Email address</label>
<input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp">
<label for="email" class="form-label">Email address</label>
<input type="email" class="form-control" id="email" name="email" aria-describedby="emailHelp">
<div id="emailHelp" class="form-text">We'll never share your email with anyone else.</div>
</div>
<div class="mb-3">
<label for="exampleInputPassword1" class="form-label">Password</label>
<input type="password" class="form-control" id="exampleInputPassword1" required>
<label for="password" class="form-label">Password</label>
<input type="password" class="form-control" id="password" name="password" required>
</div>
<div class="mb-3 form-check">
<input type="checkbox" class="form-check-input" id="exampleCheck1" required>
<input type="checkbox" class="form-check-input" id="exampleCheck1">
<label class="form-check-label" for="exampleCheck1">Show Password</label>
</div>
<div class="fs-6">

View file

@ -1,7 +1,10 @@
package main
import (
"encoding/json"
"fmt"
"net/http"
"os"
"time"
)
@ -15,11 +18,12 @@ type UserData struct {
LastLogin time.Time `json:"last-login"`
}
// Handles requests to /login.html
func (s *Server) handle_login(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Forbidden", http.StatusForbidden)
return
}
switch r.Method {
case http.MethodGet:
http.ServeFile(w, r, "./static/register.html")
case http.MethodPost:
// Get data from form
email := r.FormValue("email")
password := r.FormValue("password")
@ -38,38 +42,44 @@ func (s *Server) handle_login(w http.ResponseWriter, r *http.Request) {
// Generate session
session, err := s.Sessions.Get(r, SESSION_COOKIE_NAME)
if err != nil {
http.Error(w, "Internal Error", http.StatusInternalServerError)
s.handle_logout(w, r)
http.Error(w, "Invalid session", http.StatusUnauthorized)
return
}
session.Values[SESSION_AUTH] = true
if err := session.Save(r, w); err != nil {
http.Error(w, "Internal Error", http.StatusInternalServerError)
return
}
session.Save(r, w)
// Update last-login on DB
user.LastLogin = time.Now()
s.Users[email] = user
// Redirect to index.html
http.Redirect(w, r, "/", http.StatusFound)
default:
http.Error(w, "Forbidden", http.StatusForbidden)
}
}
// Handles requests to /register.html
func (s *Server) handle_register(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Forbidden", http.StatusForbidden)
return
}
switch r.Method {
case http.MethodGet:
http.ServeFile(w, r, "./static/register.html")
case http.MethodPost:
// Get data from form
email := r.FormValue("email")
password := r.FormValue("password")
fmt.Println(r.Form)
// Check that this email is not already registered
if _, ok := s.Users[email]; ok {
fmt.Println("Already registered")
http.Error(w, "Forbidden", http.StatusForbidden)
return
}
// Generate session
session, err := s.Sessions.Get(r, SESSION_COOKIE_NAME)
// If session cookie invalid
if err != nil {
http.Error(w, "Internal Error", http.StatusInternalServerError)
s.handle_logout(w, r)
http.Error(w, "Invalid session", http.StatusUnauthorized)
return
}
// Save user information to DB
@ -82,10 +92,34 @@ func (s *Server) handle_register(w http.ResponseWriter, r *http.Request) {
// Make session valid
session.Values[SESSION_AUTH] = true
// Send session token to browser
if err := session.Save(r, w); err != nil {
http.Error(w, "Internal Error", http.StatusInternalServerError)
return
}
session.Save(r, w)
// Redirect to index.html
s.save_state()
http.Redirect(w, r, "/", http.StatusFound)
default:
http.Error(w, "Forbidden", http.StatusForbidden)
}
}
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 {
// Remove authorization
session.Values[SESSION_AUTH] = false
session.Save(r, w)
}
// Remove session cookie
http.SetCookie(w, &http.Cookie{
Name: SESSION_COOKIE_NAME,
MaxAge: -1,
})
}
func (s *Server) save_state() {
file, err := os.Create("db.json")
if err != nil {
panic(err)
}
defer file.Close()
json.NewEncoder(file).Encode(s.Users)
}

View file

@ -1,3 +0,0 @@
{
"users" = {}
}