package httpapi import ( "errors" "net/http" "strings" "time" postgresstore "knowledge-governance/internal/platform/postgres" ) const defaultSessionTTL = 12 * time.Hour type loginRequest struct { Username string `json:"username"` Password string `json:"password"` } func (config Config) handleLogin(w http.ResponseWriter, r *http.Request) { var input loginRequest if err := decodeStrictJSON(r, &input); err != nil || input.Username == "" || input.Password == "" { writeJSON(w, http.StatusBadRequest, map[string]string{"error": "username and password are required"}) return } outcome, err := config.Auth.Store.Login(r.Context(), strings.TrimSpace(input.Username), input.Password, r.UserAgent(), config.Now().UTC(), config.Auth.SessionTTL) switch { case errors.Is(err, postgresstore.ErrAuthInvalidCredential): writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "invalid username or password"}) case errors.Is(err, postgresstore.ErrAuthLocked): writeJSON(w, http.StatusTooManyRequests, map[string]string{"error": "account temporarily locked, try again later"}) case errors.Is(err, postgresstore.ErrAuthUserDisabled): writeJSON(w, http.StatusForbidden, map[string]string{"error": "account is disabled"}) case err != nil: writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "login failed"}) default: ttl := config.Auth.SessionTTL if ttl <= 0 { ttl = defaultSessionTTL } config.Auth.setSessionCookie(w, outcome.SessionToken, config.Now().UTC().Add(ttl)) writeJSON(w, http.StatusOK, map[string]any{"data": userPayload(outcome.User)}) } } func userPayload(user postgresstore.AuthUser) map[string]any { payload := map[string]any{ "id": user.ID, "username": user.Username, "display_name": user.DisplayName, "role": user.Role, "state": user.State, "must_change_password": user.MustChangePassword, } if user.LastLoginAt != nil { payload["last_login_at"] = user.LastLoginAt.UTC().Format(time.RFC3339) } return payload } func (config Config) handleLogout(w http.ResponseWriter, r *http.Request) { if identity, ok := sessionFrom(r.Context()); ok && identity.SessionID != "" { _ = config.Auth.Store.Logout(r.Context(), identity.SessionID, config.Now().UTC()) } config.Auth.clearSessionCookie(w) writeJSON(w, http.StatusOK, map[string]any{"data": map[string]string{"status": "logged_out"}}) } func (config Config) handleMe(w http.ResponseWriter, r *http.Request) { identity, ok := sessionFrom(r.Context()) if !ok { writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "authentication required"}) return } writeJSON(w, http.StatusOK, map[string]any{"data": map[string]any{ "id": identity.UserID, "username": identity.Username, "display_name": identity.DisplayName, "role": identity.Role, "must_change_password": identity.MustChangePassword, }}) } type changePasswordRequest struct { CurrentPassword string `json:"current_password"` NewPassword string `json:"new_password"` } func (config Config) handleChangePassword(w http.ResponseWriter, r *http.Request) { identity, ok := sessionFrom(r.Context()) if !ok { writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "authentication required"}) return } var input changePasswordRequest if err := decodeStrictJSON(r, &input); err != nil || input.CurrentPassword == "" || len(input.NewPassword) < 8 { writeJSON(w, http.StatusBadRequest, map[string]string{"error": "current_password and new_password (min 8 chars) are required"}) return } err := config.Auth.Store.ChangePassword(r.Context(), identity.UserID, input.CurrentPassword, input.NewPassword, config.Now().UTC()) switch { case errors.Is(err, postgresstore.ErrAuthInvalidCredential): writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "current password is incorrect"}) case errors.Is(err, postgresstore.ErrAuthInvalidUser): writeJSON(w, http.StatusBadRequest, map[string]string{"error": "new password must differ from the old one"}) case err != nil: writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "password change failed"}) default: // ChangePassword revoked every session including this one; re-login // with the new password so a forced first-login change keeps the // operator inside the app instead of bouncing to the login screen. outcome, loginErr := config.Auth.Store.Login(r.Context(), identity.Username, input.NewPassword, r.UserAgent(), config.Now().UTC(), config.Auth.SessionTTL) if loginErr == nil { ttl := config.Auth.SessionTTL if ttl <= 0 { ttl = defaultSessionTTL } config.Auth.setSessionCookie(w, outcome.SessionToken, config.Now().UTC().Add(ttl)) } writeJSON(w, http.StatusOK, map[string]any{"data": map[string]bool{"changed": true}}) } } func (config Config) authRoutes(mux *http.ServeMux) { mux.HandleFunc("POST /api/v1/auth/login", config.handleLogin) mux.HandleFunc("POST /api/v1/auth/logout", config.handleLogout) mux.HandleFunc("GET /api/v1/auth/me", config.handleMe) mux.HandleFunc("POST /api/v1/auth/change-password", config.handleChangePassword) }