The user_session is valid for 24 hours, but the session will be bumped if it has been over an hour since the last update. An hour was set as a deadline, so that we would not update the user_session rows too often.
73 lines
1.7 KiB
Go
73 lines
1.7 KiB
Go
package handlers
|
|
|
|
import (
|
|
"go-backend/internal/auth"
|
|
"go-backend/internal/database/sqlc"
|
|
"log"
|
|
"net/http"
|
|
)
|
|
|
|
type SignupRequest struct {
|
|
Username string
|
|
Password string
|
|
Email string
|
|
}
|
|
|
|
func (h *Handler) SignUpHandler(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method != http.MethodPost {
|
|
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
|
return
|
|
}
|
|
|
|
req := SignupRequest{
|
|
Username: r.PostFormValue("username"),
|
|
Password: r.PostFormValue("password"),
|
|
Email: r.PostFormValue("email"),
|
|
}
|
|
|
|
if req.Username == "" || req.Password == "" || req.Email == "" {
|
|
http.Error(w, "Invalid request body", http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
user, err := h.users.FindByUsername(r.Context(), req.Username)
|
|
|
|
if err != nil {
|
|
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
if user != nil {
|
|
http.Error(w, "Username already taken", http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
hashedPassword, err := auth.HashPassword(req.Password)
|
|
|
|
if err != nil {
|
|
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
user, err = h.users.CreateUser(r.Context(), sqlc.InsertUserParams{Username: req.Username, Email: req.Email, PasswordHash: hashedPassword})
|
|
|
|
if err != nil {
|
|
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
session, err := h.auth.CreateSession(r.Context(), user.ID)
|
|
|
|
if err != nil {
|
|
log.Printf("Error creating session: %v", err)
|
|
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
cookie := auth.NewSessionCookie(session.Token, false)
|
|
http.SetCookie(w, cookie)
|
|
|
|
w.Header().Set("HX-Redirect", "/")
|
|
w.WriteHeader(http.StatusOK)
|
|
w.Write([]byte("Success"))
|
|
}
|