package api_auth import ( "encoding/json" "fmt" "log/slog" "net/http" "git.oblat.lv/alex/triggerssmith/internal/auth" "git.oblat.lv/alex/triggerssmith/internal/server" ) type loginRequest struct { Username string `json:"username"` Password string `json:"password"` } type loginResponse struct { Token string `json:"accessToken"` } // @Summary Login // @Tags auth // @Produce json // @Param request body loginRequest true "Login request" // @Success 200 {object} loginResponse // @Failure 400 {object} server.ProblemDetails // @Failure 401 {object} server.ProblemDetails // @Router /api/auth/login [post] func (h *authHandler) handleLogin(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") var req loginRequest err := json.NewDecoder(r.Body).Decode(&req) if err != nil { server.WriteProblem(w, http.StatusBadRequest, "/errors/invalid-request-body", "Invalid request body", "Body is not valid JSON", r) return } tokens, err := h.a.Login(req.Username, req.Password) if err != nil { slog.Error("Login failed", "error", err.Error()) switch err { case auth.ErrInvalidUsername: server.WriteProblem(w, http.StatusUnauthorized, "/errors/auth/invalid-credentials", "Invalid credentials", fmt.Sprintf("User with username %s not found", req.Username), r) case auth.ErrInvalidPassword: server.WriteProblem(w, http.StatusUnauthorized, "/errors/auth/invalid-credentials", "Invalid credentials", fmt.Sprintf("Invalid password for user %s", req.Username), r) default: server.WriteProblem(w, http.StatusInternalServerError, "/errors/internal-server-error", "Internal Server Error", "unexpected error", r) } return } setRefreshCookie(w, tokens.Refresh, h.cfg.Auth.RefreshTokenTTL, false) _ = json.NewEncoder(w).Encode(loginResponse{Token: tokens.Access}) }