golang-template/internal/handlers/login.go

72 lines
1.6 KiB
Go

package handlers
import (
"encoding/json"
"log"
"net/http"
"go-backend/internal/auth"
)
type LoginRequest struct {
Username string `json:"username"`
Password string `json:"password"`
}
func (h *Handler) LoginHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
var req LoginRequest
decoder := json.NewDecoder(r.Body)
err := decoder.Decode(&req)
if err != nil {
http.Error(w, "Invalid request body", http.StatusBadRequest)
return
}
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 := &http.Cookie{
Name: "session",
Value: session.Token,
HttpOnly: true,
SameSite: http.SameSiteLaxMode,
MaxAge: 86400, // 24 hours
Path: "/",
}
http.SetCookie(w, cookie)
w.WriteHeader(http.StatusOK)
w.Write([]byte("Success"))
}