mirror of
https://github.com/adanrsantos/ThePlaceHolders.git
synced 2024-12-16 14:20:39 -06:00
Fixed bug with session handling
This commit is contained in:
parent
0e7d1a43e2
commit
c0b826afa8
1
db.json
Normal file
1
db.json
Normal 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
5
go.mod
|
@ -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
2
go.sum
|
@ -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=
|
||||
|
|
27
server.go
27
server.go
|
@ -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)
|
||||
|
|
|
@ -14,11 +14,14 @@
|
|||
</h1>
|
||||
<ul>
|
||||
<li>
|
||||
<a href="/register.html"> Register </a>
|
||||
<a href="/register.html"> Register </a>
|
||||
</li>
|
||||
|
||||
<li>
|
||||
<a href="/login.html"> Login </a>
|
||||
<a href="/login.html"> Login </a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="/logout"> Log Out </a>
|
||||
</li>
|
||||
</ul>
|
||||
</body>
|
||||
|
|
|
@ -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">
|
||||
|
|
|
@ -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">
|
||||
|
|
164
users.go
164
users.go
|
@ -1,7 +1,10 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
"time"
|
||||
)
|
||||
|
||||
|
@ -15,77 +18,108 @@ 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 {
|
||||
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")
|
||||
// Get user from database
|
||||
user, ok := s.Users[email]
|
||||
// If user does not exist
|
||||
if !ok {
|
||||
http.Error(w, "Forbidden", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
// If password does not match
|
||||
if password != user.Password {
|
||||
http.Error(w, "Forbidden", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
// Generate session
|
||||
session, err := s.Sessions.Get(r, SESSION_COOKIE_NAME)
|
||||
if err != nil {
|
||||
s.handle_logout(w, r)
|
||||
http.Error(w, "Invalid session", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
session.Values[SESSION_AUTH] = true
|
||||
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)
|
||||
return
|
||||
}
|
||||
// Get data from form
|
||||
email := r.FormValue("email")
|
||||
password := r.FormValue("password")
|
||||
// Get user from database
|
||||
user, ok := s.Users[email]
|
||||
// If user does not exist
|
||||
if !ok {
|
||||
http.Error(w, "Forbidden", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
// If password does not match
|
||||
if password != user.Password {
|
||||
http.Error(w, "Forbidden", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
// Generate session
|
||||
session, err := s.Sessions.Get(r, SESSION_COOKIE_NAME)
|
||||
if err != nil {
|
||||
http.Error(w, "Internal Error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
session.Values[SESSION_AUTH] = true
|
||||
if err := session.Save(r, w); err != nil {
|
||||
http.Error(w, "Internal Error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
// Update last-login on DB
|
||||
user.LastLogin = time.Now()
|
||||
s.Users[email] = user
|
||||
// Redirect to index.html
|
||||
http.Redirect(w, r, "/", http.StatusFound)
|
||||
}
|
||||
|
||||
// Handles requests to /register.html
|
||||
func (s *Server) handle_register(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
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 {
|
||||
s.handle_logout(w, r)
|
||||
http.Error(w, "Invalid session", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
// Save user information to DB
|
||||
s.Users[email] = UserData{
|
||||
Email: email,
|
||||
Password: password,
|
||||
AccountCreated: time.Now(),
|
||||
LastLogin: time.Now(),
|
||||
}
|
||||
// Make session valid
|
||||
session.Values[SESSION_AUTH] = true
|
||||
// Send session token to browser
|
||||
session.Save(r, w)
|
||||
// Redirect to index.html
|
||||
s.save_state()
|
||||
http.Redirect(w, r, "/", http.StatusFound)
|
||||
default:
|
||||
http.Error(w, "Forbidden", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
// Get data from form
|
||||
email := r.FormValue("email")
|
||||
password := r.FormValue("password")
|
||||
// Check that this email is not already registered
|
||||
if _, ok := s.Users[email]; ok {
|
||||
http.Error(w, "Forbidden", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
// Generate session
|
||||
session, err := s.Sessions.Get(r, SESSION_COOKIE_NAME)
|
||||
if err != nil {
|
||||
http.Error(w, "Internal Error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
// Save user information to DB
|
||||
s.Users[email] = UserData{
|
||||
Email: email,
|
||||
Password: password,
|
||||
AccountCreated: time.Now(),
|
||||
LastLogin: time.Now(),
|
||||
}
|
||||
// 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
|
||||
}
|
||||
// Redirect to index.html
|
||||
http.Redirect(w, r, "/", http.StatusFound)
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
|
|
|
@ -1,3 +0,0 @@
|
|||
{
|
||||
"users" = {}
|
||||
}
|
Loading…
Reference in a new issue