package handler import ( "context" "encoding/json" "log/slog" "net/http" "gitea.michaelthomson.dev/mthomson/habits/internal/auth/service" ) type Loginer interface { Login(ctx context.Context, email string, password string) (string, error) } type LoginRequest struct { Email string `json:"email"` Password string `json:"password"` } func HandleLogin(logger *slog.Logger, authService Loginer) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { ctx := r.Context() loginRequest := LoginRequest{} decoder := json.NewDecoder(r.Body) decoder.DisallowUnknownFields() err := decoder.Decode(&loginRequest) if err != nil { logger.ErrorContext(ctx, err.Error()) http.Error(w, "", http.StatusBadRequest) return } token, err := authService.Login(ctx, loginRequest.Email, loginRequest.Password) if err == service.ErrUnauthorized { http.Error(w, "", http.StatusUnauthorized) return } if err == service.ErrNotFound { http.Error(w, "", http.StatusUnauthorized) return } if err != nil { logger.ErrorContext(ctx, err.Error()) http.Error(w, "", http.StatusInternalServerError) return } cookie := http.Cookie{ Name: "token", Value: token, Path: "/", MaxAge: 3600, HttpOnly: true, Secure: false, SameSite: http.SameSiteLaxMode, } http.SetCookie(w, &cookie) w.WriteHeader(http.StatusOK) } }