golang-template/internal/handlers/login.go
Leo 43219268e9 feat: Add Sliding expiration for user_sessions
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.
2026-08-17 23:47:11 +03:00

83 lines
1.9 KiB
Go

package handlers
import (
"log"
"net/http"
"go-backend/internal/auth"
)
type LoginRequest struct {
Username string
Password string
}
func (h *Handler) LoginHandler(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
http.Error(w, "Invalid request body", http.StatusBadRequest)
return
}
req := LoginRequest{
Username: r.PostFormValue("username"),
Password: r.PostFormValue("password"),
}
if req.Username == "" || req.Password == "" {
http.Error(w, "Invalid request body", http.StatusBadRequest)
return
}
user, err := h.users.FindByUsername(r.Context(), req.Username)
if err != nil {
log.Printf("Error finding user: %v", err)
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
if user == nil {
http.Error(w, "Invalid username", http.StatusBadRequest)
return
}
if !auth.VerifyPassword(user.PasswordHash, req.Password) {
http.Error(w, "Invalid username or password", http.StatusBadRequest)
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"))
}
func (h *Handler) LogoutHandler(w http.ResponseWriter, r *http.Request) {
cookie, err := r.Cookie("session")
if err != nil {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
err = h.auth.DeleteSession(r.Context(), cookie.Value)
if err != nil {
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
http.SetCookie(w, auth.NewSessionCookie("", true))
w.Header().Set("HX-Redirect", "/")
w.WriteHeader(http.StatusOK)
w.Write([]byte("Success"))
}