Open source AI coding agent. Designed for large projects and real world tasks.
Go aiai-agentsai-developer-toolsai-toolsclicommand-linedeveloper-toolsgitgolanggpt-4llmopenaipolyglot-programmingterminalterminal-basedterminal-ui
more work on auth, trial, error handling across client/server
Dane Schneider296581721f2c
diff --git a/cli/api/errors.go b/cli/api/errors.gonew file mode 100644index 00000000..08709850--- /dev/null+++ b/cli/api/errors.go@@ -0,0 +1,32 @@+package api++import (+ "encoding/json"+ "log"+ "net/http"++ "github.com/plandex/plandex/shared"+)++func handleApiError(r *http.Response, errBody []byte) *shared.ApiError {+ // Check if the response is JSON+ if r.Header.Get("Content-Type") != "application/json" {+ return &shared.ApiError{+ Type: shared.ApiErrorTypeOther,+ Status: r.StatusCode,+ Msg: string(errBody),+ }+ }++ var apiError shared.ApiError+ if err := json.Unmarshal(errBody, &apiError); err != nil {+ log.Printf("Error unmarshalling JSON: %v\n", err)+ return &shared.ApiError{+ Type: shared.ApiErrorTypeOther,+ Status: r.StatusCode,+ Msg: string(errBody),+ }+ }++ return &apiError+}diff --git a/cli/api/methods.go b/cli/api/methods.goindex af656596..73135472 100644--- a/cli/api/methods.go+++ b/cli/api/methods.go@@ -12,308 +12,316 @@ import ("github.com/plandex/plandex/shared")-func (a *Api) StartTrial() (*shared.StartTrialResponse, error) {+func (a *Api) StartTrial() (*shared.StartTrialResponse, *shared.ApiError) {serverUrl := cloudApiHost + "/accounts/start_trial"resp, err := unauthenticatedClient.Post(serverUrl, "application/json", nil)if err != nil {- return nil, fmt.Errorf("error sending request: %v", err)+ return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error sending request: %v", err)}}defer resp.Body.Close()if resp.StatusCode >= 400 {errorBody, _ := io.ReadAll(resp.Body)- return nil, fmt.Errorf("error starting trial: %d - %s", resp.StatusCode, string(errorBody))+ apiErr := handleApiError(resp, errorBody)+ return nil, apiErr}var startTrialResponse shared.StartTrialResponseerr = json.NewDecoder(resp.Body).Decode(&startTrialResponse)if err != nil {- return nil, fmt.Errorf("error decoding response: %v", err)+ return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error decoding response: %v", err)}}return &startTrialResponse, nil}-func (a *Api) CreateProject(req shared.CreateProjectRequest) (*shared.CreateProjectResponse, error) {+func (a *Api) CreateProject(req shared.CreateProjectRequest) (*shared.CreateProjectResponse, *shared.ApiError) {serverUrl := getApiHost() + "/projects"reqBytes, err := json.Marshal(req)if err != nil {- return nil, fmt.Errorf("error marshalling request: %v", err)+ return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error marshalling request: %v", err)}}resp, err := authenticatedFastClient.Post(serverUrl, "application/json", bytes.NewBuffer(reqBytes))if err != nil {- return nil, fmt.Errorf("error sending request: %v", err)+ return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error sending request: %v", err)}}defer resp.Body.Close()if resp.StatusCode >= 400 {errorBody, _ := io.ReadAll(resp.Body)- return nil, fmt.Errorf("error creating project: %d - %s", resp.StatusCode, string(errorBody))+ apiErr := handleApiError(resp, errorBody)+ return nil, apiErr}var respBody shared.CreateProjectResponseerr = json.NewDecoder(resp.Body).Decode(&respBody)if err != nil {- return nil, fmt.Errorf("error decoding response: %v", err)+ return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error decoding response: %v", err)}}return &respBody, nil}-func (a *Api) ListProjects() ([]*shared.Project, error) {+func (a *Api) ListProjects() ([]*shared.Project, *shared.ApiError) {serverUrl := getApiHost() + "/projects"resp, err := authenticatedFastClient.Get(serverUrl)if err != nil {- return nil, fmt.Errorf("error sending request: %v", err)+ return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error sending request: %v", err)}}defer resp.Body.Close()if resp.StatusCode >= 400 {errorBody, _ := io.ReadAll(resp.Body)- return nil, fmt.Errorf("error listing projects: %d - %s", resp.StatusCode, string(errorBody))+ apiErr := handleApiError(resp, errorBody)+ return nil, apiErr}var projects []*shared.Projecterr = json.NewDecoder(resp.Body).Decode(&projects)if err != nil {- return nil, fmt.Errorf("error decoding response: %v", err)+ return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error decoding response: %v", err)}}return projects, nil}-func (a *Api) SetProjectPlan(projectId string, req shared.SetProjectPlanRequest) error {+func (a *Api) SetProjectPlan(projectId string, req shared.SetProjectPlanRequest) *shared.ApiError {serverUrl := fmt.Sprintf("%s/projects/%s/set_plan", getApiHost(), projectId)reqBytes, err := json.Marshal(req)if err != nil {- return fmt.Errorf("error marshalling request: %v", err)+ return &shared.ApiError{Msg: fmt.Sprintf("error marshalling request: %v", err)}}request, err := http.NewRequest(http.MethodPut, serverUrl, bytes.NewBuffer(reqBytes))if err != nil {- return fmt.Errorf("error creating request: %v", err)+ return &shared.ApiError{Msg: fmt.Sprintf("error creating request: %v", err)}}request.Header.Set("Content-Type", "application/json")resp, err := authenticatedFastClient.Do(request)if err != nil {- return fmt.Errorf("error sending request: %v", err)+ return &shared.ApiError{Msg: fmt.Sprintf("error sending request: %v", err)}}defer resp.Body.Close()if resp.StatusCode >= 400 {errorBody, _ := io.ReadAll(resp.Body)- return fmt.Errorf("error setting project plan: %d - %s", resp.StatusCode, string(errorBody))+ return handleApiError(resp, errorBody)}return nil}-func (a *Api) RenameProject(projectId string, req shared.RenameProjectRequest) error {+func (a *Api) RenameProject(projectId string, req shared.RenameProjectRequest) *shared.ApiError {serverUrl := fmt.Sprintf("%s/projects/%s/rename", getApiHost(), projectId)reqBytes, err := json.Marshal(req)if err != nil {- return fmt.Errorf("error marshalling request: %v", err)+ return &shared.ApiError{Msg: fmt.Sprintf("error marshalling request: %v", err)}}request, err := http.NewRequest(http.MethodPut, serverUrl, bytes.NewBuffer(reqBytes))if err != nil {- return fmt.Errorf("error creating request: %v", err)+ return &shared.ApiError{Msg: fmt.Sprintf("error creating request: %v", err)}}request.Header.Set("Content-Type", "application/json")resp, err := authenticatedFastClient.Do(request)if err != nil {- return fmt.Errorf("error sending request: %v", err)+ return &shared.ApiError{Msg: fmt.Sprintf("error sending request: %v", err)}}defer resp.Body.Close()if resp.StatusCode >= 400 {errorBody, _ := io.ReadAll(resp.Body)- return fmt.Errorf("error renaming project: %d - %s", resp.StatusCode, string(errorBody))+ return handleApiError(resp, errorBody)}return nil}-func (a *Api) ListPlans(projectId string) ([]*shared.Plan, error) {+func (a *Api) ListPlans(projectId string) ([]*shared.Plan, *shared.ApiError) {serverUrl := fmt.Sprintf("%s/projects/%s/plans", getApiHost(), projectId)resp, err := authenticatedFastClient.Get(serverUrl)if err != nil {- return nil, fmt.Errorf("error sending request: %v", err)+ return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error sending request: %v", err)}}defer resp.Body.Close()if resp.StatusCode >= 400 {errorBody, _ := io.ReadAll(resp.Body)- return nil, fmt.Errorf("error listing plans: %d - %s", resp.StatusCode, string(errorBody))+ apiErr := handleApiError(resp, errorBody)+ return nil, apiErr}var plans []*shared.Planerr = json.NewDecoder(resp.Body).Decode(&plans)if err != nil {- return nil, fmt.Errorf("error decoding response: %v", err)+ return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error decoding response: %v", err)}}return plans, nil}-func (a *Api) ListArchivedPlans(projectId string) ([]*shared.Plan, error) {+func (a *Api) ListArchivedPlans(projectId string) ([]*shared.Plan, *shared.ApiError) {serverUrl := fmt.Sprintf("%s/projects/%s/plans/archive", getApiHost(), projectId)resp, err := authenticatedFastClient.Get(serverUrl)if err != nil {- return nil, fmt.Errorf("error sending request: %v", err)+ return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error sending request: %v", err)}}defer resp.Body.Close()if resp.StatusCode >= 400 {errorBody, _ := io.ReadAll(resp.Body)- return nil, fmt.Errorf("error listing archived plans: %d - %s", resp.StatusCode, string(errorBody))+ apiErr := handleApiError(resp, errorBody)+ return nil, apiErr}var plans []*shared.Planerr = json.NewDecoder(resp.Body).Decode(&plans)if err != nil {- return nil, fmt.Errorf("error decoding response: %v", err)+ return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error decoding response: %v", err)}}return plans, nil}-func (a *Api) ListPlansRunning(projectId string) ([]*shared.Plan, error) {+func (a *Api) ListPlansRunning(projectId string) ([]*shared.Plan, *shared.ApiError) {serverUrl := fmt.Sprintf("%s/projects/%s/plans/ps", getApiHost(), projectId)resp, err := authenticatedFastClient.Get(serverUrl)if err != nil {- return nil, fmt.Errorf("error sending request: %v", err)+ return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error sending request: %v", err)}}defer resp.Body.Close()if resp.StatusCode >= 400 {errorBody, _ := io.ReadAll(resp.Body)- return nil, fmt.Errorf("error listing running plans: %d - %s", resp.StatusCode, string(errorBody))+ apiErr := handleApiError(resp, errorBody)+ return nil, apiErr}var plans []*shared.Planerr = json.NewDecoder(resp.Body).Decode(&plans)if err != nil {- return nil, fmt.Errorf("error decoding response: %v", err)+ return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error decoding response: %v", err)}}return plans, nil}-func (a *Api) CreatePlan(projectId string, req shared.CreatePlanRequest) (*shared.CreatePlanResponse, error) {+func (a *Api) CreatePlan(projectId string, req shared.CreatePlanRequest) (*shared.CreatePlanResponse, *shared.ApiError) {serverUrl := fmt.Sprintf("%s/projects/%s/plans", getApiHost(), projectId)reqBytes, err := json.Marshal(req)if err != nil {- return nil, fmt.Errorf("error marshalling request: %v", err)+ return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error marshalling request: %v", err)}}resp, err := authenticatedFastClient.Post(serverUrl, "application/json", bytes.NewBuffer(reqBytes))if err != nil {- return nil, fmt.Errorf("error sending request: %v", err)+ return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error sending request: %v", err)}}defer resp.Body.Close()if resp.StatusCode >= 400 {errorBody, _ := io.ReadAll(resp.Body)- return nil, fmt.Errorf("error creating plan: %d - %s", resp.StatusCode, string(errorBody))+ apiErr := handleApiError(resp, errorBody)+ return nil, apiErr}var respBody shared.CreatePlanResponseerr = json.NewDecoder(resp.Body).Decode(&respBody)if err != nil {- return nil, fmt.Errorf("error decoding response: %v", err)+ return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error decoding response: %v", err)}}return &respBody, nil}-func (a *Api) GetPlan(planId string) (*shared.Plan, error) {+func (a *Api) GetPlan(planId string) (*shared.Plan, *shared.ApiError) {serverUrl := fmt.Sprintf("%s/plans/%s", getApiHost(), planId)resp, err := authenticatedFastClient.Get(serverUrl)if err != nil {- return nil, fmt.Errorf("error sending request: %v", err)+ return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error sending request: %v", err)}}defer resp.Body.Close()if resp.StatusCode >= 400 {errorBody, _ := io.ReadAll(resp.Body)- return nil, fmt.Errorf("error getting plan: %d - %s", resp.StatusCode, string(errorBody))+ apiErr := handleApiError(resp, errorBody)+ return nil, apiErr}var plan shared.Planerr = json.NewDecoder(resp.Body).Decode(&plan)if err != nil {- return nil, fmt.Errorf("error decoding response: %v", err)+ return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error decoding response: %v", err)}}return &plan, nil}-func (a *Api) DeletePlan(planId string) error {+func (a *Api) DeletePlan(planId string) *shared.ApiError {serverUrl := fmt.Sprintf("%s/plans/%s", getApiHost(), planId)req, err := http.NewRequest(http.MethodDelete, serverUrl, nil)if err != nil {- return fmt.Errorf("error creating request: %v", err)+ return &shared.ApiError{Msg: fmt.Sprintf("error creating request: %v", err)}}resp, err := authenticatedFastClient.Do(req)if err != nil {- return fmt.Errorf("error sending request: %v", err)+ return &shared.ApiError{Msg: fmt.Sprintf("error sending request: %v", err)}}defer resp.Body.Close()if resp.StatusCode >= 400 {errorBody, _ := io.ReadAll(resp.Body)- return fmt.Errorf("error deleting plan: %d - %s", resp.StatusCode, string(errorBody))+ return handleApiError(resp, errorBody)}return nil}-func (a *Api) DeleteAllPlans(projectId string) error {+func (a *Api) DeleteAllPlans(projectId string) *shared.ApiError {serverUrl := fmt.Sprintf("%s/projects/%s/plans", getApiHost(), projectId)req, err := http.NewRequest(http.MethodDelete, serverUrl, nil)if err != nil {- return fmt.Errorf("error creating request: %v", err)+ return &shared.ApiError{Msg: fmt.Sprintf("error creating request: %v", err)}}resp, err := authenticatedFastClient.Do(req)if err != nil {- return fmt.Errorf("error sending request: %v", err)+ return &shared.ApiError{Msg: fmt.Sprintf("error sending request: %v", err)}}defer resp.Body.Close()if resp.StatusCode >= 400 {errorBody, _ := io.ReadAll(resp.Body)- return fmt.Errorf("error deleting all plans: %d - %s", resp.StatusCode, string(errorBody))+ return handleApiError(resp, errorBody)}return nil}-func (a *Api) TellPlan(planId string, req shared.TellPlanRequest, onStream types.OnStreamPlan) error {+func (a *Api) TellPlan(planId string, req shared.TellPlanRequest, onStream types.OnStreamPlan) *shared.ApiError {serverUrl := fmt.Sprintf("%s/plans/%s/tell", getApiHost(), planId)reqBytes, err := json.Marshal(req)if err != nil {- return fmt.Errorf("error marshalling request: %v", err)+ return &shared.ApiError{Msg: fmt.Sprintf("error marshalling request: %v", err)}}request, err := http.NewRequest(http.MethodPost, serverUrl, bytes.NewBuffer(reqBytes))if err != nil {- return fmt.Errorf("error creating request: %v", err)+ return &shared.ApiError{Msg: fmt.Sprintf("error creating request: %v", err)}}request.Header.Set("Content-Type", "application/json")@@ -326,12 +334,12 @@ func (a *Api) TellPlan(planId string, req shared.TellPlanRequest, onStream typesresp, err := client.Do(request)if err != nil {- return fmt.Errorf("error sending request: %v", err)+ return &shared.ApiError{Msg: fmt.Sprintf("error sending request: %v", err)}}if resp.StatusCode >= 400 {errorBody, _ := io.ReadAll(resp.Body)- return fmt.Errorf("error telling plan: %d - %s", resp.StatusCode, string(errorBody))+ return handleApiError(resp, errorBody)}if req.ConnectStream {@@ -342,23 +350,23 @@ func (a *Api) TellPlan(planId string, req shared.TellPlanRequest, onStream typesreturn nil}-func (a *Api) ConnectPlan(planId string, onStream types.OnStreamPlan) error {+func (a *Api) ConnectPlan(planId string, onStream types.OnStreamPlan) *shared.ApiError {serverUrl := fmt.Sprintf("%s/plans/%s/connect", getApiHost(), planId)req, err := http.NewRequest(http.MethodPatch, serverUrl, nil)if err != nil {- return fmt.Errorf("error creating request: %v", err)+ return &shared.ApiError{Msg: fmt.Sprintf("error creating request: %v", err)}}resp, err := authenticatedStreamingClient.Do(req)if err != nil {- return fmt.Errorf("error sending request: %v", err)+ return &shared.ApiError{Msg: fmt.Sprintf("error sending request: %v", err)}}defer resp.Body.Close()if resp.StatusCode >= 400 {errorBody, _ := io.ReadAll(resp.Body)- return fmt.Errorf("error connecting plan: %d - %s", resp.StatusCode, string(errorBody))+ return handleApiError(resp, errorBody)}connectPlanRespStream(resp.Body, onStream)@@ -366,201 +374,203 @@ func (a *Api) ConnectPlan(planId string, onStream types.OnStreamPlan) error {return nil}-func (a *Api) StopPlan(planId string) error {+func (a *Api) StopPlan(planId string) *shared.ApiError {serverUrl := fmt.Sprintf("%s/plans/%s/stop", getApiHost(), planId)req, err := http.NewRequest(http.MethodDelete, serverUrl, nil)if err != nil {- return fmt.Errorf("error creating request: %v", err)+ return &shared.ApiError{Msg: fmt.Sprintf("error creating request: %v", err)}}resp, err := authenticatedFastClient.Do(req)if err != nil {- return fmt.Errorf("error sending request: %v", err)+ return &shared.ApiError{Msg: fmt.Sprintf("error sending request: %v", err)}}defer resp.Body.Close()if resp.StatusCode >= 400 {errorBody, _ := io.ReadAll(resp.Body)- return fmt.Errorf("error stopping plan: %d - %s", resp.StatusCode, string(errorBody))+ return handleApiError(resp, errorBody)}return nil}-func (a *Api) GetCurrentPlanState(planId string) (*shared.CurrentPlanState, error) {+func (a *Api) GetCurrentPlanState(planId string) (*shared.CurrentPlanState, *shared.ApiError) {serverUrl := fmt.Sprintf("%s/plans/%s/current_plan", getApiHost(), planId)resp, err := authenticatedFastClient.Get(serverUrl)if err != nil {- return nil, fmt.Errorf("error sending request: %v", err)+ return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error sending request: %v", err)}}defer resp.Body.Close()if resp.StatusCode >= 400 {errorBody, _ := io.ReadAll(resp.Body)- return nil, fmt.Errorf("error getting current plan state: %d - %s", resp.StatusCode, string(errorBody))+ apiErr := handleApiError(resp, errorBody)+ return nil, apiErr}var state shared.CurrentPlanStateerr = json.NewDecoder(resp.Body).Decode(&state)if err != nil {- return nil, fmt.Errorf("error decoding response: %v", err)+ return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error decoding response: %v", err)}}return &state, nil}-func (a *Api) ApplyPlan(planId string) error {+func (a *Api) ApplyPlan(planId string) *shared.ApiError {serverUrl := fmt.Sprintf("%s/plans/%s/apply", getApiHost(), planId)req, err := http.NewRequest(http.MethodPatch, serverUrl, nil)if err != nil {- return fmt.Errorf("error creating request: %v", err)+ return &shared.ApiError{Msg: fmt.Sprintf("error creating request: %v", err)}}resp, err := authenticatedFastClient.Do(req)if err != nil {- return fmt.Errorf("error sending request: %v", err)+ return &shared.ApiError{Msg: fmt.Sprintf("error sending request: %v", err)}}defer resp.Body.Close()if resp.StatusCode >= 400 {errorBody, _ := io.ReadAll(resp.Body)- return fmt.Errorf("error applying plan: %d - %s", resp.StatusCode, string(errorBody))+ return handleApiError(resp, errorBody)}return nil}-func (a *Api) ArchivePlan(planId string) error {+func (a *Api) ArchivePlan(planId string) *shared.ApiError {serverUrl := fmt.Sprintf("%s/plans/%s/archive", getApiHost(), planId)req, err := http.NewRequest(http.MethodPatch, serverUrl, nil)if err != nil {- return fmt.Errorf("error creating request: %v", err)+ return &shared.ApiError{Msg: fmt.Sprintf("error creating request: %v", err)}}resp, err := authenticatedFastClient.Do(req)if err != nil {- return fmt.Errorf("error sending request: %v", err)+ return &shared.ApiError{Msg: fmt.Sprintf("error sending request: %v", err)}}defer resp.Body.Close()if resp.StatusCode >= 400 {errorBody, _ := io.ReadAll(resp.Body)- return fmt.Errorf("error archiving plan: %d - %s", resp.StatusCode, string(errorBody))+ return handleApiError(resp, errorBody)}return nil}-func (a *Api) RejectAllChanges(planId string) error {+func (a *Api) RejectAllChanges(planId string) *shared.ApiError {serverUrl := fmt.Sprintf("%s/plans/%s/reject_all", getApiHost(), planId)req, err := http.NewRequest(http.MethodPatch, serverUrl, nil)if err != nil {- return fmt.Errorf("error creating request: %v", err)+ return &shared.ApiError{Msg: fmt.Sprintf("error creating request: %v", err)}}resp, err := authenticatedFastClient.Do(req)if err != nil {- return fmt.Errorf("error sending request: %v", err)+ return &shared.ApiError{Msg: fmt.Sprintf("error sending request: %v", err)}}defer resp.Body.Close()if resp.StatusCode >= 400 {errorBody, _ := io.ReadAll(resp.Body)- return fmt.Errorf("error rejecting all changes: %d - %s", resp.StatusCode, string(errorBody))+ return handleApiError(resp, errorBody)}return nil}-func (a *Api) RejectResult(planId, resultId string) error {+func (a *Api) RejectResult(planId, resultId string) *shared.ApiError {serverUrl := fmt.Sprintf("%s/plans/%s/results/%s/reject", getApiHost(), planId, resultId)req, err := http.NewRequest(http.MethodPatch, serverUrl, nil)if err != nil {- return fmt.Errorf("error creating request: %v", err)+ return &shared.ApiError{Msg: fmt.Sprintf("error creating request: %v", err)}}resp, err := authenticatedFastClient.Do(req)if err != nil {- return fmt.Errorf("error sending request: %v", err)+ return &shared.ApiError{Msg: fmt.Sprintf("error sending request: %v", err)}}defer resp.Body.Close()if resp.StatusCode >= 400 {errorBody, _ := io.ReadAll(resp.Body)- return fmt.Errorf("error rejecting result: %d - %s", resp.StatusCode, string(errorBody))+ return handleApiError(resp, errorBody)}return nil}-func (a *Api) RejectReplacement(planId, resultId, replacementId string) error {+func (a *Api) RejectReplacement(planId, resultId, replacementId string) *shared.ApiError {serverUrl := fmt.Sprintf("%s/plans/%s/results/%s/replacements/%s/reject", getApiHost(), planId, resultId, replacementId)req, err := http.NewRequest(http.MethodPatch, serverUrl, nil)if err != nil {- return fmt.Errorf("error creating request: %v", err)+ return &shared.ApiError{Msg: fmt.Sprintf("error creating request: %v", err)}}resp, err := authenticatedFastClient.Do(req)if err != nil {- return fmt.Errorf("error sending request: %v", err)+ return &shared.ApiError{Msg: fmt.Sprintf("error sending request: %v", err)}}defer resp.Body.Close()if resp.StatusCode >= 400 {errorBody, _ := io.ReadAll(resp.Body)- return fmt.Errorf("error rejecting replacement: %d - %s", resp.StatusCode, string(errorBody))+ return handleApiError(resp, errorBody)}return nil}-func (a *Api) LoadContext(planId string, req shared.LoadContextRequest) (*shared.LoadContextResponse, error) {+func (a *Api) LoadContext(planId string, req shared.LoadContextRequest) (*shared.LoadContextResponse, *shared.ApiError) {serverUrl := fmt.Sprintf("%s/plans/%s/context", getApiHost(), planId)reqBytes, err := json.Marshal(req)if err != nil {- return nil, fmt.Errorf("error marshalling request: %v", err)+ return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error marshalling request: %v", err)}}// use the slow client since we may be uploading relatively large filesresp, err := authenticatedSlowClient.Post(serverUrl, "application/json", bytes.NewBuffer(reqBytes))if err != nil {- return nil, fmt.Errorf("error sending request: %v", err)+ return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error sending request: %v", err)}}defer resp.Body.Close()if resp.StatusCode >= 400 {errorBody, _ := io.ReadAll(resp.Body)- return nil, fmt.Errorf("error loading context: %d - %s", resp.StatusCode, string(errorBody))+ apiErr := handleApiError(resp, errorBody)+ return nil, apiErr}var loadContextResponse shared.LoadContextResponseerr = json.NewDecoder(resp.Body).Decode(&loadContextResponse)if err != nil {- return nil, fmt.Errorf("error decoding response: %v", err)+ return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error decoding response: %v", err)}}return &loadContextResponse, nil}-func (a *Api) UpdateContext(planId string, req shared.UpdateContextRequest) (*shared.UpdateContextResponse, error) {+func (a *Api) UpdateContext(planId string, req shared.UpdateContextRequest) (*shared.UpdateContextResponse, *shared.ApiError) {serverUrl := fmt.Sprintf("%s/plans/%s/context", getApiHost(), planId)reqBytes, err := json.Marshal(req)if err != nil {- return nil, fmt.Errorf("error marshalling request: %v", err)+ return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error marshalling request: %v", err)}}request, err := http.NewRequest(http.MethodPut, serverUrl, bytes.NewBuffer(reqBytes))if err != nil {- return nil, fmt.Errorf("error creating request: %v", err)+ return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error creating request: %v", err)}}request.Header.Set("Content-Type", "application/json")@@ -568,157 +578,504 @@ func (a *Api) UpdateContext(planId string, req shared.UpdateContextRequest) (*sh// use the slow client since we may be uploading relatively large filesresp, err := authenticatedSlowClient.Do(request)if err != nil {- return nil, fmt.Errorf("error sending request: %v", err)+ return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error sending request: %v", err)}}defer resp.Body.Close()if resp.StatusCode >= 400 {errorBody, _ := io.ReadAll(resp.Body)- return nil, fmt.Errorf("error loading context: %d - %s", resp.StatusCode, string(errorBody))+ apiErr := handleApiError(resp, errorBody)+ return nil, apiErr}var updateContextResponse shared.UpdateContextResponseerr = json.NewDecoder(resp.Body).Decode(&updateContextResponse)if err != nil {- return nil, fmt.Errorf("error decoding response: %v", err)+ return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error decoding response: %v", err)}}return &updateContextResponse, nil}-func (a *Api) DeleteContext(planId string, req shared.DeleteContextRequest) (*shared.DeleteContextResponse, error) {+func (a *Api) DeleteContext(planId string, req shared.DeleteContextRequest) (*shared.DeleteContextResponse, *shared.ApiError) {serverUrl := fmt.Sprintf("%s/plans/%s/context", getApiHost(), planId)reqBytes, err := json.Marshal(req)if err != nil {- return nil, fmt.Errorf("error marshalling request: %v", err)+ return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error marshalling request: %v", err)}}request, err := http.NewRequest(http.MethodDelete, serverUrl, bytes.NewBuffer(reqBytes))if err != nil {- return nil, fmt.Errorf("error creating request: %v", err)+ return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error creating request: %v", err)}}request.Header.Set("Content-Type", "application/json")resp, err := authenticatedFastClient.Do(request)if err != nil {- return nil, fmt.Errorf("error sending request: %v", err)+ return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error sending request: %v", err)}}defer resp.Body.Close()if resp.StatusCode >= 400 {errorBody, _ := io.ReadAll(resp.Body)- return nil, fmt.Errorf("error deleting context: %d - %s", resp.StatusCode, string(errorBody))+ apiErr := handleApiError(resp, errorBody)+ return nil, apiErr}var deleteContextResponse shared.DeleteContextResponseerr = json.NewDecoder(resp.Body).Decode(&deleteContextResponse)if err != nil {- return nil, fmt.Errorf("error decoding response: %v", err)+ return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error decoding response: %v", err)}}return &deleteContextResponse, nil}-func (a *Api) ListContext(planId string) ([]*shared.Context, error) {+func (a *Api) ListContext(planId string) ([]*shared.Context, *shared.ApiError) {serverUrl := fmt.Sprintf("%s/plans/%s/context", getApiHost(), planId)resp, err := authenticatedFastClient.Get(serverUrl)if err != nil {- return nil, fmt.Errorf("error sending request: %v", err)+ return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error sending request: %v", err)}}defer resp.Body.Close()if resp.StatusCode >= 400 {errorBody, _ := io.ReadAll(resp.Body)- return nil, fmt.Errorf("error listing context: %d - %s", resp.StatusCode, string(errorBody))+ apiErr := handleApiError(resp, errorBody)+ return nil, apiErr}var contexts []*shared.Contexterr = json.NewDecoder(resp.Body).Decode(&contexts)if err != nil {- return nil, fmt.Errorf("error decoding response: %v", err)+ return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error decoding response: %v", err)}}return contexts, nil}-func (a *Api) ListConvo(planId string) ([]*shared.ConvoMessage, error) {+func (a *Api) ListConvo(planId string) ([]*shared.ConvoMessage, *shared.ApiError) {serverUrl := fmt.Sprintf("%s/plans/%s/convo", getApiHost(), planId)resp, err := authenticatedFastClient.Get(serverUrl)if err != nil {- return nil, fmt.Errorf("error sending request: %v", err)+ return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error sending request: %v", err)}}defer resp.Body.Close()if resp.StatusCode >= 400 {errorBody, _ := io.ReadAll(resp.Body)- return nil, fmt.Errorf("error listing conversations: %d - %s", resp.StatusCode, string(errorBody))+ apiErr := handleApiError(resp, errorBody)+ return nil, apiErr}var convos []*shared.ConvoMessageerr = json.NewDecoder(resp.Body).Decode(&convos)if err != nil {- return nil, fmt.Errorf("error decoding response: %v", err)+ return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error decoding response: %v", err)}}return convos, nil}-func (a *Api) ListLogs(planId string) (*shared.LogResponse, error) {+func (a *Api) ListLogs(planId string) (*shared.LogResponse, *shared.ApiError) {serverUrl := fmt.Sprintf("%s/plans/%s/logs", getApiHost(), planId)resp, err := authenticatedFastClient.Get(serverUrl)if err != nil {- return nil, fmt.Errorf("error sending request: %v", err)+ return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error sending request: %v", err)}}defer resp.Body.Close()if resp.StatusCode >= 400 {errorBody, _ := io.ReadAll(resp.Body)- return nil, fmt.Errorf("error listing logs: %d - %s", resp.StatusCode, string(errorBody))+ apiErr := handleApiError(resp, errorBody)+ return nil, apiErr}var logs shared.LogResponseerr = json.NewDecoder(resp.Body).Decode(&logs)if err != nil {- return nil, fmt.Errorf("error decoding response: %v", err)+ return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error decoding response: %v", err)}}return &logs, nil}-func (a *Api) RewindPlan(planId string, req shared.RewindPlanRequest) (*shared.RewindPlanResponse, error) {+func (a *Api) RewindPlan(planId string, req shared.RewindPlanRequest) (*shared.RewindPlanResponse, *shared.ApiError) {serverUrl := fmt.Sprintf("%s/plans/%s/rewind", getApiHost(), planId)reqBytes, err := json.Marshal(req)if err != nil {- return nil, fmt.Errorf("error marshalling request: %v", err)+ return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error marshalling request: %v", err)}}request, err := http.NewRequest(http.MethodPatch, serverUrl, bytes.NewBuffer(reqBytes))if err != nil {- return nil, fmt.Errorf("error creating request: %v", err)+ return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error creating request: %v", err)}}request.Header.Set("Content-Type", "application/json")resp, err := authenticatedFastClient.Do(request)if err != nil {- return nil, fmt.Errorf("error sending request: %v", err)+ return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error sending request: %v", err)}}defer resp.Body.Close()if resp.StatusCode >= 400 {errorBody, _ := io.ReadAll(resp.Body)- return nil, fmt.Errorf("error rewinding plan: %d - %s", resp.StatusCode, string(errorBody))+ apiErr := handleApiError(resp, errorBody)+ return nil, apiErr}var rewindPlanResponse shared.RewindPlanResponseerr = json.NewDecoder(resp.Body).Decode(&rewindPlanResponse)if err != nil {- return nil, fmt.Errorf("error decoding response: %v", err)+ return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error decoding response: %v", err)}}return &rewindPlanResponse, nil}++func (a *Api) SignIn(req shared.SignInRequest, customHost string) (*shared.SessionResponse, *shared.ApiError) {+ serverUrl := customHost + "/accounts/sign_in"+ reqBytes, err := json.Marshal(req)+ if err != nil {+ return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error marshalling request: %v", err)}+ }++ resp, err := unauthenticatedClient.Post(serverUrl, "application/json", bytes.NewBuffer(reqBytes))+ if err != nil {+ return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error sending request: %v", err)}+ }+ defer resp.Body.Close()++ if resp.StatusCode >= 400 {+ errorBody, _ := io.ReadAll(resp.Body)+ apiErr := handleApiError(resp, errorBody)+ return nil, apiErr+ }++ var sessionResponse shared.SessionResponse+ err = json.NewDecoder(resp.Body).Decode(&sessionResponse)+ if err != nil {+ return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error decoding response: %v", err)}+ }++ return &sessionResponse, nil+}++func (a *Api) CreateAccount(req shared.CreateAccountRequest, customHost string) (*shared.SessionResponse, *shared.ApiError) {+ serverUrl := customHost + "/accounts"+ reqBytes, err := json.Marshal(req)+ if err != nil {+ return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error marshalling request: %v", err)}+ }++ resp, err := unauthenticatedClient.Post(serverUrl, "application/json", bytes.NewBuffer(reqBytes))+ if err != nil {+ return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error sending request: %v", err)}+ }+ defer resp.Body.Close()++ if resp.StatusCode >= 400 {+ errorBody, _ := io.ReadAll(resp.Body)+ apiErr := handleApiError(resp, errorBody)+ return nil, apiErr+ }++ var sessionResponse shared.SessionResponse+ err = json.NewDecoder(resp.Body).Decode(&sessionResponse)+ if err != nil {+ return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error decoding response: %v", err)}+ }++ return &sessionResponse, nil+}++func (a *Api) ConvertTrial(req shared.ConvertTrialRequest) (*shared.SessionResponse, *shared.ApiError) {+ serverUrl := getApiHost() + "/accounts/convert_trial"+ reqBytes, err := json.Marshal(req)+ if err != nil {+ return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error marshalling request: %v", err)}+ }++ resp, err := authenticatedFastClient.Post(serverUrl, "application/json", bytes.NewBuffer(reqBytes))+ if err != nil {+ return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error sending request: %v", err)}+ }+ defer resp.Body.Close()++ if resp.StatusCode >= 400 {+ errorBody, _ := io.ReadAll(resp.Body)+ apiErr := handleApiError(resp, errorBody)+ return nil, apiErr+ }++ var sessionResponse shared.SessionResponse+ err = json.NewDecoder(resp.Body).Decode(&sessionResponse)+ if err != nil {+ return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error decoding response: %v", err)}+ }++ return &sessionResponse, nil+}++func (a *Api) CreateOrg(req shared.CreateOrgRequest) (*shared.CreateOrgResponse, *shared.ApiError) {+ serverUrl := getApiHost() + "/orgs"+ reqBytes, err := json.Marshal(req)+ if err != nil {+ return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error marshalling request: %v", err)}+ }++ resp, err := authenticatedFastClient.Post(serverUrl, "application/json", bytes.NewBuffer(reqBytes))+ if err != nil {+ return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error sending request: %v", err)}+ }+ defer resp.Body.Close()++ if resp.StatusCode >= 400 {+ errorBody, _ := io.ReadAll(resp.Body)+ apiErr := handleApiError(resp, errorBody)+ return nil, apiErr+ }++ var createOrgResponse shared.CreateOrgResponse+ err = json.NewDecoder(resp.Body).Decode(&createOrgResponse)+ if err != nil {+ return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error decoding response: %v", err)}+ }++ return &createOrgResponse, nil+}++func (a *Api) ListOrgs() ([]*shared.Org, *shared.ApiError) {+ serverUrl := getApiHost() + "/orgs"+ resp, err := authenticatedFastClient.Get(serverUrl)+ if err != nil {+ return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error sending request: %v", err)}+ }+ defer resp.Body.Close()++ if resp.StatusCode >= 400 {+ errorBody, _ := io.ReadAll(resp.Body)+ apiErr := handleApiError(resp, errorBody)+ return nil, apiErr+ }++ var orgs []*shared.Org+ err = json.NewDecoder(resp.Body).Decode(&orgs)+ if err != nil {+ return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error decoding response: %v", err)}+ }++ return orgs, nil+}++func (a *Api) DeleteUser(userId string) *shared.ApiError {+ serverUrl := fmt.Sprintf("%s/orgs/users/%s", getApiHost(), userId)+ req, err := http.NewRequest(http.MethodDelete, serverUrl, nil)+ if err != nil {+ return &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error creating request: %v", err)}+ }++ resp, err := authenticatedFastClient.Do(req)+ if err != nil {+ return &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error sending request: %v", err)}+ }+ defer resp.Body.Close()++ if resp.StatusCode >= 400 {+ errorBody, _ := io.ReadAll(resp.Body)+ return handleApiError(resp, errorBody)+ }++ return nil+}++func (a *Api) InviteUser(req shared.InviteRequest) *shared.ApiError {+ serverUrl := getApiHost() + "/invites"+ reqBytes, err := json.Marshal(req)+ if err != nil {+ return &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error marshalling request: %v", err)}+ }++ resp, err := authenticatedFastClient.Post(serverUrl, "application/json", bytes.NewBuffer(reqBytes))+ if err != nil {+ return &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error sending request: %v", err)}+ }+ defer resp.Body.Close()++ if resp.StatusCode >= 400 {+ errorBody, _ := io.ReadAll(resp.Body)+ return handleApiError(resp, errorBody)+ }++ return nil+}++func (a *Api) ListPendingInvites() ([]*shared.Invite, *shared.ApiError) {+ serverUrl := getApiHost() + "/invites/pending"+ resp, err := authenticatedFastClient.Get(serverUrl)+ if err != nil {+ return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error sending request: %v", err)}+ }+ defer resp.Body.Close()++ if resp.StatusCode >= 400 {+ errorBody, _ := io.ReadAll(resp.Body)+ apiErr := handleApiError(resp, errorBody)+ return nil, apiErr+ }++ var invites []*shared.Invite+ err = json.NewDecoder(resp.Body).Decode(&invites)+ if err != nil {+ return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error decoding response: %v", err)}+ }++ return invites, nil+}++func (a *Api) ListAcceptedInvites() ([]*shared.Invite, *shared.ApiError) {+ serverUrl := getApiHost() + "/invites/accepted"+ resp, err := authenticatedFastClient.Get(serverUrl)+ if err != nil {+ return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error sending request: %v", err)}+ }+ defer resp.Body.Close()++ if resp.StatusCode >= 400 {+ errorBody, _ := io.ReadAll(resp.Body)+ apiErr := handleApiError(resp, errorBody)+ return nil, apiErr+ }++ var invites []*shared.Invite+ err = json.NewDecoder(resp.Body).Decode(&invites)+ if err != nil {+ return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error decoding response: %v", err)}+ }++ return invites, nil+}++func (a *Api) ListAllInvites() ([]*shared.Invite, *shared.ApiError) {+ serverUrl := getApiHost() + "/invites/all"+ resp, err := authenticatedFastClient.Get(serverUrl)+ if err != nil {+ return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error sending request: %v", err)}+ }+ defer resp.Body.Close()++ if resp.StatusCode >= 400 {+ errorBody, _ := io.ReadAll(resp.Body)+ apiErr := handleApiError(resp, errorBody)+ return nil, apiErr+ }++ var invites []*shared.Invite+ err = json.NewDecoder(resp.Body).Decode(&invites)+ if err != nil {+ return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error decoding response: %v", err)}+ }++ return invites, nil+}++func (a *Api) DeleteInvite(inviteId string) *shared.ApiError {+ serverUrl := fmt.Sprintf("%s/invites/%s", getApiHost(), inviteId)+ req, err := http.NewRequest(http.MethodDelete, serverUrl, nil)+ if err != nil {+ return &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error creating request: %v", err)}+ }++ resp, err := authenticatedFastClient.Do(req)+ if err != nil {+ return &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error sending request: %v", err)}+ }+ defer resp.Body.Close()++ if resp.StatusCode >= 400 {+ errorBody, _ := io.ReadAll(resp.Body)+ return handleApiError(resp, errorBody)+ }++ return nil+}++func (a *Api) CreateEmailVerification(email, customHost, userId string) (*shared.CreateEmailVerificationResponse, *shared.ApiError) {+ serverUrl := customHost + "/accounts/email_verifications"+ req := shared.CreateEmailVerificationRequest{Email: email, UserId: userId}+ reqBytes, err := json.Marshal(req)+ if err != nil {+ return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error marshalling request: %v", err)}+ }++ resp, err := unauthenticatedClient.Post(serverUrl, "application/json", bytes.NewBuffer(reqBytes))+ if err != nil {+ return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error sending request: %v", err)}+ }+ defer resp.Body.Close()++ if resp.StatusCode >= 400 {+ errorBody, _ := io.ReadAll(resp.Body)+ apiErr := handleApiError(resp, errorBody)+ return nil, apiErr+ }++ var verificationResponse shared.CreateEmailVerificationResponse+ err = json.NewDecoder(resp.Body).Decode(&verificationResponse)+ if err != nil {+ return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error decoding response: %v", err)}+ }++ return &verificationResponse, nil+}++func (a *Api) SignOut() *shared.ApiError {+ serverUrl := getApiHost() + "/accounts/sign_out"++ req, err := http.NewRequest(http.MethodPost, serverUrl, nil)+ if err != nil {+ return &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error creating request: %v", err)}+ }++ resp, err := authenticatedFastClient.Do(req)+ if err != nil {+ return &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error sending request: %v", err)}+ }+ defer resp.Body.Close()++ if resp.StatusCode >= 400 {+ errorBody, _ := io.ReadAll(resp.Body)+ return handleApiError(resp, errorBody)+ }++ return nil+}++func (a *Api) ListUsers() ([]*shared.User, *shared.ApiError) {+ serverUrl := getApiHost() + "/users"+ resp, err := authenticatedFastClient.Get(serverUrl)+ if err != nil {+ return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error sending request: %v", err)}+ }+ defer resp.Body.Close()++ if resp.StatusCode >= 400 {+ errorBody, _ := io.ReadAll(resp.Body)+ apiErr := handleApiError(resp, errorBody)+ return nil, apiErr+ }++ var users []*shared.User+ err = json.NewDecoder(resp.Body).Decode(&users)+ if err != nil {+ return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error decoding response: %v", err)}+ }++ return users, nil+}diff --git a/cli/auth/account.go b/cli/auth/account.gonew file mode 100644index 00000000..b3c2296e--- /dev/null+++ b/cli/auth/account.go@@ -0,0 +1,215 @@+package auth++import (+ "fmt"+ "plandex/term"+ "plandex/types"++ "github.com/plandex/plandex/shared"+)++const (+ AuthFreeTrialOption = "Start a free trial on Plandex Cloud (no email or credit card required)"+ AuthAccountOption = "Sign in, create an account, or accept an invite"+)++func promptInitialAuth() error {+ selected, err := term.SelectFromList("👋 Hey there! It looks like this is your first time using Plandex on this computer. What would you like to do?", []string{AuthFreeTrialOption, AuthAccountOption})++ if err != nil {+ return fmt.Errorf("error selecting auth option: %v", err)+ }++ switch selected {+ case AuthFreeTrialOption:+ err = startTrial()++ if err != nil {+ return fmt.Errorf("error starting trial: %v", err)+ }++ case AuthAccountOption:+ err = selectOrSignInOrCreate()++ if err != nil {+ return fmt.Errorf("error selecting or signing in to account: %v", err)+ }+ }++ return nil+}++const AddAccountOption = "Add another account"++func selectOrSignInOrCreate() error {+ accounts, err := loadAccounts()++ if err != nil {+ return fmt.Errorf("error loading accounts: %v", err)+ }++ if len(accounts) == 0 {+ err := promptSignInNewAccount()+ if err != nil {+ return fmt.Errorf("error signing in to new account: %v", err)+ }+ }++ var options []string+ for _, account := range accounts {+ options = append(options, fmt.Sprintf("<%s> %s", account.UserName, account.Email))+ }++ options = append(options, AddAccountOption)++ // either select from existing accounts or sign in/create account++ selectedOpt, err := term.SelectFromList("Select an account:", options)++ if err != nil {+ return fmt.Errorf("error selecting account: %v", err)+ }++ if selectedOpt == AddAccountOption {+ err := promptSignInNewAccount()+ if err != nil {+ return fmt.Errorf("error prompting for sign in to new account: %v", err)+ }+ return nil+ }++ var selected *types.ClientAccount+ for i, opt := range options {+ if selectedOpt == opt {+ selected = accounts[i]+ break+ }+ }++ if selected == nil {+ return fmt.Errorf("error selecting account: account not found")+ }++ orgs, apiErr := apiClient.ListOrgs()++ if apiErr != nil {+ return fmt.Errorf("error listing orgs: %v", apiErr.Msg)+ }++ orgId, orgName, err := resolveOrgAuth(orgs)++ if err != nil {+ return fmt.Errorf("error resolving org: %v", err)+ }++ err = setAuth(&types.ClientAuth{+ ClientAccount: *selected,+ OrgId: orgId,+ OrgName: orgName,+ })++ if err != nil {+ return fmt.Errorf("error setting auth: %v", err)+ }++ return nil+}++const (+ SignInCloudOption = "Plandex Cloud"+ SignInOtherOption = "Another host"+)++func promptSignInNewAccount() error {+ selected, err := term.SelectFromList("Use Plandex Cloud or another host?", []string{SignInCloudOption, SignInOtherOption})++ if err != nil {+ return fmt.Errorf("error selecting sign in option: %v", err)+ }++ var host string+ var email string++ if selected == SignInCloudOption {+ email, err = term.GetUserStringInput("Your email:")++ if err != nil {+ return fmt.Errorf("error prompting email: %v", err)+ }+ } else {+ host, err = term.GetUserStringInput("Host:")++ if err != nil {+ return fmt.Errorf("error prompting host: %v", err)+ }++ email, err = term.GetUserStringInput("Your email:")++ if err != nil {+ return fmt.Errorf("error prompting email: %v", err)+ }+ }++ hasAccount, pin, err := verifyEmail(email, host)++ if err != nil {+ return fmt.Errorf("error verifying email: %v", err)+ }++ if hasAccount {+ return signIn(email, pin, host)+ } else {+ return createAccount(email, pin, host)+ }+}++func verifyEmail(email, host string) (bool, string, error) {+ res, apiErr := apiClient.CreateEmailVerification(email, host, "")++ if apiErr != nil {+ return false, "", fmt.Errorf("error creating email verification: %v", apiErr.Msg)+ }++ pin, err := term.GetUserStringInput("You'll now receive a 6 character pin by email. Please enter it here:")++ if err != nil {+ return false, "", fmt.Errorf("error prompting pin: %v", err)+ }++ return res.HasAccount, pin, nil+}++func signIn(email, pin, host string) error {+ res, apiErr := apiClient.SignIn(shared.SignInRequest{+ Email: email,+ Pin: pin,+ }, host)++ if apiErr != nil {+ return fmt.Errorf("error signing in: %v", apiErr.Msg)+ }++ orgId, orgName, err := resolveOrgAuth(res.Orgs)++ if err != nil {+ return fmt.Errorf("error resolving org: %v", err)+ }++ err = setAuth(&types.ClientAuth{+ ClientAccount: types.ClientAccount{+ Email: res.Email,+ UserId: res.UserId,+ UserName: res.UserName,+ Token: res.Token,+ IsTrial: false,+ },+ OrgId: orgId,+ OrgName: orgName,+ })++ if err != nil {+ return fmt.Errorf("error setting auth: %v", err)+ }++ return nil+}diff --git a/cli/auth/api.go b/cli/auth/api.gonew file mode 100644index 00000000..3aed52c7--- /dev/null+++ b/cli/auth/api.go@@ -0,0 +1,41 @@+package auth++import (+ "encoding/base64"+ "encoding/json"+ "fmt"+ "net/http"+ "plandex/types"++ "github.com/plandex/plandex/shared"+)++var apiClient types.ApiClient++func SetApiClient(client types.ApiClient) {+ apiClient = client+}++func SetAuthHeader(req *http.Request) error {+ if Current == nil {+ return fmt.Errorf("error setting auth header: auth not loaded")+ }++ authHeader := shared.AuthHeader{+ Token: Current.Token,+ OrgId: Current.OrgId,+ }++ bytes, err := json.Marshal(authHeader)++ if err != nil {+ return fmt.Errorf("error marshalling auth header: %v", err)+ }++ // base64 encode+ token := base64.StdEncoding.EncodeToString(bytes)++ req.Header.Set("Authorization", "Bearer "+token)++ return nil+}diff --git a/cli/auth/auth.go b/cli/auth/auth.goindex 80dc4b6f..1e679b3c 100644--- a/cli/auth/auth.go+++ b/cli/auth/auth.go@@ -1,26 +1,18 @@package authimport (- "encoding/base64""encoding/json""fmt"- "net/http""os""plandex/fs"- "plandex/term""plandex/types"-- "github.com/plandex/plandex/shared")-var Current *types.ClientAuth-var apiClient types.ApiClient--func SetApiClient(client types.ApiClient) {- apiClient = client+func MustResolveAuthWithOrg() {+ MustResolveAuth(true)}-func MustResolveAuth() {+func MustResolveAuth(requireOrg bool) {if apiClient == nil {panic(fmt.Errorf("error resolving auth: api client not set"))}@@ -30,7 +22,7 @@ func MustResolveAuth() {if err != nil {if os.IsNotExist(err) {- err = promptAuth()+ err = promptInitialAuth()if err != nil {panic(fmt.Errorf("error resolving auth: %v", err))@@ -49,241 +41,58 @@ func MustResolveAuth() {}Current = &auth-}-func LoadAccounts() ([]*types.ClientAccount, error) {- bytes, err := os.ReadFile(fs.HomeAccountsPath)+ if requireOrg && Current.OrgId == "" {+ orgs, apiErr := apiClient.ListOrgs()- if err != nil {- if os.IsNotExist(err) {- // no accounts- return []*types.ClientAccount{}, nil- } else {- return nil, fmt.Errorf("error reading accounts.json: %v", err)+ if apiErr != nil {+ panic(fmt.Errorf("error listing orgs: %v", apiErr.Msg))}- }- var accounts []*types.ClientAccount- err = json.Unmarshal(bytes, &accounts)+ orgId, orgName, err := resolveOrgAuth(orgs)- if err != nil {- return nil, fmt.Errorf("error unmarshalling accounts.json: %v", err)- }-- return accounts, nil-}--func StoreAccountIfNew(acct *types.ClientAccount) error {- accounts, err := LoadAccounts()-- if err != nil {- return fmt.Errorf("error loading accounts: %v", err)- }-- for _, account := range accounts {- if account.UserId == acct.UserId {- return nil- }- }-- accounts = append(accounts, acct)-- bytes, err := json.Marshal(accounts)-- if err != nil {- return fmt.Errorf("error marshalling accounts: %v", err)- }-- err = os.WriteFile(fs.HomeAccountsPath, bytes, os.ModePerm)-- if err != nil {- return fmt.Errorf("error writing accounts: %v", err)- }-- return nil-}--func SetAuthHeader(req *http.Request) error {- if Current == nil {- return fmt.Errorf("error setting auth header: auth not loaded")- }-- authHeader := shared.AuthHeader{- Token: Current.Token,- OrgId: Current.OrgId,- }-- bytes, err := json.Marshal(authHeader)-- if err != nil {- return fmt.Errorf("error marshalling auth header: %v", err)- }-- // base64 encode- token := base64.StdEncoding.EncodeToString(bytes)-- req.Header.Set("Authorization", "Bearer "+token)-- return nil-}--func writeCurrentAuth() error {- if Current == nil {- return fmt.Errorf("error writing auth: auth not loaded")- }-- bytes, err := json.Marshal(Current)-- if err != nil {- return fmt.Errorf("error marshalling auth: %v", err)- }-- err = os.WriteFile(fs.HomeAuthPath, bytes, os.ModePerm)-- if err != nil {- return fmt.Errorf("error writing auth: %v", err)- }-- return nil-}--const (- AuthFreeTrialOption = "Start a free trial on Plandex Cloud"- AuthSignInOption = "Sign in to an existing account on Plandex Cloud or another host"- AuthCreateAccount = "Create a new account on Plandex Cloud or another host"-)--func promptAuth() error {- selected, err := term.SelectFromList("👋 Hey there! It looks like this is your first time using Plandex on this computer. What would you like to do?", []string{AuthFreeTrialOption, AuthSignInOption, AuthCreateAccount})-- if err != nil {- return fmt.Errorf("error selecting auth option: %v", err)- }-- switch selected {- case AuthFreeTrialOption:- err = startTrial()-- if err != nil {- return fmt.Errorf("error starting trial: %v", err)- }-- case AuthSignInOption:- // sign in- // TODO-- case AuthCreateAccount:- // create account- // TODO- }-- return nil-}--func signIn() error {- acccounts, err := LoadAccounts()-- if err != nil {- return fmt.Errorf("error loading accounts: %v", err)- }-- if len(acccounts) == 0 {- err := promptSignInNewAccount()if err != nil {- return fmt.Errorf("error signing in to new account: %v", err)+ panic(fmt.Errorf("error resolving org: %v", err))}- }-- var options []string- for _, account := range acccounts {- options = append(options, fmt.Sprintf("<%s> %s", account.UserName, account.Email))- }-- options = append(options, "Sign in to another account")-- // either select from existing accounts or prompt for email-- return nil-}--const (- SignInCloudOption = "Sign in to Plandex Cloud"- SignInOtherOption = "Sign in to another host"-)--func promptSignInNewAccount() error {-- selected, err := term.SelectFromList("You can sign in to an existing account on Plandex Cloud or another host.", []string{SignInCloudOption, SignInOtherOption})-- if err != nil {- return fmt.Errorf("error selecting sign in option: %v", err)- }- if selected == SignInCloudOption {- email, err := term.GetUserStringInput("Your email:")-- if err != nil {- return fmt.Errorf("error prompting email: %v", err)+ if orgId == "" {+ // still no org--exit now+ os.Exit(1)}- } else {- host, err := term.GetUserStringInput("Host:")- if err != nil {- return fmt.Errorf("error prompting host: %v", err)- }+ Current.OrgId = orgId+ Current.OrgName = orgName- email, err := term.GetUserStringInput("Your email:")+ err = writeCurrentAuth()if err != nil {- return fmt.Errorf("error prompting email: %v", err)+ panic(fmt.Errorf("error writing auth: %v", err))}-}-}-func createAccount() error {-- return nil}-func startTrial() error {- term.StartSpinner("🌟 Starting trial...")-- res, err := apiClient.StartTrial()-- if err != nil {- term.StopSpinner()- return fmt.Errorf("error starting trial: %v", err)+func RefreshInvalidToken() error {+ if Current == nil {+ return fmt.Errorf("error refreshing token: auth not loaded")}- term.StopSpinner()-- err = StoreAccountIfNew(&types.ClientAccount{- Email: res.Email,- UserId: res.UserId,- UserName: res.UserName,- Token: res.Token,- IsTrial: true,- })+ hasAccount, pin, err := verifyEmail(Current.Email, Current.Host)if err != nil {- return fmt.Errorf("error storing trial account: %v", err)- }-- Current = &types.ClientAuth{- Email: res.Email,- UserId: res.UserId,- UserName: res.UserName,- OrgId: res.OrgId,- OrgName: res.OrgName,- Token: res.Token,- IsTrial: true,+ return fmt.Errorf("error verifying email: %v", err)}- err = writeCurrentAuth()+ if hasAccount {+ return signIn(Current.Email, pin, Current.Host)+ } else {+ host := Current.Host+ if host == "" {+ host = "Plandex Cloud"+ }- if err != nil {- return fmt.Errorf("error writing auth: %v", err)+ fmt.Printf("🚨 Account %s not found on %s\n", Current.Email, host)+ os.Exit(1)}return nildiff --git a/cli/auth/org.go b/cli/auth/org.gonew file mode 100644index 00000000..336ab05a--- /dev/null+++ b/cli/auth/org.go@@ -0,0 +1,181 @@+package auth++import (+ "fmt"+ "plandex/term"+ "plandex/types"+ "strings"++ "github.com/plandex/plandex/shared"+)++func resolveOrgAuth(orgs []*shared.Org) (string, string, error) {+ var org *shared.Org+ var err error++ if len(orgs) == 0 {+ org, err = promptNoOrgs()++ if err != nil {+ return "", "", fmt.Errorf("error prompting no orgs: %v", err)+ }++ } else if len(orgs) == 1 {+ org = orgs[0]+ } else {+ org, err = selectOrg(orgs)++ if err != nil {+ return "", "", fmt.Errorf("error selecting org: %v", err)+ }+ }++ var (+ orgId string+ orgName string+ )++ if org != nil {+ orgId = org.Id+ orgName = org.Name+ }++ return orgId, orgName, nil+}++func createAccount(email, pin, host string) error {++ name, err := term.GetUserStringInput("Your name:")++ if err != nil {+ return fmt.Errorf("error prompting name: %v", err)+ }++ res, apiErr := apiClient.CreateAccount(shared.CreateAccountRequest{+ Email: email,+ UserName: name,+ Pin: pin,+ }, host)++ if apiErr != nil {+ return fmt.Errorf("error creating account: %v", apiErr.Msg)+ }++ err = setAuth(&types.ClientAuth{+ ClientAccount: types.ClientAccount{+ Email: res.Email,+ UserId: res.UserId,+ UserName: res.UserName,+ Token: res.Token,+ },+ })++ if err != nil {+ return fmt.Errorf("error setting auth: %v", err)+ }++ orgId, orgName, err := resolveOrgAuth(res.Orgs)++ if err != nil {+ return fmt.Errorf("error resolving org: %v", err)+ }++ Current.OrgId = orgId+ Current.OrgName = orgName++ err = writeCurrentAuth()++ if err != nil {+ return fmt.Errorf("error writing auth: %v", err)+ }++ return nil+}++func promptNoOrgs() (*shared.Org, error) {+ fmt.Println("🧐 You don't have access to any orgs yet.\n\nTo join an existing org, ask an admin to either invite you directly or give your whole email domain access.\n\nOtherwise, you can go ahead and create a new org.")++ shouldCreate, err := term.ConfirmYesNo("Create a new org now?")++ if err != nil {+ return nil, fmt.Errorf("error prompting create org: %v", err)+ }++ if shouldCreate {+ return createOrg()+ }++ return nil, nil+}++func createOrg() (*shared.Org, error) {+ name, err := term.GetUserStringInput("Org name:")+ if err != nil {+ return nil, fmt.Errorf("error prompting org name: %v", err)+ }++ autoAddDomainUsers, err := promptAutoAddUsersIfValid(Current.Email)++ if err != nil {+ return nil, fmt.Errorf("error prompting auto add domain users: %v", err)+ }++ res, apiErr := apiClient.CreateOrg(shared.CreateOrgRequest{+ Name: name,+ AutoAddDomainUsers: autoAddDomainUsers,+ })++ if apiErr != nil {+ return nil, fmt.Errorf("error creating org: %v", apiErr.Msg)+ }++ return &shared.Org{Id: res.Id, Name: name}, nil+}++func promptAutoAddUsersIfValid(email string) (bool, error) {+ userDomain := strings.Split(Current.Email, "@")[1]+ var autoAddDomainUsers bool+ var err error+ if !shared.IsEmailServiceDomain(userDomain) {+ autoAddDomainUsers, err = term.ConfirmYesNo(fmt.Sprintf("Do you want to allow any user with an email ending in @%s to auto-join this org?", userDomain))++ if err != nil {+ return false, err+ }+ }+ return autoAddDomainUsers, nil+}++const CreateOrgOption = "Create a new org"++func selectOrg(orgs []*shared.Org) (*shared.Org, error) {+ var options []string+ for _, org := range orgs {+ options = append(options, org.Name)+ }+ options = append(options, CreateOrgOption)++ selected, err := term.SelectFromList("Select an org:", options)++ if err != nil {+ return nil, fmt.Errorf("error selecting org: %v", err)+ }++ if selected == CreateOrgOption {+ return createOrg()+ }++ var selectedOrg *shared.Org+ for _, org := range orgs {+ if org.Name == selected {+ selectedOrg = org+ break+ }+ }++ if selectedOrg == nil {+ return nil, fmt.Errorf("error selecting org: org not found")+ }++ return selectedOrg, nil+}diff --git a/cli/auth/state.go b/cli/auth/state.gonew file mode 100644index 00000000..2c9c4009--- /dev/null+++ b/cli/auth/state.go@@ -0,0 +1,106 @@+package auth++import (+ "encoding/json"+ "fmt"+ "os"+ "plandex/fs"+ "plandex/types"+)++var Current *types.ClientAuth++func loadAccounts() ([]*types.ClientAccount, error) {+ bytes, err := os.ReadFile(fs.HomeAccountsPath)++ if err != nil {+ if os.IsNotExist(err) {+ // no accounts+ return []*types.ClientAccount{}, nil+ } else {+ return nil, fmt.Errorf("error reading accounts.json: %v", err)+ }+ }++ var accounts []*types.ClientAccount+ err = json.Unmarshal(bytes, &accounts)++ if err != nil {+ return nil, fmt.Errorf("error unmarshalling accounts.json: %v", err)+ }++ return accounts, nil+}++func setAuth(auth *types.ClientAuth) error {+ err := storeAccount(&auth.ClientAccount)++ if err != nil {+ return fmt.Errorf("error storing account: %v", err)+ }++ Current = auth++ err = writeCurrentAuth()++ if err != nil {+ return fmt.Errorf("error writing auth: %v", err)+ }++ return nil+}++func storeAccount(toStore *types.ClientAccount) error {+ accounts, err := loadAccounts()++ if err != nil {+ return fmt.Errorf("error loading accounts: %v", err)+ }++ found := false+ for i, account := range accounts {+ if account.UserId == toStore.UserId {+ accounts[i] = toStore+ found = true+ break+ }+ }++ if !found {+ accounts = append(accounts, toStore)+ }++ bytes, err := json.Marshal(accounts)++ if err != nil {+ return fmt.Errorf("error marshalling accounts: %v", err)+ }++ err = os.WriteFile(fs.HomeAccountsPath, bytes, os.ModePerm)++ if err != nil {+ return fmt.Errorf("error writing accounts: %v", err)+ }++ return nil+}++func writeCurrentAuth() error {+ if Current == nil {+ return fmt.Errorf("error writing auth: auth not loaded")+ }++ bytes, err := json.Marshal(Current)++ if err != nil {+ return fmt.Errorf("error marshalling auth: %v", err)+ }++ err = os.WriteFile(fs.HomeAuthPath, bytes, os.ModePerm)++ if err != nil {+ return fmt.Errorf("error writing auth: %v", err)+ }++ return nil+}diff --git a/cli/auth/trial.go b/cli/auth/trial.gonew file mode 100644index 00000000..a14ced12--- /dev/null+++ b/cli/auth/trial.go@@ -0,0 +1,107 @@+package auth++import (+ "fmt"+ "os"+ "plandex/term"+ "plandex/types"++ "github.com/plandex/plandex/shared"+)++func ConvertTrial() error {+ email, err := term.GetUserStringInput("Your email:")++ if err != nil {+ return fmt.Errorf("error prompting email: %v", err)+ }++ hasAccount, pin, err := verifyEmail(email, "")++ if err != nil {+ return fmt.Errorf("error verifying email: %v", err)+ }++ if hasAccount {+ fmt.Println("🚨 Can't convert a trial into an account that already exists")+ os.Exit(1)+ }++ name, err := term.GetUserStringInput("Your name:")++ if err != nil {+ return fmt.Errorf("error prompting name: %v", err)+ }++ orgName, err := term.GetUserStringInput("Org name:")++ if err != nil {+ return fmt.Errorf("error prompting org name: %v", err)+ }++ autoAddDomainUsers, err := promptAutoAddUsersIfValid(email)++ if err != nil {+ return fmt.Errorf("error prompting auto add domain users: %v", err)+ }++ res, apiErr := apiClient.ConvertTrial(shared.ConvertTrialRequest{+ Email: email,+ Pin: pin,+ UserName: name,+ OrgName: orgName,+ OrgAutoAddDomainUsers: autoAddDomainUsers,+ })++ if apiErr != nil {+ return fmt.Errorf("error converting trial: %v", apiErr)+ }++ err = setAuth(&types.ClientAuth{+ ClientAccount: types.ClientAccount{+ Email: res.Email,+ UserId: res.UserId,+ UserName: res.UserName,+ Token: res.Token,+ },+ OrgId: res.Orgs[0].Id,+ OrgName: res.Orgs[0].Id,+ })++ if err != nil {+ return fmt.Errorf("error setting auth: %v", err)+ }++ return nil+}++func startTrial() error {+ term.StartSpinner("🌟 Starting trial...")++ res, apiErr := apiClient.StartTrial()++ if apiErr != nil {+ term.StopSpinner()+ return fmt.Errorf("error starting trial: %v", apiErr.Msg)+ }++ term.StopSpinner()++ err := setAuth(&types.ClientAuth{+ ClientAccount: types.ClientAccount{+ Email: res.Email,+ UserId: res.UserId,+ UserName: res.UserName,+ Token: res.Token,+ IsTrial: true,+ },+ OrgId: res.OrgId,+ OrgName: res.OrgName,+ })++ if err != nil {+ return fmt.Errorf("error setting auth: %v", err)+ }++ return nil+}diff --git a/cli/changes_tui/model.go b/cli/changes_tui/model.goindex ef5232f7..06881134 100644--- a/cli/changes_tui/model.go+++ b/cli/changes_tui/model.go@@ -53,9 +53,9 @@ func (m changesUIModel) Init() tea.Cmd {}func initialModel() *changesUIModel {- currentPlan, err := api.Client.GetCurrentPlanState(lib.CurrentPlanId)- if err != nil {- err = fmt.Errorf("error getting current plan state: %v", err)+ currentPlan, apiErr := api.Client.GetCurrentPlanState(lib.CurrentPlanId)+ if apiErr != nil {+ err := fmt.Errorf("error getting current plan state: %v", apiErr.Msg)log.Println(err)panic(err)}diff --git a/cli/cmd/apply.go b/cli/cmd/apply.goindex 301feb5c..a743e4a7 100644--- a/cli/cmd/apply.go+++ b/cli/cmd/apply.go@@ -4,6 +4,7 @@ import ("fmt""os""plandex/api"+ "plandex/auth""plandex/lib""strconv"@@ -27,6 +28,7 @@ var applyCmd = &cobra.Command{}func apply(cmd *cobra.Command, args []string) error {+ auth.MustResolveAuthWithOrg()lib.MustResolveProject()var planId string@@ -51,10 +53,10 @@ func apply(cmd *cobra.Command, args []string) error {} else {var plan *shared.Plan- plans, err := api.Client.ListPlans(lib.CurrentProjectId)+ plans, apiErr := api.Client.ListPlans(lib.CurrentProjectId)- if err != nil {- fmt.Fprintln(os.Stderr, "Error getting plans:", err)+ if apiErr != nil {+ fmt.Fprintln(os.Stderr, "Error getting plans:", apiErr.Msg)os.Exit(1)}diff --git a/cli/cmd/cd.go b/cli/cmd/cd.goindex c027ddf6..859a53b8 100644--- a/cli/cmd/cd.go+++ b/cli/cmd/cd.go@@ -4,6 +4,7 @@ import ("fmt""os""plandex/api"+ "plandex/auth""plandex/lib""strconv""time"@@ -25,15 +26,16 @@ var cdCmd = &cobra.Command{}func cd(cmd *cobra.Command, args []string) {+ auth.MustResolveAuthWithOrg()lib.MustResolveProject()nameOrIdx := args[0]var plan *shared.Plan- plans, err := api.Client.ListPlans(lib.CurrentProjectId)+ plans, apiErr := api.Client.ListPlans(lib.CurrentProjectId)- if err != nil {- fmt.Fprintln(os.Stderr, "Error getting plans:", err)+ if apiErr != nil {+ fmt.Fprintln(os.Stderr, "Error getting plans:", apiErr.Msg)os.Exit(1)}diff --git a/cli/cmd/changes.go b/cli/cmd/changes.goindex 2a7aed3d..88a6d670 100644--- a/cli/cmd/changes.go+++ b/cli/cmd/changes.go@@ -3,6 +3,7 @@ package cmdimport ("fmt""os"+ "plandex/auth""plandex/changes_tui""plandex/lib"@@ -21,6 +22,7 @@ var changesCmd = &cobra.Command{}func changes(cmd *cobra.Command, args []string) {+ auth.MustResolveAuthWithOrg()lib.MustResolveProject()err := changes_tui.StartChangesUI()diff --git a/cli/cmd/clear.go b/cli/cmd/clear.goindex 3205c059..248bce37 100644--- a/cli/cmd/clear.go+++ b/cli/cmd/clear.go@@ -4,6 +4,7 @@ import ("fmt""os""plandex/api"+ "plandex/auth""plandex/lib""github.com/plandex/plandex/shared"@@ -18,6 +19,7 @@ var clearCmd = &cobra.Command{}func clearAllContext(cmd *cobra.Command, args []string) {+ auth.MustResolveAuthWithOrg()lib.MustResolveProject()if lib.CurrentPlanId == "" {diff --git a/cli/cmd/continue.go b/cli/cmd/continue.goindex f0d0a747..71f43cb8 100644--- a/cli/cmd/continue.go+++ b/cli/cmd/continue.go@@ -4,6 +4,7 @@ import ("fmt""os""plandex/api"+ "plandex/auth""plandex/lib"streamtui "plandex/stream_tui"@@ -31,20 +32,21 @@ func init() {}func next(cmd *cobra.Command, args []string) {+ auth.MustResolveAuthWithOrg()lib.MustResolveProject()lib.MustCheckOutdatedContextWithOutput()- err := api.Client.TellPlan(lib.CurrentPlanId, shared.TellPlanRequest{+ apiErr := api.Client.TellPlan(lib.CurrentPlanId, shared.TellPlanRequest{Prompt: continuePrompt,ConnectStream: !continueBg,}, lib.OnStreamPlan)- if err != nil {- fmt.Fprintln(os.Stderr, "Prompt error:", err)+ if apiErr != nil {+ fmt.Fprintln(os.Stderr, "Prompt error:", apiErr.Msg)return}if !continueBg {- err = streamtui.StartStreamUI()+ err := streamtui.StartStreamUI()if err != nil {fmt.Fprintln(os.Stderr, "Error starting stream UI:", err)diff --git a/cli/cmd/convo.go b/cli/cmd/convo.goindex 592b2837..5e56eee9 100644--- a/cli/cmd/convo.go+++ b/cli/cmd/convo.go@@ -4,6 +4,7 @@ import ("fmt""os""plandex/api"+ "plandex/auth""plandex/lib""plandex/term""strings"@@ -25,11 +26,12 @@ func init() {}func convo(cmd *cobra.Command, args []string) {+ auth.MustResolveAuthWithOrg()lib.MustResolveProject()- conversation, err := api.Client.ListConvo(lib.CurrentPlanId)- if err != nil {- fmt.Fprintln(os.Stderr, "Error loading conversation:", err)+ conversation, apiErr := api.Client.ListConvo(lib.CurrentPlanId)+ if apiErr != nil {+ fmt.Fprintln(os.Stderr, "Error loading conversation:", apiErr.Msg)return}diff --git a/cli/cmd/current.go b/cli/cmd/current.goindex 5a3c8b9e..3a92938c 100644--- a/cli/cmd/current.go+++ b/cli/cmd/current.go@@ -4,6 +4,7 @@ import ("fmt""os""plandex/api"+ "plandex/auth""plandex/format""plandex/lib""plandex/term"@@ -26,6 +27,7 @@ func init() {}func current(cmd *cobra.Command, args []string) {+ auth.MustResolveAuthWithOrg()lib.MustResolveProject()if lib.CurrentPlanId == "" {diff --git a/cli/cmd/delete_plan.go b/cli/cmd/delete_plan.goindex 65b3a0c3..c42c68c8 100644--- a/cli/cmd/delete_plan.go+++ b/cli/cmd/delete_plan.go@@ -6,6 +6,7 @@ import ("strconv""plandex/api"+ "plandex/auth""plandex/lib""github.com/fatih/color"@@ -30,6 +31,7 @@ var rmCmd = &cobra.Command{}func del(cmd *cobra.Command, args []string) {+ auth.MustResolveAuthWithOrg()lib.MustResolveProject()if all {@@ -40,10 +42,10 @@ func del(cmd *cobra.Command, args []string) {nameOrIdx := args[0]var plan *shared.Plan- plans, err := api.Client.ListPlans(lib.CurrentProjectId)+ plans, apiErr := api.Client.ListPlans(lib.CurrentProjectId)- if err != nil {- fmt.Fprintln(os.Stderr, "Error getting plans:", err)+ if apiErr != nil {+ fmt.Fprintln(os.Stderr, "Error getting plans:", apiErr.Msg)os.Exit(1)}@@ -71,10 +73,10 @@ func del(cmd *cobra.Command, args []string) {}}- err = api.Client.DeletePlan(plan.Id)+ apiErr = api.Client.DeletePlan(plan.Id)- if err != nil {- fmt.Fprintln(os.Stderr, "Error deleting plan:", err)+ if apiErr != nil {+ fmt.Fprintln(os.Stderr, "Error deleting plan:", apiErr.Msg)return}diff --git a/cli/cmd/load.go b/cli/cmd/load.goindex 7556d15c..ea5fab1f 100644--- a/cli/cmd/load.go+++ b/cli/cmd/load.go@@ -3,6 +3,7 @@ package cmdimport ("fmt""os"+ "plandex/auth""plandex/lib""plandex/term""plandex/types"@@ -32,6 +33,7 @@ func init() {}func contextLoad(cmd *cobra.Command, args []string) {+ auth.MustResolveAuthWithOrg()lib.MustResolveProject()if lib.CurrentPlanId == "" {diff --git a/cli/cmd/log.go b/cli/cmd/log.goindex d277d134..86bafa36 100644--- a/cli/cmd/log.go+++ b/cli/cmd/log.go@@ -3,6 +3,7 @@ package cmdimport ("fmt""plandex/api"+ "plandex/auth""plandex/lib""plandex/term"@@ -25,6 +26,7 @@ func init() {}func runLog(cmd *cobra.Command, args []string) {+ auth.MustResolveAuthWithOrg()lib.MustResolveProject()if lib.CurrentPlanId == "" {diff --git a/cli/cmd/ls.go b/cli/cmd/ls.goindex ca82b93d..a901654f 100644--- a/cli/cmd/ls.go+++ b/cli/cmd/ls.go@@ -4,6 +4,7 @@ import ("fmt""os""plandex/api"+ "plandex/auth""plandex/format""plandex/lib""plandex/term"@@ -22,6 +23,7 @@ var contextCmd = &cobra.Command{}func context(cmd *cobra.Command, args []string) {+ auth.MustResolveAuthWithOrg()lib.MustResolveProject()contexts, err := api.Client.ListContext(lib.CurrentPlanId)diff --git a/cli/cmd/new.go b/cli/cmd/new.goindex f6b2ba2f..30e06749 100644--- a/cli/cmd/new.go+++ b/cli/cmd/new.go@@ -32,17 +32,38 @@ func init() {}func new(cmd *cobra.Command, args []string) {- auth.MustResolveAuth()+ auth.MustResolveAuthWithOrg()lib.MustResolveProject()- res, err := api.Client.CreatePlan(lib.CurrentProjectId, shared.CreatePlanRequest{Name: name})+ res, apiErr := api.Client.CreatePlan(lib.CurrentProjectId, shared.CreatePlanRequest{Name: name})- if err != nil {- fmt.Fprintln(os.Stderr, "Error creating plan:", err)+ if apiErr != nil {+ if apiErr.Type == shared.ApiErrorTypeTrialPlansExceeded {+ fmt.Fprintf(os.Stderr, "🚨 You've reached the free trial limit of %d plans\n", apiErr.TrialPlansExceededError.MaxPlans)++ res, err := term.ConfirmYesNo("Upgrade trial now?")++ if err != nil {+ fmt.Fprintln(os.Stderr, "Error prompting upgrade trial:", err)+ return+ }++ if res {+ err := auth.ConvertTrial()+ if err != nil {+ fmt.Fprintln(os.Stderr, "Error converting trial:", err)+ return+ }+ }++ return+ }++ fmt.Fprintln(os.Stderr, "Error creating plan:", apiErr.Msg)return}- err = lib.SetCurrentPlan(res.Id)+ err := lib.SetCurrentPlan(res.Id)if err != nil {fmt.Fprintln(os.Stderr, "Error setting current plan:", err)diff --git a/cli/cmd/plans.go b/cli/cmd/plans.goindex 08e51c6f..04dfdc80 100644--- a/cli/cmd/plans.go+++ b/cli/cmd/plans.go@@ -6,6 +6,7 @@ import ("strconv""plandex/api"+ "plandex/auth""plandex/format""plandex/lib""plandex/term"@@ -27,6 +28,7 @@ var plansCmd = &cobra.Command{}func plans(cmd *cobra.Command, args []string) {+ auth.MustResolveAuthWithOrg()lib.MustResolveProject()plans, err := api.Client.ListPlans(lib.CurrentProjectId)diff --git a/cli/cmd/rewind.go b/cli/cmd/rewind.goindex 3ec62305..1eb0a9d6 100644--- a/cli/cmd/rewind.go+++ b/cli/cmd/rewind.go@@ -4,6 +4,7 @@ import ("fmt""os""plandex/api"+ "plandex/auth""plandex/lib""strconv"@@ -35,6 +36,7 @@ func init() {}func rewind(cmd *cobra.Command, args []string) {+ auth.MustResolveAuthWithOrg()lib.MustResolveProject()if lib.CurrentPlanId == "" {diff --git a/cli/cmd/rm.go b/cli/cmd/rm.goindex 51f991fd..fa8d0519 100644--- a/cli/cmd/rm.go+++ b/cli/cmd/rm.go@@ -5,6 +5,7 @@ import ("os""path/filepath""plandex/api"+ "plandex/auth""plandex/lib""github.com/plandex/plandex/shared"@@ -21,6 +22,7 @@ var contextRmCmd = &cobra.Command{}func contextRm(cmd *cobra.Command, args []string) {+ auth.MustResolveAuthWithOrg()lib.MustResolveProject()if lib.CurrentPlanId == "" {diff --git a/cli/cmd/tell.go b/cli/cmd/tell.goindex ccf107ba..f2add6a6 100644--- a/cli/cmd/tell.go+++ b/cli/cmd/tell.go@@ -6,6 +6,7 @@ import ("os""os/exec""plandex/api"+ "plandex/auth""plandex/lib"streamtui "plandex/stream_tui""plandex/term"@@ -39,6 +40,7 @@ func init() {}func tell(cmd *cobra.Command, args []string) {+ auth.MustResolveAuthWithOrg()lib.MustResolveProject()var prompt string@@ -133,12 +135,33 @@ func tell(cmd *cobra.Command, args []string) {}()}- err := api.Client.TellPlan(lib.CurrentPlanId, shared.TellPlanRequest{+ apiErr := api.Client.TellPlan(lib.CurrentPlanId, shared.TellPlanRequest{Prompt: prompt,ConnectStream: !tellBg,}, lib.OnStreamPlan)- if err != nil {- fmt.Fprintln(os.Stderr, "Prompt error:", err)+ if apiErr != nil {+ fmt.Fprintln(os.Stderr, "Prompt error:", apiErr.Msg)+ return+ }++ if apiErr.Type == shared.ApiErrorTypeTrialMessagesExceeded {+ fmt.Fprintf(os.Stderr, "🚨 You've reached the free trial limit of %d messages per plan\n", apiErr.TrialMessagesExceededError.MaxMessages)++ res, err := term.ConfirmYesNo("Upgrade now?")++ if err != nil {+ fmt.Fprintln(os.Stderr, "Error prompting upgrade trial:", err)+ return+ }++ if res {+ err := auth.ConvertTrial()+ if err != nil {+ fmt.Fprintln(os.Stderr, "Error converting trial:", err)+ return+ }+ }+return}diff --git a/cli/cmd/update.go b/cli/cmd/update.goindex e9eaf939..d75dcde9 100644--- a/cli/cmd/update.go+++ b/cli/cmd/update.go@@ -1,6 +1,7 @@package cmdimport (+ "plandex/auth""plandex/lib""github.com/spf13/cobra"@@ -20,6 +21,7 @@ func init() {}func update(cmd *cobra.Command, args []string) {+ auth.MustResolveAuthWithOrg()lib.MustResolveProject()lib.MustUpdateContextWithOuput()diff --git a/cli/lib/apply.go b/cli/lib/apply.goindex b7e985ca..ec4e413e 100644--- a/cli/lib/apply.go+++ b/cli/lib/apply.go@@ -17,10 +17,10 @@ import ()func ApplyPlanWithOutput(planId string, autoConfirm bool) error {- currentPlanState, err := api.Client.GetCurrentPlanState(planId)+ currentPlanState, apiErr := api.Client.GetCurrentPlanState(planId)- if err != nil {- return fmt.Errorf("error getting current plan state: %w", err)+ if apiErr != nil {+ return fmt.Errorf("error getting current plan state: %w", apiErr.Msg)}currentPlanFiles := currentPlanState.CurrentPlanFiles@@ -42,6 +42,7 @@ func ApplyPlanWithOutput(planId string, autoConfirm bool) error {outdatedCanMergeSet := map[string]bool{}canMergeAllOutdated := true+ var err errorfor path := range currentPlanFiles.Files {contextSha := currentPlanFiles.ContextShas[path]@@ -303,11 +304,11 @@ func ApplyPlanWithOutput(planId string, autoConfirm bool) error {}}- err := api.Client.ApplyPlan(planId)+ apiErr := api.Client.ApplyPlan(planId)- if err != nil {+ if apiErr != nil {aborted = true- return fmt.Errorf("failed to set pending results applied: %w", err)+ return fmt.Errorf("failed to set pending results applied: %w", apiErr.Msg)}if isRepo {diff --git a/cli/lib/context_load.go b/cli/lib/context_load.goindex eec7a791..839a8902 100644--- a/cli/lib/context_load.go+++ b/cli/lib/context_load.go@@ -169,10 +169,10 @@ func MustLoadContext(resources []string, params *types.LoadContextParams) {os.Exit(0)}- res, err := api.Client.LoadContext(CurrentPlanId, loadContextReq)+ res, apiErr := api.Client.LoadContext(CurrentPlanId, loadContextReq)- if err != nil {- onErr(fmt.Errorf("failed to load context: %v", err))+ if apiErr != nil {+ onErr(fmt.Errorf("failed to load context: %v", apiErr.Msg))}term.StopSpinner()diff --git a/cli/lib/current.go b/cli/lib/current.goindex 437088af..736b2864 100644--- a/cli/lib/current.go+++ b/cli/lib/current.go@@ -98,10 +98,10 @@ func MustLoadCurrentPlan() {}func mustInitProject() {- res, err := api.Client.CreateProject(shared.CreateProjectRequest{Name: filepath.Base(fs.ProjectRoot)})+ res, apiErr := api.Client.CreateProject(shared.CreateProjectRequest{Name: filepath.Base(fs.ProjectRoot)})- if err != nil {- panic(fmt.Errorf("error creating project: %v", err))+ if apiErr != nil {+ panic(fmt.Errorf("error creating project: %v", apiErr.Msg))}CurrentProjectId = res.Iddiff --git a/cli/types/api.go b/cli/types/api.goindex ea811a76..af5ac997 100644--- a/cli/types/api.go+++ b/cli/types/api.go@@ -14,38 +14,58 @@ type OnStreamPlanParams struct {type OnStreamPlan func(params OnStreamPlanParams)type ApiClient interface {- StartTrial() (*shared.StartTrialResponse, error)- CreateProject(req shared.CreateProjectRequest) (*shared.CreateProjectResponse, error)- ListProjects() ([]*shared.Project, error)- SetProjectPlan(projectId string, req shared.SetProjectPlanRequest) error- RenameProject(projectId string, req shared.RenameProjectRequest) error-- ListPlans(projectId string) ([]*shared.Plan, error)- ListArchivedPlans(projectId string) ([]*shared.Plan, error)- ListPlansRunning(projectId string) ([]*shared.Plan, error)- GetPlan(planId string) (*shared.Plan, error)- CreatePlan(projectId string, req shared.CreatePlanRequest) (*shared.CreatePlanResponse, error)-- TellPlan(planId string, req shared.TellPlanRequest, onStreamPlan OnStreamPlan) error- DeletePlan(planId string) error- DeleteAllPlans(projectId string) error- ConnectPlan(planId string, onStreamPlan OnStreamPlan) error- StopPlan(planId string) error-- ArchivePlan(planId string) error-- GetCurrentPlanState(planId string) (*shared.CurrentPlanState, error)- ApplyPlan(planId string) error- RejectAllChanges(planId string) error- RejectResult(planId, resultId string) error- RejectReplacement(planId, resultId, replacementId string) error-- LoadContext(planId string, req shared.LoadContextRequest) (*shared.LoadContextResponse, error)- UpdateContext(planId string, req shared.UpdateContextRequest) (*shared.UpdateContextResponse, error)- DeleteContext(planId string, req shared.DeleteContextRequest) (*shared.DeleteContextResponse, error)- ListContext(planId string) ([]*shared.Context, error)-- ListConvo(planId string) ([]*shared.ConvoMessage, error)- ListLogs(planId string) (*shared.LogResponse, error)- RewindPlan(planId string, req shared.RewindPlanRequest) (*shared.RewindPlanResponse, error)+ StartTrial() (*shared.StartTrialResponse, *shared.ApiError)+ ConvertTrial(req shared.ConvertTrialRequest) (*shared.SessionResponse, *shared.ApiError)++ CreateEmailVerification(email, customHost, userId string) (*shared.CreateEmailVerificationResponse, *shared.ApiError)++ CreateAccount(req shared.CreateAccountRequest, customHost string) (*shared.SessionResponse, *shared.ApiError)+ SignIn(req shared.SignInRequest, customHost string) (*shared.SessionResponse, *shared.ApiError)+ SignOut() *shared.ApiError++ ListOrgs() ([]*shared.Org, *shared.ApiError)+ CreateOrg(req shared.CreateOrgRequest) (*shared.CreateOrgResponse, *shared.ApiError)++ ListUsers() ([]*shared.User, *shared.ApiError)+ DeleteUser(userId string) *shared.ApiError++ InviteUser(req shared.InviteRequest) *shared.ApiError+ ListPendingInvites() ([]*shared.Invite, *shared.ApiError)+ ListAcceptedInvites() ([]*shared.Invite, *shared.ApiError)+ ListAllInvites() ([]*shared.Invite, *shared.ApiError)+ DeleteInvite(inviteId string) *shared.ApiError++ CreateProject(req shared.CreateProjectRequest) (*shared.CreateProjectResponse, *shared.ApiError)+ ListProjects() ([]*shared.Project, *shared.ApiError)+ SetProjectPlan(projectId string, req shared.SetProjectPlanRequest) *shared.ApiError+ RenameProject(projectId string, req shared.RenameProjectRequest) *shared.ApiError++ ListPlans(projectId string) ([]*shared.Plan, *shared.ApiError)+ ListArchivedPlans(projectId string) ([]*shared.Plan, *shared.ApiError)+ ListPlansRunning(projectId string) ([]*shared.Plan, *shared.ApiError)+ GetPlan(planId string) (*shared.Plan, *shared.ApiError)+ CreatePlan(projectId string, req shared.CreatePlanRequest) (*shared.CreatePlanResponse, *shared.ApiError)++ TellPlan(planId string, req shared.TellPlanRequest, onStreamPlan OnStreamPlan) *shared.ApiError+ DeletePlan(planId string) *shared.ApiError+ DeleteAllPlans(projectId string) *shared.ApiError+ ConnectPlan(planId string, onStreamPlan OnStreamPlan) *shared.ApiError+ StopPlan(planId string) *shared.ApiError++ ArchivePlan(planId string) *shared.ApiError++ GetCurrentPlanState(planId string) (*shared.CurrentPlanState, *shared.ApiError)+ ApplyPlan(planId string) *shared.ApiError+ RejectAllChanges(planId string) *shared.ApiError+ RejectResult(planId, resultId string) *shared.ApiError+ RejectReplacement(planId, resultId, replacementId string) *shared.ApiError++ LoadContext(planId string, req shared.LoadContextRequest) (*shared.LoadContextResponse, *shared.ApiError)+ UpdateContext(planId string, req shared.UpdateContextRequest) (*shared.UpdateContextResponse, *shared.ApiError)+ DeleteContext(planId string, req shared.DeleteContextRequest) (*shared.DeleteContextResponse, *shared.ApiError)+ ListContext(planId string) ([]*shared.Context, *shared.ApiError)++ ListConvo(planId string) ([]*shared.ConvoMessage, *shared.ApiError)+ ListLogs(planId string) (*shared.LogResponse, *shared.ApiError)+ RewindPlan(planId string, req shared.RewindPlanRequest) (*shared.RewindPlanResponse, *shared.ApiError)}diff --git a/cli/types/types.go b/cli/types/types.goindex 22ea8059..9af68cf5 100644--- a/cli/types/types.go+++ b/cli/types/types.go@@ -13,15 +13,9 @@ type ClientAccount struct {}type ClientAuth struct {- IsCloud bool `json:"isCloud"`- Host string `json:"host"`- Email string `json:"email"`- OrgId string `json:"orgId"`- OrgName string `json:"orgName"`- UserId string `json:"userId"`- UserName string `json:"userName"`- Token string `json:"token"`- IsTrial bool `json:"isTrial"`+ ClientAccount+ OrgId string `json:"orgId"`+ OrgName string `json:"orgName"`}type LoadContextParams struct {diff --git a/server/db/auth_helpers.go b/server/db/auth_helpers.goindex 699ad40a..376c7cc0 100644--- a/server/db/auth_helpers.go+++ b/server/db/auth_helpers.go@@ -28,28 +28,29 @@ func CreateAuthToken(userId string, tx *sql.Tx) (token, id string, err error) {return uid.String(), id, nil}-func ValidateAuthToken(token string) (userId, tokenHash string, err error) {+func ValidateAuthToken(token string) (*AuthToken, error) {uid, err := uuid.Parse(token)if err != nil {- return "", "", errors.New("invalid token")+ return nil, errors.New("invalid token")}bytes := uid[:]hashBytes := sha256.Sum256(bytes)- tokenHash = hex.EncodeToString(hashBytes[:])+ tokenHash := hex.EncodeToString(hashBytes[:])- err = Conn.QueryRow("SELECT user_id FROM auth_tokens WHERE token_hash = $1 AND created_at > $2 AND deleted_at IS NULL", tokenHash, time.Now().AddDate(0, 0, -tokenExpirationDays)).Scan(&userId)+ var authToken AuthToken+ err = Conn.Get(&authToken, "SELECT * FROM auth_tokens WHERE token_hash = $1 AND created_at > $2 AND deleted_at IS NULL", tokenHash, time.Now().AddDate(0, 0, -tokenExpirationDays))if err != nil {if err == sql.ErrNoRows {- return "", "", errors.New("invalid token")+ return nil, errors.New("invalid token")}- return "", "", fmt.Errorf("error validating token: %v", err)+ return nil, fmt.Errorf("error validating token: %v", err)}- return userId, tokenHash, nil+ return &authToken, nil}func CreateEmailVerification(email string, userId, pinHash string) error {diff --git a/server/db/invite_helpers.go b/server/db/invite_helpers.gonew file mode 100644index 00000000..b90f0099--- /dev/null+++ b/server/db/invite_helpers.go@@ -0,0 +1,149 @@+package db++import (+ "database/sql"+ "fmt"+ "log"+ "strings"+)++func CreateInvite(invite *Invite) error {+ _, err := Conn.NamedExec(`INSERT INTO invites (id, org_id, email, name, inviter_id) VALUES (:id, :org_id, :email, :name, :inviter_id)`, invite)+ if err != nil {+ return fmt.Errorf("error creating invite: %v", err)+ }++ return nil+}++func GetInvite(id string) (*Invite, error) {+ var invite Invite+ err := Conn.Get(&invite, "SELECT * FROM invites WHERE id = $1", id)++ if err != nil {+ return nil, fmt.Errorf("error getting invite: %v", err)+ }++ return &invite, nil+}++func GetInviteForOrgUser(orgId, userId string) (*Invite, error) {+ var invite Invite+ err := Conn.Get(&invite, "SELECT * FROM invites WHERE org_id = $1 AND invitee_id = $2", orgId, userId)++ if err != nil {+ if err == sql.ErrNoRows {+ return nil, nil+ }++ return nil, fmt.Errorf("error getting invite: %v", err)+ }++ return &invite, nil+}++func ListPendingInvites(orgId string) ([]*Invite, error) {+ var invites []*Invite+ err := Conn.Select(&invites, "SELECT * FROM invites WHERE org_id = $1 AND accepted_at IS NULL", orgId)++ if err != nil {+ return nil, fmt.Errorf("error getting invites for org: %v", err)+ }++ return invites, nil+}++func ListAllInvites(orgId string) ([]*Invite, error) {+ var invites []*Invite+ err := Conn.Select(&invites, "SELECT * FROM invites WHERE org_id = $1", orgId)++ if err != nil {+ return nil, fmt.Errorf("error getting invites for org: %v", err)+ }++ return invites, nil+}++func ListAcceptedInvites(orgId string) ([]*Invite, error) {+ var invites []*Invite+ err := Conn.Select(&invites, "SELECT * FROM invites WHERE org_id = $1 AND accepted_at IS NOT NULL", orgId)++ if err != nil {+ return nil, fmt.Errorf("error getting invites for org: %v", err)+ }++ return invites, nil+}++func GetPendingInvitesForEmail(email string) ([]*Invite, error) {+ email = strings.ToLower(email)+ var invites []*Invite+ err := Conn.Select(&invites, "SELECT * FROM invites WHERE email = $1 AND accepted_at IS NULL", email)+ if err != nil {+ if err == sql.ErrNoRows {+ return nil, nil+ }++ return nil, fmt.Errorf("error getting invites and org names for email: %v", err)+ }++ return invites, nil+}++func DeleteInvite(id string, tx *sql.Tx) error {+ query := "DELETE FROM invites WHERE id = $1"+ var err error++ if tx == nil {+ _, err = tx.Exec(query, id)+ } else {+ _, err = Conn.Exec(query, id)+ }++ if err != nil {+ return fmt.Errorf("error deleting invite: %v", err)+ }++ return nil+}++func AcceptInvite(invite *Invite, inviteeId string) error {+ // start a transaction+ tx, err := Conn.Begin()+ if err != nil {+ return fmt.Errorf("error starting transaction: %v", err)+ }++ // Ensure that rollback is attempted in case of failure+ defer func() {+ if err != nil {+ if rbErr := tx.Rollback(); rbErr != nil {+ log.Printf("transaction rollback error: %v\n", rbErr)+ } else {+ log.Println("transaction rolled back")+ }+ }+ }()++ _, err = tx.Exec(`UPDATE invites SET accepted_at = NOW(), invitee_id = $1 WHERE id = $2`, inviteeId, invite.Id)+ if err != nil {+ return fmt.Errorf("error accepting invite: %v", err)+ }++ // create org user+ err = CreateOrgUser(invite.OrgId, invite.InviteeId, tx)++ if err != nil {+ return fmt.Errorf("error creating org user: %v", err)+ }++ // commit transaction+ err = tx.Commit()+ if err != nil {+ return fmt.Errorf("error committing transaction: %v", err)+ }++ invite.InviteeId = inviteeId++ return nil+}diff --git a/server/db/models.go b/server/db/models.goindex efed01f3..08250bd0 100644--- a/server/db/models.go+++ b/server/db/models.go@@ -11,10 +11,18 @@ import (// This adds some duplication, but helps ensure that server-only data doesn't leak to the client.// Models used client-side have a ToApi() method to convert it to the corresponding client-side model.+type AuthToken struct {+ Id string `db:"id"`+ UserId string `db:"user_id"`+ TokenHash string `db:"token_hash"`+ CreatedAt time.Time `db:"created_at"`+ DeletedAt time.Time `db:"deleted_at"`+}+type Org struct {Id string `db:"id"`Name string `db:"name"`- Domain string `db:"domain"`+ Domain *string `db:"domain"`AutoAddDomainUsers bool `db:"auto_add_domain_users"`OwnerId string `db:"owner_id"`CreatedAt time.Time `db:"created_at"`@@ -32,6 +40,7 @@ type User struct {Id string `db:"id"`Name string `db:"name"`Email string `db:"email"`+ Domain string `db:"domain"`NumNonDraftPlans int `db:"num_non_draft_plans"`IsTrial bool `db:"is_trial"`CreatedAt time.Time `db:"created_at"`@@ -48,6 +57,31 @@ func (user *User) ToApi() *shared.User {}}+type Invite struct {+ Id string `db:"id"`+ OrgId string `db:"org_id"`+ Email string `db:"email"`+ Name string `db:"name"`+ InviterId string `db:"inviter_id"`+ InviteeId string `db:"invitee_id"`+ AcceptedAt *time.Time `db:"accepted_at"`+ CreatedAt time.Time `db:"created_at"`+ UpdatedAt time.Time `db:"updated_at"`+}++func (invite *Invite) ToApi() *shared.Invite {+ return &shared.Invite{+ Id: invite.Id,+ OrgId: invite.OrgId,+ Email: invite.Email,+ Name: invite.Name,+ InviterId: invite.InviterId,+ InviteeId: invite.InviteeId,+ AcceptedAt: invite.AcceptedAt,+ CreatedAt: invite.CreatedAt,+ }+}+type OrgUser struct {Id string `db:"id"`OrgId string `db:"org_id"`diff --git a/server/db/org_helpers.go b/server/db/org_helpers.gonew file mode 100644index 00000000..226c14f9--- /dev/null+++ b/server/db/org_helpers.go@@ -0,0 +1,167 @@+package db++import (+ "database/sql"+ "fmt"+ "strings"++ "github.com/plandex/plandex/shared"+)++func GetAccessibleOrgsForUser(user *User) ([]*Org, error) {+ // direct access+ var orgs []*Org+ err := Conn.Select(&orgs, "SELECT o.* FROM orgs o JOIN orgs_users ou ON o.id = ou.org_id WHERE ou.user_id = $1", user.Id)++ if err != nil {+ return nil, fmt.Errorf("error getting orgs for user: %v", err)+ }++ // access via invitation+ invites, err := GetPendingInvitesForEmail(user.Email)++ if err != nil {+ return nil, fmt.Errorf("error getting invites for user: %v", err)+ }++ var orgIds []string+ for _, invite := range invites {+ orgIds = append(orgIds, invite.OrgId)+ }++ if len(orgIds) > 0 {+ var orgsFromInvites []*Org+ err = Conn.Select(&orgsFromInvites, "SELECT * FROM orgs WHERE id IN (?)", strings.Join(orgIds, ","))+ if err != nil {+ return nil, fmt.Errorf("error getting orgs from invites: %v", err)+ }+ orgs = append(orgs, orgsFromInvites...)+ }++ return orgs, nil+}++func GetOrg(orgId string) (*Org, error) {+ var org Org+ err := Conn.Get(&org, "SELECT * FROM orgs WHERE id = $1", orgId)++ if err != nil {+ if err == sql.ErrNoRows {+ return nil, fmt.Errorf("org not found")+ }++ return nil, fmt.Errorf("error getting org: %v", err)+ }++ return &org, nil+}++func ValidateOrgMembership(userId string, orgId string) (bool, error) {+ var count int+ err := Conn.QueryRow("SELECT COUNT(*) FROM orgs_users WHERE user_id = $1 AND org_id = $2", userId, orgId).Scan(&count)++ if err != nil {+ return false, fmt.Errorf("error validating org membership: %v", err)+ }++ return count > 0, nil+}++func CreateOrg(req *shared.CreateOrgRequest, userId string, domain *string, tx *sql.Tx) (*Org, error) {+ org := &Org{+ Name: req.Name,+ Domain: domain,+ AutoAddDomainUsers: req.AutoAddDomainUsers,+ OwnerId: userId,+ }++ err := tx.QueryRow("INSERT INTO orgs (name, domain, auto_add_domain_users, owner_id) VALUES ($1, $2, $3, $4) RETURNING id", req.Name, domain, req.AutoAddDomainUsers, userId).Scan(&org.Id)++ if err != nil {+ if IsNonUniqueErr(err) {+ // Handle the uniqueness constraint violation+ return nil, fmt.Errorf("an org with domain %s already exists", domain)++ }++ return nil, fmt.Errorf("error creating org: %v", err)+ }++ _, err = tx.Exec("INSERT INTO orgs_users (org_id, user_id) VALUES ($1, $2)", org.Id, userId)++ if err != nil {+ return nil, fmt.Errorf("error adding org membership: %v", err)+ }++ return org, nil+}++func GetOrgForDomain(domain string) (*Org, error) {+ var org Org+ err := Conn.Get(&org, "SELECT * FROM orgs WHERE domain = $1", domain)++ if err != nil {+ if err == sql.ErrNoRows {+ return nil, nil+ }++ return nil, fmt.Errorf("error getting org for domain: %v", err)+ }++ return &org, nil+}++func AddOrgDomainUsers(orgId, domain string, tx *sql.Tx) error {+ usersForDomain, err := GetUsersForDomain(domain)++ if err != nil {+ return fmt.Errorf("error getting users for domain: %v", err)+ }++ if len(usersForDomain) > 0 {++ // create org users for each user+ var valueStrings []string+ var valueArgs []interface{}+ for i, user := range usersForDomain {+ valueStrings = append(valueStrings, fmt.Sprintf("($%d, $%d)", i*2+1, i*2+2))+ valueArgs = append(valueArgs, orgId, user.Id)+ }++ // Join all value strings and execute a single query+ stmt := fmt.Sprintf("INSERT INTO orgs_users (org_id, user_id) VALUES %s", strings.Join(valueStrings, ","))+ _, err = tx.Exec(stmt, valueArgs...)++ if err != nil {+ return fmt.Errorf("error adding org users: %v", err)+ }+ }++ return nil+}++func DeleteOrgUser(orgId, userId string, tx *sql.Tx) error {+ _, err := tx.Exec("DELETE FROM orgs_users WHERE org_id = $1 AND user_id = $2", orgId, userId)++ if err != nil {+ return fmt.Errorf("error deleting org member: %v", err)+ }++ return nil+}++func CreateOrgUser(orgId, userId string, tx *sql.Tx) error {+ query := "INSERT INTO orgs_users (org_id, user_id) VALUES ($1, $2)"+ var err error+ if tx == nil {+ _, err = Conn.Exec(query, orgId, userId)+ } else {+ _, err = tx.Exec(query, orgId, userId)+ }++ if err != nil {+ return fmt.Errorf("error adding org member: %v", err)+ }++ return nil+}diff --git a/server/db/user_helpers.go b/server/db/user_helpers.goindex 6bb7187c..764cf287 100644--- a/server/db/user_helpers.go+++ b/server/db/user_helpers.go@@ -3,9 +3,6 @@ package dbimport ("database/sql""fmt"- "log"-- "github.com/plandex/plandex/shared")func GetUser(userId string) (*User, error) {@@ -34,76 +31,32 @@ func GetUserByEmail(email string) (*User, error) {return &user, nil}-func GetOrgsForUser(userId string) ([]*Org, error) {- var orgs []*Org- err := Conn.Select(&orgs, "SELECT o.* FROM orgs o JOIN orgs_users ou ON o.id = ou.org_id WHERE ou.user_id = $1", userId)+func GetUsersForDomain(domain string) ([]*User, error) {+ var users []*User+ err := Conn.Select(&users, "SELECT * FROM users WHERE domain = $1", domain)if err != nil {- return nil, fmt.Errorf("error getting orgs for user: %v", err)- }-- return orgs, nil-}--func ValidateOrgMembership(userId string, orgId string) (bool, error) {- var count int- err := Conn.QueryRow("SELECT COUNT(*) FROM orgs_users WHERE user_id = $1 AND org_id = $2", userId, orgId).Scan(&count)+ if err == sql.ErrNoRows {+ return nil, nil+ }- if err != nil {- return false, fmt.Errorf("error validating org membership: %v", err)+ return nil, fmt.Errorf("error getting users for domain: %v", err)}- return count > 0, nil+ return users, nil}-func CreateOrg(req *shared.CreateOrgRequest, userId string) (*Org, error) {- org := &Org{- Name: req.Name,- Domain: req.Domain,- AutoAddDomainUsers: req.AutoAddDomainUsers,- OwnerId: userId,- }+func ListUsers(orgId string) ([]*User, error) {+ var users []*User+ err := Conn.Select(&users, "SELECT u.* FROM users u INNER JOIN orgs_users ou ON u.id = ou.user_id WHERE ou.org_id = $1", orgId)- // start a transaction- tx, err := Conn.Begin()if err != nil {- return nil, fmt.Errorf("error starting transaction: %v", err)+ return nil, fmt.Errorf("error listing users: %v", err)}- // Ensure that rollback is attempted in case of failure- defer func() {- if err != nil {- if rbErr := tx.Rollback(); rbErr != nil {- log.Printf("transaction rollback error: %v\n", rbErr)- } else {- log.Println("transaction rolled back")- }- }- }()-- err = tx.QueryRow("INSERT INTO orgs (name, domain, auto_add_domain_users, owner_id) VALUES ($1, $2, $3, $4) RETURNING id", req.Name, req.Domain, req.AutoAddDomainUsers, userId).Scan(&org.Id)-- if err != nil {- if IsNonUniqueErr(err) {- // Handle the uniqueness constraint violation- return nil, fmt.Errorf("an org with domain %s already exists", req.Domain)-- }-- return nil, fmt.Errorf("error creating org: %v", err)- }-- _, err = tx.Exec("INSERT INTO orgs_users (org_id, user_id) VALUES ($1, $2)", org.Id, userId)-- if err != nil {- return nil, fmt.Errorf("error adding org membership: %v", err)- }-- err = tx.Commit()-- if err != nil {- return nil, fmt.Errorf("error committing transaction: %v", err)- }+ return users, nil+}- return org, nil+func CreateUser(user *User, tx *sql.Tx) error {+ return tx.QueryRow("INSERT INTO users (name, email, domain) VALUES ($1, $2, $3) RETURNING id", user.Name, user.Email, user.Domain).Scan(&user.Id)}diff --git a/server/handlers/accounts.go b/server/handlers/accounts.goindex 22457e57..d0df1fc5 100644--- a/server/handlers/accounts.go+++ b/server/handlers/accounts.go@@ -1,15 +1,12 @@package handlersimport (- "crypto/sha256"- "encoding/hex""encoding/json""fmt""io""log""net/http""plandex-server/db"- "plandex-server/email""strings""github.com/plandex/plandex/shared"@@ -44,6 +41,7 @@ func StartTrialHandler(w http.ResponseWriter, r *http.Request) {return}tag := fmt.Sprintf("%x", b)+ tag = strings.ToLower(tag)name := "Trial User " + tagemail := tag + "@trial.plandex.ai"@@ -69,7 +67,7 @@ func StartTrialHandler(w http.ResponseWriter, r *http.Request) {}// insert org user- _, err = tx.Exec("INSERT INTO orgs_users (org_id, user_id) VALUES ($1, $2)", orgId, userId)+ err = db.CreateOrgUser(userId, orgId, tx)if err != nil {log.Printf("Error inserting org user: %v\n", err)http.Error(w, "Error inserting org user: "+err.Error(), http.StatusInternalServerError)@@ -115,60 +113,8 @@ func StartTrialHandler(w http.ResponseWriter, r *http.Request) {w.Write(bytes)}-func CreateEmailVerificationHandler(w http.ResponseWriter, r *http.Request) {- log.Println("Received request for CreateEmailVerificationHandler")-- // read the request body- body, err := io.ReadAll(r.Body)- if err != nil {- log.Printf("Error reading request body: %v\n", err)- http.Error(w, "Error reading request body: "+err.Error(), http.StatusInternalServerError)- return- }-- var req shared.CreateEmailVerificationRequest- err = json.Unmarshal(body, &req)- if err != nil {- log.Printf("Error unmarshalling request: %v\n", err)- http.Error(w, "Error unmarshalling request: "+err.Error(), http.StatusInternalServerError)- return- }-- // create pin - 6 alphanumeric characters- pinBytes, err := shared.GetRandomAlphanumeric(6)- if err != nil {- log.Printf("Error generating random pin: %v\n", err)- http.Error(w, "Error generating random pin: "+err.Error(), http.StatusInternalServerError)- return- }-- // get sha256 hash of pin- hashBytes := sha256.Sum256(pinBytes)- pinHash := hex.EncodeToString(hashBytes[:])-- // create verification- err = db.CreateEmailVerification(req.Email, pinHash, req.UserId)-- if err != nil {- log.Printf("Error creating email verification: %v\n", err)- http.Error(w, "Error creating email verification: "+err.Error(), http.StatusInternalServerError)- return- }-- err = email.SendVerificationEmail(req.Email, string(pinBytes))-- if err != nil {- log.Printf("Error sending verification email: %v\n", err)- http.Error(w, "Error sending verification email: "+err.Error(), http.StatusInternalServerError)- return- }-- log.Println("Successfully created email verification")--}--func SignInHandler(w http.ResponseWriter, r *http.Request) {- log.Println("Received request for SignInHandler")+func CreateAccountHandler(w http.ResponseWriter, r *http.Request) {+ log.Println("Received request for CreateAccountHandler")// read the request bodybody, err := io.ReadAll(r.Body)@@ -178,13 +124,14 @@ func SignInHandler(w http.ResponseWriter, r *http.Request) {return}- var req shared.SignInRequest+ var req shared.CreateAccountRequesterr = json.Unmarshal(body, &req)if err != nil {log.Printf("Error unmarshalling request: %v\n", err)http.Error(w, "Error unmarshalling request: "+err.Error(), http.StatusInternalServerError)return}+ req.Email = strings.ToLower(req.Email)emailVerificationId, err := db.ValidateEmailVerification(req.Email, req.Pin)@@ -194,20 +141,6 @@ func SignInHandler(w http.ResponseWriter, r *http.Request) {return}- user, err := db.GetUserByEmail(req.Email)-- if err != nil {- log.Printf("Error getting user: %v\n", err)- http.Error(w, "Error getting user: "+err.Error(), http.StatusInternalServerError)- return- }-- if user == nil {- log.Printf("User not found for email: %v\n", req.Email)- http.Error(w, "Not found", http.StatusNotFound)- return- }-// start a transactiontx, err := db.Conn.Begin()if err != nil {@@ -227,8 +160,38 @@ func SignInHandler(w http.ResponseWriter, r *http.Request) {}}()+ // create user+ emailSplit := strings.Split(req.Email, "@")+ if len(emailSplit) != 2 {+ log.Printf("Invalid email: %v\n", req.Email)+ http.Error(w, "Invalid email: "+req.Email, http.StatusBadRequest)+ return+ }+ domain := emailSplit[1]++ user := db.User{+ Name: req.UserName,+ Email: req.Email,+ Domain: domain,+ }+ err = db.CreateUser(&user, tx)++ if err != nil {+ if db.IsNonUniqueErr(err) {+ log.Printf("User already exists for email: %v\n", req.Email)+ http.Error(w, "User already exists for email: "+req.Email, http.StatusConflict)+ return+ }++ log.Printf("Error creating user: %v\n", err)+ http.Error(w, "Error creating user: "+err.Error(), http.StatusInternalServerError)+ return+ }++ userId := user.Id+// create auth token- token, authTokenId, err := db.CreateAuthToken(user.Id, tx)+ token, authTokenId, err := db.CreateAuthToken(userId, tx)if err != nil {log.Printf("Error creating auth token: %v\n", err)@@ -237,7 +200,7 @@ func SignInHandler(w http.ResponseWriter, r *http.Request) {}// update email verification with user and auth token ids- _, err = tx.Exec("UPDATE email_verifications SET user_id = $1, auth_token_id = $2 WHERE id = $3", user.Id, authTokenId, emailVerificationId)+ _, err = tx.Exec("UPDATE email_verifications SET user_id = $1, auth_token_id = $2 WHERE id = $3", userId, authTokenId, emailVerificationId)if err != nil {log.Printf("Error updating email verification: %v\n", err)@@ -245,6 +208,25 @@ func SignInHandler(w http.ResponseWriter, r *http.Request) {return}+ // add to org matching domain if one exists and auto add domain users is true for that org+ org, err := db.GetOrgForDomain(domain)++ if err != nil {+ log.Printf("Error getting org for domain: %v\n", err)+ http.Error(w, "Error getting org for domain: "+err.Error(), http.StatusInternalServerError)+ return+ }++ if org != nil && org.AutoAddDomainUsers {+ err = db.CreateOrgUser(userId, org.Id, tx)++ if err != nil {+ log.Printf("Error adding org user: %v\n", err)+ http.Error(w, "Error adding org user: "+err.Error(), http.StatusInternalServerError)+ return+ }+ }+// commit transactionerr = tx.Commit()if err != nil {@@ -254,7 +236,7 @@ func SignInHandler(w http.ResponseWriter, r *http.Request) {}// get orgs- orgs, err := db.GetOrgsForUser(user.Id)+ orgs, err := db.GetAccessibleOrgsForUser(&user)if err != nil {log.Printf("Error getting orgs for user: %v\n", err)@@ -268,10 +250,10 @@ func SignInHandler(w http.ResponseWriter, r *http.Request) {}resp := shared.SessionResponse{- UserId: user.Id,+ UserId: userId,Token: token,- Email: user.Email,- UserName: user.Name,+ Email: req.Email,+ UserName: req.UserName,Orgs: apiOrgs,}@@ -283,43 +265,27 @@ func SignInHandler(w http.ResponseWriter, r *http.Request) {return}- log.Println("Successfully signed in")+ log.Println("Successfully created account")w.Write(bytes)}-func SignOutHandler(w http.ResponseWriter, r *http.Request) {- log.Println("Received request for SignOutHandler")+func ConvertTrialHandler(w http.ResponseWriter, r *http.Request) {+ log.Println("Received request for ConvertTrialHandler")- auth := authenticate(w, r, false)+ auth := authenticate(w, r, true)if auth == nil {return}- _, err := db.Conn.Exec("UPDATE auth_tokens SET deleted_at = NOW() WHERE token_hash = $1", auth.TokenHash)-- if err != nil {- log.Printf("Error deleting auth token: %v\n", err)- http.Error(w, "Error deleting auth token: "+err.Error(), http.StatusInternalServerError)- return- }-- log.Println("Successfully signed out")-}--func CreateAccountHandler(w http.ResponseWriter, r *http.Request) {- log.Println("Received request for CreateAccountHandler")-- // read the request body- body, err := io.ReadAll(r.Body)- if err != nil {- log.Printf("Error reading request body: %v\n", err)- http.Error(w, "Error reading request body: "+err.Error(), http.StatusInternalServerError)+ if !auth.User.IsTrial {+ log.Println("Trial isn't active")+ http.Error(w, "Trial isn't active", http.StatusBadRequest)return}- var req shared.CreateAccountRequest- err = json.Unmarshal(body, &req)+ var req shared.ConvertTrialRequest+ err := json.NewDecoder(r.Body).Decode(&req)if err != nil {log.Printf("Error unmarshalling request: %v\n", err)http.Error(w, "Error unmarshalling request: "+err.Error(), http.StatusInternalServerError)@@ -334,6 +300,24 @@ func CreateAccountHandler(w http.ResponseWriter, r *http.Request) {return}+ emailSplit := strings.Split(req.Email, "@")+ if len(emailSplit) != 2 {+ log.Printf("Invalid email: %v\n", req.Email)+ http.Error(w, "Invalid email: "+req.Email, http.StatusBadRequest)+ return+ }+ userDomain := emailSplit[1]+ var domain *string+ if req.OrgAutoAddDomainUsers {+ if shared.IsEmailServiceDomain(userDomain) {+ log.Printf("Invalid domain: %v\n", userDomain)+ http.Error(w, "Invalid domain: "+userDomain, http.StatusBadRequest)+ return+ }++ domain = &userDomain+ }+// start a transactiontx, err := db.Conn.Begin()if err != nil {@@ -353,9 +337,7 @@ func CreateAccountHandler(w http.ResponseWriter, r *http.Request) {}}()- // create user- var userId string- err = tx.QueryRow("INSERT INTO users (name, email) VALUES ($1, $2) RETURNING id", req.UserName, req.Email).Scan(&userId)+ _, err = tx.Exec("UPDATE users SET name = $1, email = $2, domain = $3, is_trial = false WHERE id = $4", req.UserName, req.Email, userDomain, auth.AuthToken.UserId)if err != nil {if db.IsNonUniqueErr(err) {@@ -363,23 +345,13 @@ func CreateAccountHandler(w http.ResponseWriter, r *http.Request) {http.Error(w, "User already exists for email: "+req.Email, http.StatusConflict)return}-- log.Printf("Error creating user: %v\n", err)- http.Error(w, "Error creating user: "+err.Error(), http.StatusInternalServerError)- return- }-- // create auth token- token, authTokenId, err := db.CreateAuthToken(userId, tx)-- if err != nil {- log.Printf("Error creating auth token: %v\n", err)- http.Error(w, "Error creating auth token: "+err.Error(), http.StatusInternalServerError)+ log.Printf("Error updating user: %v\n", err)+ http.Error(w, "Error updating user: "+err.Error(), http.StatusInternalServerError)return}// update email verification with user and auth token ids- _, err = tx.Exec("UPDATE email_verifications SET user_id = $1, auth_token_id = $2 WHERE id = $3", userId, authTokenId, emailVerificationId)+ _, err = tx.Exec("UPDATE email_verifications SET user_id = $1, auth_token_id = $2 WHERE id = $3", auth.AuthToken.UserId, auth.AuthToken.Id, emailVerificationId)if err != nil {log.Printf("Error updating email verification: %v\n", err)@@ -387,100 +359,27 @@ func CreateAccountHandler(w http.ResponseWriter, r *http.Request) {return}- // commit transaction- err = tx.Commit()- if err != nil {- log.Printf("Error committing transaction: %v\n", err)- http.Error(w, "Error committing transaction: "+err.Error(), http.StatusInternalServerError)- return- }-- resp := shared.SessionResponse{- UserId: userId,- Token: token,- Email: req.Email,- UserName: req.UserName,- }-- bytes, err := json.Marshal(resp)-- if err != nil {- log.Printf("Error marshalling response: %v\n", err)- http.Error(w, "Error marshalling response: "+err.Error(), http.StatusInternalServerError)- return- }-- log.Println("Successfully created account")-- w.Write(bytes)-}--func CreateOrgHandler(w http.ResponseWriter, r *http.Request) {- log.Println("Received request for CreateOrgHandler")-- auth := authenticate(w, r, false)- if auth == nil {- return- }-- // read the request body- body, err := io.ReadAll(r.Body)- if err != nil {- log.Printf("Error reading request body: %v\n", err)- http.Error(w, "Error reading request body: "+err.Error(), http.StatusInternalServerError)- return- }+ // update org+ _, err = tx.Exec("UPDATE orgs SET name = $1, domain = $2, auto_add_domain_users = $3, is_trial = false WHERE id = $4", req.OrgName, domain, req.OrgAutoAddDomainUsers, auth.OrgId)- var req shared.CreateOrgRequest- err = json.Unmarshal(body, &req)if err != nil {- log.Printf("Error unmarshalling request: %v\n", err)- http.Error(w, "Error unmarshalling request: "+err.Error(), http.StatusInternalServerError)- return- }-- if req.Domain != "" {- // ensure user email matches domain- user, err := db.GetUser(auth.UserId)-- if err != nil {- log.Printf("Error getting user: %v\n", err)- http.Error(w, "Error getting user: "+err.Error(), http.StatusInternalServerError)- return- }-- split := strings.Split(user.Email, "@")- userDomain := split[1]-- if userDomain != req.Domain {- log.Printf("User email domain does not match request domain: %v\n", req.Domain)- http.Error(w, "User email domain does not match request domain: "+req.Domain, http.StatusBadRequest)+ if db.IsNonUniqueErr(err) {+ log.Printf("Org already exists for domain: %v\n", userDomain)+ http.Error(w, "Org already exists for domain: "+userDomain, http.StatusConflict)return}- }-- // create a new org- org, err := db.CreateOrg(&req, auth.UserId)-- if err != nil {- log.Printf("Error creating org: %v\n", err)- http.Error(w, "Error creating org: "+err.Error(), http.StatusInternalServerError)+ log.Printf("Error updating org: %v\n", err)+ http.Error(w, "Error updating org: "+err.Error(), http.StatusInternalServerError)return}- resp := shared.CreateOrgResponse{- Id: org.Id,- }-- bytes, err := json.Marshal(resp)-+ // commit transaction+ err = tx.Commit()if err != nil {- log.Printf("Error marshalling response: %v\n", err)- http.Error(w, "Error marshalling response: "+err.Error(), http.StatusInternalServerError)+ log.Printf("Error committing transaction: %v\n", err)+ http.Error(w, "Error committing transaction: "+err.Error(), http.StatusInternalServerError)return}- log.Println("Successfully created org")-- w.Write(bytes)+ log.Println("Successfully converted trial")}diff --git a/server/handlers/auth_helpers.go b/server/handlers/auth_helpers.goindex eb549771..30bf739a 100644--- a/server/handlers/auth_helpers.go+++ b/server/handlers/auth_helpers.go@@ -52,18 +52,29 @@ func authenticate(w http.ResponseWriter, r *http.Request, requireOrg bool) *type}// validate the token- userId, tokenHash, err := db.ValidateAuthToken(parsed.Token)+ authToken, err := db.ValidateAuthToken(parsed.Token)if err != nil {- log.Printf("error validating auth token: %v\n", err)- http.Error(w, "invalid auth token", http.StatusUnauthorized)+ writeApiError(w, shared.ApiErr{+ Type: shared.ApiErrorTypeInvalidToken,+ Status: http.StatusUnauthorized,+ Msg: "Invalid auth token",+ })+ return nil+ }++ user, err := db.GetUser(authToken.UserId)++ if err != nil {+ log.Printf("error getting user: %v\n", err)+ http.Error(w, "error getting user", http.StatusInternalServerError)return nil}if !requireOrg {return &types.ServerAuth{- UserId: userId,- TokenHash: tokenHash,+ AuthToken: authToken,+ User: user,}}@@ -74,7 +85,7 @@ func authenticate(w http.ResponseWriter, r *http.Request, requireOrg bool) *type}// validate the org membership- isMember, err := db.ValidateOrgMembership(userId, parsed.OrgId)+ isMember, err := db.ValidateOrgMembership(authToken.UserId, parsed.OrgId)if err != nil {log.Printf("error validating org membership: %v\n", err)@@ -82,17 +93,43 @@ func authenticate(w http.ResponseWriter, r *http.Request, requireOrg bool) *typereturn nil}- if !isMember {- log.Println("user is not a member of the org")- http.Error(w, "not a member of org", http.StatusUnauthorized)- return nil- }+ if isMember {+ return &types.ServerAuth{+ AuthToken: authToken,+ User: user,+ OrgId: parsed.OrgId,+ }+ } else {+ // check if there's an invite for this user and accept it if so (adds the user to the org)+ invite, err := db.GetInviteForOrgUser(parsed.OrgId, authToken.UserId)++ if err != nil {+ log.Printf("error getting invite for org user: %v\n", err)+ http.Error(w, "error getting invite for org user", http.StatusInternalServerError)+ return nil+ }- return &types.ServerAuth{- UserId: userId,- OrgId: parsed.OrgId,- TokenHash: tokenHash,+ if invite != nil {+ err := db.AcceptInvite(invite, authToken.UserId)++ if err != nil {+ log.Printf("error accepting invite: %v\n", err)+ http.Error(w, "error accepting invite", http.StatusInternalServerError)+ return nil+ }++ return &types.ServerAuth{+ AuthToken: authToken,+ User: user,+ OrgId: parsed.OrgId,+ }+ } else {+ log.Println("user is not a member of the org")+ http.Error(w, "not a member of org", http.StatusUnauthorized)+ return nil+ }}+}func authorizeProject(w http.ResponseWriter, projectId, userId, orgId string) bool {diff --git a/server/handlers/err_helper.go b/server/handlers/err_helper.gonew file mode 100644index 00000000..5af081e1--- /dev/null+++ b/server/handlers/err_helper.go@@ -0,0 +1,29 @@+package handlers++import (+ "encoding/json"+ "log"+ "net/http"++ "github.com/plandex/plandex/shared"+)++func writeApiError(w http.ResponseWriter, apiErr shared.ApiErr) {+ bytes, err := json.Marshal(apiErr)+ if err != nil {+ log.Printf("Error marshalling response: %v\n", err)+ // If marshalling fails, fall back to a simpler error message+ http.Error(w, "Error marshalling response", http.StatusInternalServerError)+ return+ }++ log.Printf("API Error: %v\n", apiErr.Msg)++ w.Header().Set("Content-Type", "application/json")+ w.WriteHeader(apiErr.Status)++ _, writeErr := w.Write(bytes)+ if writeErr != nil {+ log.Printf("Error writing response: %v\n", writeErr)+ }+}diff --git a/server/handlers/invites.go b/server/handlers/invites.gonew file mode 100644index 00000000..8c356dad--- /dev/null+++ b/server/handlers/invites.go@@ -0,0 +1,268 @@+package handlers++import (+ "encoding/json"+ "log"+ "net/http"+ "plandex-server/db"+ "strings"++ "github.com/gorilla/mux"+ "github.com/plandex/plandex/shared"+)++func InviteUserHandler(w http.ResponseWriter, r *http.Request) {+ log.Println("Received a request for InviteUserHandler")+ auth := authenticate(w, r, true)+ if auth == nil {+ return+ }++ if auth.User.IsTrial {+ log.Println("Trial user can't invite other users")+ http.Error(w, "Trial user can't invite other users", http.StatusForbidden)+ return+ }++ currentUserId := auth.User.Id++ var req shared.InviteRequest+ err := json.NewDecoder(r.Body).Decode(&req)+ if err != nil {+ log.Printf("Error unmarshalling request: %v\n", err)+ http.Error(w, "Error unmarshalling request: "+err.Error(), http.StatusInternalServerError)+ return+ }+ req.Email = strings.ToLower(req.Email)++ // ensure user doesn't already have access to org via domain+ split := strings.Split(req.Email, "@")+ if len(split) != 2 {+ log.Printf("Invalid email: %v\n", req.Email)+ http.Error(w, "Invalid email: "+req.Email, http.StatusBadRequest)+ return+ }+ domain := &split[1]+ org, err := db.GetOrg(auth.OrgId)++ if err != nil {+ log.Printf("Error getting org: %v\n", err)+ http.Error(w, "Error getting org: "+err.Error(), http.StatusInternalServerError)+ return+ }++ if org.AutoAddDomainUsers && org.Domain == domain {+ log.Printf("User already has access to org via domain: %v\n", domain)+ http.Error(w, "User already has access to org via domain: "+*domain, http.StatusBadRequest)+ }++ // ensure user with this email isn't already in the org+ user, err := db.GetUserByEmail(req.Email)++ if err != nil {+ log.Printf("Error getting user: %v\n", err)+ http.Error(w, "Error getting user: "+err.Error(), http.StatusInternalServerError)+ return+ }++ if user != nil {+ isMember, err := db.ValidateOrgMembership(user.Id, auth.OrgId)++ if err != nil {+ log.Printf("Error validating org membership: %v\n", err)+ http.Error(w, "Error validating org membership: "+err.Error(), http.StatusInternalServerError)+ return+ }++ if isMember {+ log.Println("User is already a member of org")+ http.Error(w, "User is already a member of org", http.StatusBadRequest)+ return+ }+ }++ // ensure invite isn't already active+ invite, err := db.GetInviteForOrgUser(auth.OrgId, req.Email)++ if err != nil {+ log.Printf("Error getting invite: %v\n", err)+ http.Error(w, "Error getting invite: "+err.Error(), http.StatusInternalServerError)+ return+ }++ if invite != nil {+ log.Println("Invite already exists")+ http.Error(w, "Invite already exists", http.StatusBadRequest)+ return+ }++ err = db.CreateInvite(&db.Invite{+ OrgId: auth.OrgId,+ Email: req.Email,+ Name: req.Name,+ InviterId: currentUserId,+ })++ if err != nil {+ log.Printf("Error creating invite: %v\n", err)+ http.Error(w, "Error creating invite: "+err.Error(), http.StatusInternalServerError)+ return+ }++ log.Println("Successfully created invite")+}++func ListPendingInvitesHandler(w http.ResponseWriter, r *http.Request) {+ log.Println("Received a request for ListInvitesHandler")+ auth := authenticate(w, r, true)+ if auth == nil {+ return+ }++ if auth.User.IsTrial {+ log.Println("Trial user can't list invites")+ http.Error(w, "Trial user can't list invites", http.StatusForbidden)+ return+ }++ invites, err := db.ListPendingInvites(auth.OrgId)++ if err != nil {+ log.Printf("Error listing invites: %v\n", err)+ http.Error(w, "Error listing invites: "+err.Error(), http.StatusInternalServerError)+ return+ }++ var apiInvites []*shared.Invite+ for _, invite := range invites {+ apiInvites = append(apiInvites, invite.ToApi())+ }++ bytes, err := json.Marshal(apiInvites)++ if err != nil {+ log.Printf("Error marshalling invites: %v\n", err)+ http.Error(w, "Error marshalling invites: "+err.Error(), http.StatusInternalServerError)+ return+ }++ w.Write(bytes)+ log.Println("Successfully processed request for ListPendingInvitesHandler")+}++func ListAcceptedInvitesHandler(w http.ResponseWriter, r *http.Request) {+ log.Println("Received a request for ListAcceptedInvitesHandler")+ auth := authenticate(w, r, true)+ if auth == nil {+ return+ }++ if auth.User.IsTrial {+ log.Println("Trial user can't list invites")+ http.Error(w, "Trial user can't list invites", http.StatusForbidden)+ return+ }++ invites, err := db.ListAcceptedInvites(auth.OrgId)++ if err != nil {+ log.Printf("Error listing invites: %v\n", err)+ http.Error(w, "Error listing invites: "+err.Error(), http.StatusInternalServerError)+ return+ }++ var apiInvites []*shared.Invite+ for _, invite := range invites {+ apiInvites = append(apiInvites, invite.ToApi())+ }++ bytes, err := json.Marshal(apiInvites)++ if err != nil {+ log.Printf("Error marshalling invites: %v\n", err)+ http.Error(w, "Error marshalling invites: "+err.Error(), http.StatusInternalServerError)+ return+ }++ w.Write(bytes)+ log.Println("Successfully processed request for ListAcceptedInvitesHandler")+}++func ListAllInvitesHandler(w http.ResponseWriter, r *http.Request) {+ log.Println("Received a request for ListAllInvitesHandler")+ auth := authenticate(w, r, true)+ if auth == nil {+ return+ }++ if auth.User.IsTrial {+ log.Println("Trial user can't list invites")+ http.Error(w, "Trial user can't list invites", http.StatusForbidden)+ return+ }++ invites, err := db.ListAllInvites(auth.OrgId)++ if err != nil {+ log.Printf("Error listing invites: %v\n", err)+ http.Error(w, "Error listing invites: "+err.Error(), http.StatusInternalServerError)+ return+ }++ var apiInvites []*shared.Invite+ for _, invite := range invites {+ apiInvites = append(apiInvites, invite.ToApi())+ }++ bytes, err := json.Marshal(apiInvites)++ if err != nil {+ log.Printf("Error marshalling invites: %v\n", err)+ http.Error(w, "Error marshalling invites: "+err.Error(), http.StatusInternalServerError)+ return+ }++ w.Write(bytes)+ log.Println("Successfully processed request for ListAllInvitesHandler")+}++func DeleteInviteHandler(w http.ResponseWriter, r *http.Request) {+ log.Println("Received a request for DeleteInviteHandler")+ auth := authenticate(w, r, true)+ if auth == nil {+ return+ }++ if auth.User.IsTrial {+ log.Println("Trial user can't delete invites")+ http.Error(w, "Trial user can't delete invites", http.StatusForbidden)+ return+ }++ vars := mux.Vars(r)+ inviteId := vars["inviteId"]++ invite, err := db.GetInvite(inviteId)++ if err != nil {+ log.Printf("Error getting invite: %v\n", err)+ http.Error(w, "Error getting invite: "+err.Error(), http.StatusInternalServerError)+ return+ }++ if invite.OrgId != auth.OrgId {+ log.Printf("Invite does not belong to org: %v\n", inviteId)+ http.Error(w, "Invite does not belong to org: "+inviteId, http.StatusBadRequest)+ return+ }++ err = db.DeleteInvite(inviteId, nil)++ if err != nil {+ log.Printf("Error deleting invite: %v\n", err)+ http.Error(w, "Error deleting invite: "+err.Error(), http.StatusInternalServerError)+ return+ }++ log.Println("Successfully deleted invite")+}diff --git a/server/handlers/orgs.go b/server/handlers/orgs.gonew file mode 100644index 00000000..a96a2257--- /dev/null+++ b/server/handlers/orgs.go@@ -0,0 +1,149 @@+package handlers++import (+ "encoding/json"+ "io"+ "log"+ "net/http"+ "plandex-server/db"++ "github.com/plandex/plandex/shared"+)++func ListOrgsHandler(w http.ResponseWriter, r *http.Request) {+ log.Println("Received request for ListOrgsHandler")++ auth := authenticate(w, r, false)+ if auth == nil {+ return+ }++ orgs, err := db.GetAccessibleOrgsForUser(auth.User)++ if err != nil {+ log.Printf("Error listing orgs: %v\n", err)+ http.Error(w, "Error listing orgs: "+err.Error(), http.StatusInternalServerError)+ return+ }++ var apiOrgs []*shared.Org+ for _, org := range orgs {+ apiOrgs = append(apiOrgs, org.ToApi())+ }++ bytes, err := json.Marshal(apiOrgs)++ if err != nil {+ log.Printf("Error marshalling response: %v\n", err)+ http.Error(w, "Error marshalling response: "+err.Error(), http.StatusInternalServerError)+ return+ }++ log.Println("Successfully listed orgs")++ w.Write(bytes)+}++func CreateOrgHandler(w http.ResponseWriter, r *http.Request) {+ log.Println("Received request for CreateOrgHandler")++ auth := authenticate(w, r, false)+ if auth == nil {+ return+ }++ if auth.User.IsTrial {+ log.Println("Trial user cannot create org")+ http.Error(w, "Trial user cannot create org", http.StatusForbidden)+ return+ }++ // read the request body+ body, err := io.ReadAll(r.Body)+ if err != nil {+ log.Printf("Error reading request body: %v\n", err)+ http.Error(w, "Error reading request body: "+err.Error(), http.StatusInternalServerError)+ return+ }++ var req shared.CreateOrgRequest+ err = json.Unmarshal(body, &req)+ if err != nil {+ log.Printf("Error unmarshalling request: %v\n", err)+ http.Error(w, "Error unmarshalling request: "+err.Error(), http.StatusInternalServerError)+ return+ }++ // start a transaction+ tx, err := db.Conn.Begin()+ if err != nil {+ log.Printf("Error starting transaction: %v\n", err)+ http.Error(w, "Error starting transaction: "+err.Error(), http.StatusInternalServerError)+ return+ }++ // Ensure that rollback is attempted in case of failure+ defer func() {+ if err != nil {+ if rbErr := tx.Rollback(); rbErr != nil {+ log.Printf("transaction rollback error: %v\n", rbErr)+ } else {+ log.Println("transaction rolled back")+ }+ }+ }()++ var domain *string+ if req.AutoAddDomainUsers {+ if shared.IsEmailServiceDomain(auth.User.Domain) {+ log.Printf("Invalid domain: %v\n", auth.User.Domain)+ http.Error(w, "Invalid domain: "+auth.User.Domain, http.StatusBadRequest)+ return+ }++ domain = &auth.User.Domain+ }++ // create a new org+ org, err := db.CreateOrg(&req, auth.AuthToken.UserId, domain, tx)++ if err != nil {+ log.Printf("Error creating org: %v\n", err)+ http.Error(w, "Error creating org: "+err.Error(), http.StatusInternalServerError)+ return+ }++ if org.AutoAddDomainUsers && org.Domain != nil {+ err = db.AddOrgDomainUsers(org.Id, *org.Domain, tx)++ if err != nil {+ log.Printf("Error adding org domain users: %v\n", err)+ http.Error(w, "Error adding org domain users: "+err.Error(), http.StatusInternalServerError)+ return+ }+ }++ err = tx.Commit()++ if err != nil {+ log.Printf("Error committing transaction: %v\n", err)+ http.Error(w, "Error committing transaction: "+err.Error(), http.StatusInternalServerError)+ return+ }++ resp := shared.CreateOrgResponse{+ Id: org.Id,+ }++ bytes, err := json.Marshal(resp)++ if err != nil {+ log.Printf("Error marshalling response: %v\n", err)+ http.Error(w, "Error marshalling response: "+err.Error(), http.StatusInternalServerError)+ return+ }++ log.Println("Successfully created org")++ w.Write(bytes)+}diff --git a/server/handlers/plans_changes.go b/server/handlers/plans_changes.goindex 3e49100a..9ced53d8 100644--- a/server/handlers/plans_changes.go+++ b/server/handlers/plans_changes.go@@ -17,13 +17,14 @@ func CurrentPlanHandler(w http.ResponseWriter, r *http.Request) {if auth == nil {return}+ currentUserId := auth.User.Idvars := mux.Vars(r)planId := vars["planId"]log.Println("planId: ", planId)- if authorizePlan(w, planId, auth.UserId, auth.OrgId) == nil {+ if authorizePlan(w, planId, currentUserId, auth.OrgId) == nil {return}@@ -67,12 +68,13 @@ func ApplyPlanHandler(w http.ResponseWriter, r *http.Request) {if auth == nil {return}+ currentUserId := auth.User.Idvars := mux.Vars(r)planId := vars["planId"]log.Println("planId: ", planId)- if authorizePlan(w, planId, auth.UserId, auth.OrgId) == nil {+ if authorizePlan(w, planId, currentUserId, auth.OrgId) == nil {return}@@ -94,12 +96,13 @@ func RejectAllChangesHandler(w http.ResponseWriter, r *http.Request) {if auth == nil {return}+ currentUserId := auth.User.Idvars := mux.Vars(r)planId := vars["planId"]log.Println("planId: ", planId)- if authorizePlan(w, planId, auth.UserId, auth.OrgId) == nil {+ if authorizePlan(w, planId, currentUserId, auth.OrgId) == nil {return}@@ -121,6 +124,7 @@ func RejectResultHandler(w http.ResponseWriter, r *http.Request) {if auth == nil {return}+ currentUserId := auth.User.Idvars := mux.Vars(r)planId := vars["planId"]@@ -128,7 +132,7 @@ func RejectResultHandler(w http.ResponseWriter, r *http.Request) {log.Println("planId: ", planId, "resultId: ", resultId)- if authorizePlan(w, planId, auth.UserId, auth.OrgId) == nil {+ if authorizePlan(w, planId, currentUserId, auth.OrgId) == nil {return}@@ -150,6 +154,7 @@ func RejectReplacementHandler(w http.ResponseWriter, r *http.Request) {if auth == nil {return}+ currentUserId := auth.User.Idvars := mux.Vars(r)planId := vars["planId"]@@ -158,7 +163,7 @@ func RejectReplacementHandler(w http.ResponseWriter, r *http.Request) {log.Println("planId: ", planId, "resultId: ", resultId, "replacementId: ", replacementId)- if authorizePlan(w, planId, auth.UserId, auth.OrgId) == nil {+ if authorizePlan(w, planId, currentUserId, auth.OrgId) == nil {return}@@ -178,6 +183,7 @@ func ArchivePlanHandler(w http.ResponseWriter, r *http.Request) {if auth == nil {return}+ currentUserId := auth.User.Idlog.Println("Received request for ArchivePlanHandler")@@ -185,14 +191,14 @@ func ArchivePlanHandler(w http.ResponseWriter, r *http.Request) {planId := vars["planId"]log.Println("planId: ", planId)- plan := authorizePlan(w, planId, auth.UserId, auth.OrgId)+ plan := authorizePlan(w, planId, currentUserId, auth.OrgId)if plan == nil {return}// apart from authorization, only the plan owner can archive a plan- if plan.OwnerId != auth.UserId {+ if plan.OwnerId != currentUserId {log.Println("Only the plan owner can archive a plan")http.Error(w, "Only the plan owner can archive a plan", http.StatusForbidden)returndiff --git a/server/handlers/plans_context.go b/server/handlers/plans_context.goindex 225db09e..ab7c2f34 100644--- a/server/handlers/plans_context.go+++ b/server/handlers/plans_context.go@@ -24,12 +24,13 @@ func ListContextHandler(w http.ResponseWriter, r *http.Request) {if auth == nil {return}+ currentUserId := auth.User.Idvars := mux.Vars(r)planId := vars["planId"]log.Println("planId: ", planId)- if authorizePlan(w, planId, auth.UserId, auth.OrgId) == nil {+ if authorizePlan(w, planId, currentUserId, auth.OrgId) == nil {return}@@ -65,12 +66,13 @@ func LoadContextHandler(w http.ResponseWriter, r *http.Request) {if auth == nil {return}+ currentUserId := auth.User.Idvars := mux.Vars(r)planId := vars["planId"]log.Println("planId: ", planId)- if authorizePlan(w, planId, auth.UserId, auth.OrgId) == nil {+ if authorizePlan(w, planId, currentUserId, auth.OrgId) == nil {return}@@ -153,7 +155,7 @@ func LoadContextHandler(w http.ResponseWriter, r *http.Request) {context := db.Context{// Id generated by db layerOrgId: auth.OrgId,- OwnerId: auth.UserId,+ OwnerId: currentUserId,PlanId: planId,ContextType: params.ContextType,Name: params.Name,@@ -233,12 +235,13 @@ func UpdateContextHandler(w http.ResponseWriter, r *http.Request) {if auth == nil {return}+ currentUserId := auth.User.Idvars := mux.Vars(r)planId := vars["planId"]log.Println("planId: ", planId)- if authorizePlan(w, planId, auth.UserId, auth.OrgId) == nil {+ if authorizePlan(w, planId, currentUserId, auth.OrgId) == nil {return}@@ -430,12 +433,13 @@ func DeleteContextHandler(w http.ResponseWriter, r *http.Request) {if auth == nil {return}+ currentUserId := auth.User.Idvars := mux.Vars(r)planId := vars["planId"]log.Println("planId: ", planId)- plan := authorizePlan(w, planId, auth.UserId, auth.OrgId)+ plan := authorizePlan(w, planId, currentUserId, auth.OrgId)if plan == nil {returndiff --git a/server/handlers/plans_convo.go b/server/handlers/plans_convo.goindex 919476e4..5810f1bd 100644--- a/server/handlers/plans_convo.go+++ b/server/handlers/plans_convo.go@@ -13,13 +13,14 @@ func ListConvoHandler(w http.ResponseWriter, r *http.Request) {if auth == nil {return}+ currentUserId := auth.User.Idvars := mux.Vars(r)planId := vars["planId"]log.Println("planId: ", planId)- if authorizePlan(w, planId, auth.UserId, auth.OrgId) == nil {+ if authorizePlan(w, planId, currentUserId, auth.OrgId) == nil {return}diff --git a/server/handlers/plans_crud.go b/server/handlers/plans_crud.goindex 89786911..112cfef2 100644--- a/server/handlers/plans_crud.go+++ b/server/handlers/plans_crud.go@@ -13,6 +13,8 @@ import ("github.com/plandex/plandex/shared")+const TrialMaxPlans = 10+func CreatePlanHandler(w http.ResponseWriter, r *http.Request) {log.Println("Received request for CreatePlanHandler")@@ -20,18 +22,19 @@ func CreatePlanHandler(w http.ResponseWriter, r *http.Request) {if auth == nil {return}+ currentUserId := auth.User.Idvars := mux.Vars(r)projectId := vars["projectId"]log.Println("projectId: ", projectId)- if !authorizeProject(w, projectId, auth.UserId, auth.OrgId) {+ if !authorizeProject(w, projectId, currentUserId, auth.OrgId) {return}if os.Getenv("IS_CLOUD") != "" {- user, err := db.GetUser(auth.UserId)+ user, err := db.GetUser(currentUserId)if err != nil {log.Printf("Error getting user: %v\n", err)@@ -40,9 +43,15 @@ func CreatePlanHandler(w http.ResponseWriter, r *http.Request) {}if user.IsTrial {- if user.NumNonDraftPlans >= 10 {- log.Println("User has reached max number of plans")- http.Error(w, "User has reached max number of free trial plans", http.StatusForbidden)+ if user.NumNonDraftPlans >= TrialMaxPlans {+ writeApiError(w, shared.ApiErr{+ Type: shared.ApiErrorTypeTrialPlansExceeded,+ Status: http.StatusForbidden,+ Msg: "User has reached max number of free trial plans",+ TrialPlansExceededError: &shared.TrialPlansExceededError{+ MaxPlans: TrialMaxPlans,+ },+ })return}}@@ -71,7 +80,7 @@ func CreatePlanHandler(w http.ResponseWriter, r *http.Request) {if name == "draft" {// delete any existing draft plans- err = db.DeleteDraftPlans(auth.OrgId, projectId, auth.UserId)+ err = db.DeleteDraftPlans(auth.OrgId, projectId, currentUserId)if err != nil {log.Printf("Error deleting draft plans: %v\n", err)@@ -83,7 +92,7 @@ func CreatePlanHandler(w http.ResponseWriter, r *http.Request) {originalName := namefor {var count int- err := db.Conn.Get(&count, "SELECT COUNT(*) FROM plans WHERE project_id = $1 AND owner_id = $2 AND name = $3", projectId, auth.UserId, name)+ err := db.Conn.Get(&count, "SELECT COUNT(*) FROM plans WHERE project_id = $1 AND owner_id = $2 AND name = $3", projectId, currentUserId, name)if err != nil {log.Printf("Error checking if plan exists: %v\n", err)@@ -100,7 +109,7 @@ func CreatePlanHandler(w http.ResponseWriter, r *http.Request) {}}- plan, err := db.CreatePlan(auth.OrgId, projectId, auth.UserId, name)+ plan, err := db.CreatePlan(auth.OrgId, projectId, currentUserId, name)if err != nil {log.Printf("Error creating plan: %v\n", err)@@ -133,13 +142,14 @@ func GetPlanHandler(w http.ResponseWriter, r *http.Request) {if auth == nil {return}+ currentUserId := auth.User.Idvars := mux.Vars(r)planId := vars["planId"]log.Println("planId: ", planId)- plan := authorizePlan(w, planId, auth.UserId, auth.OrgId)+ plan := authorizePlan(w, planId, currentUserId, auth.OrgId)if plan == nil {return@@ -163,19 +173,20 @@ func DeletePlanHandler(w http.ResponseWriter, r *http.Request) {if auth == nil {return}+ currentUserId := auth.User.Idvars := mux.Vars(r)planId := vars["planId"]log.Println("planId: ", planId)- plan := authorizePlan(w, planId, auth.UserId, auth.OrgId)+ plan := authorizePlan(w, planId, currentUserId, auth.OrgId)if plan == nil {return}- if plan.OwnerId != auth.UserId {+ if plan.OwnerId != currentUserId {log.Println("Only the plan owner can delete a plan")http.Error(w, "Only the plan owner can delete a plan", http.StatusForbidden)return@@ -220,17 +231,18 @@ func DeleteAllPlansHandler(w http.ResponseWriter, r *http.Request) {if auth == nil {return}+ currentUserId := auth.User.Idvars := mux.Vars(r)projectId := vars["projectId"]log.Println("projectId: ", projectId)- if !authorizeProject(w, projectId, auth.UserId, auth.OrgId) {+ if !authorizeProject(w, projectId, currentUserId, auth.OrgId) {return}- err := db.DeleteOwnerPlans(auth.OrgId, projectId, auth.UserId)+ err := db.DeleteOwnerPlans(auth.OrgId, projectId, currentUserId)if err != nil {log.Printf("Error deleting plans: %v\n", err)@@ -247,17 +259,18 @@ func ListPlansHandler(w http.ResponseWriter, r *http.Request) {if auth == nil {return}+ currentUserId := auth.User.Idvars := mux.Vars(r)projectId := vars["projectId"]log.Println("projectId: ", projectId)- if !authorizeProject(w, projectId, auth.UserId, auth.OrgId) {+ if !authorizeProject(w, projectId, currentUserId, auth.OrgId) {return}- plans, err := db.ListOwnedPlans(projectId, auth.UserId, false, "")+ plans, err := db.ListOwnedPlans(projectId, currentUserId, false, "")if err != nil {log.Printf("Error listing plans: %v\n", err)@@ -283,13 +296,14 @@ func ListArchivedPlansHandler(w http.ResponseWriter, r *http.Request) {if auth == nil {return}+ currentUserId := auth.User.Idvars := mux.Vars(r)projectId := vars["projectId"]log.Println("projectId: ", projectId)- if !authorizeProject(w, projectId, auth.UserId, auth.OrgId) {+ if !authorizeProject(w, projectId, currentUserId, auth.OrgId) {return}@@ -319,13 +333,14 @@ func ListPlansRunningHandler(w http.ResponseWriter, r *http.Request) {if auth == nil {return}+ currentUserId := auth.User.Idvars := mux.Vars(r)projectId := vars["projectId"]log.Println("projectId: ", projectId)- if !authorizeProject(w, projectId, auth.UserId, auth.OrgId) {+ if !authorizeProject(w, projectId, currentUserId, auth.OrgId) {return}diff --git a/server/handlers/plans_exec.go b/server/handlers/plans_exec.goindex b6ed845c..2fa41c86 100644--- a/server/handlers/plans_exec.go+++ b/server/handlers/plans_exec.go@@ -13,6 +13,8 @@ import ("github.com/plandex/plandex/shared")+const TrialMaxMessages = 15+func TellPlanHandler(w http.ResponseWriter, r *http.Request) {log.Println("Received request for TellPlanHandler")@@ -20,13 +22,14 @@ func TellPlanHandler(w http.ResponseWriter, r *http.Request) {if auth == nil {return}+ currentUserId := auth.User.Idvars := mux.Vars(r)planId := vars["planId"]log.Println("planId: ", planId)- plan := authorizePlan(w, planId, auth.UserId, auth.OrgId)+ plan := authorizePlan(w, planId, currentUserId, auth.OrgId)if plan == nil {return@@ -51,7 +54,7 @@ func TellPlanHandler(w http.ResponseWriter, r *http.Request) {}if os.Getenv("IS_CLOUD") != "" {- user, err := db.GetUser(auth.UserId)+ user, err := db.GetUser(currentUserId)if err != nil {log.Printf("Error getting user: %v\n", err)@@ -60,15 +63,21 @@ func TellPlanHandler(w http.ResponseWriter, r *http.Request) {}if user.IsTrial {- if plan.TotalMessages >= 15 {- log.Println("User has reached max number of messages")- http.Error(w, "User has reached max number of free trial messages", http.StatusForbidden)+ if plan.TotalMessages >= TrialMaxMessages {+ writeApiError(w, shared.ApiErr{+ Type: shared.ApiErrorTypeTrialMessagesExceeded,+ Status: http.StatusForbidden,+ Msg: "Free trial message limit exceeded",+ TrialMessagesExceededError: &shared.TrialMessagesExceededError{+ MaxMessages: TrialMaxMessages,+ },+ })return}}}- err = model.Tell(plan, auth.UserId, auth.OrgId, &requestBody)+ err = model.Tell(plan, currentUserId, auth.OrgId, &requestBody)if err != nil {log.Printf("Error telling plan: %v\n", err)@@ -93,13 +102,14 @@ func BuildPlanHandler(w http.ResponseWriter, r *http.Request) {if auth == nil {return}+ currentUserId := auth.User.Idvars := mux.Vars(r)planId := vars["planId"]log.Println("planId: ", planId)- if authorizePlan(w, planId, auth.UserId, auth.OrgId) == nil {+ if authorizePlan(w, planId, currentUserId, auth.OrgId) == nil {return}@@ -111,13 +121,14 @@ func ConnectPlanHandler(w http.ResponseWriter, r *http.Request) {if auth == nil {return}+ currentUserId := auth.User.Idvars := mux.Vars(r)planId := vars["planId"]log.Println("planId: ", planId)- if authorizePlan(w, planId, auth.UserId, auth.OrgId) == nil {+ if authorizePlan(w, planId, currentUserId, auth.OrgId) == nil {return}@@ -129,13 +140,14 @@ func StopPlanHandler(w http.ResponseWriter, r *http.Request) {if auth == nil {return}+ currentUserId := auth.User.Idvars := mux.Vars(r)planId := vars["planId"]log.Println("planId: ", planId)- if authorizePlan(w, planId, auth.UserId, auth.OrgId) == nil {+ if authorizePlan(w, planId, currentUserId, auth.OrgId) == nil {return}diff --git a/server/handlers/plans_versions.go b/server/handlers/plans_versions.goindex 593a03a8..8e36ad31 100644--- a/server/handlers/plans_versions.go+++ b/server/handlers/plans_versions.go@@ -18,13 +18,14 @@ func ListLogsHandler(w http.ResponseWriter, r *http.Request) {if auth == nil {return}+ currentUserId := auth.User.Idvars := mux.Vars(r)planId := vars["planId"]log.Println("planId: ", planId)- if authorizePlan(w, planId, auth.UserId, auth.OrgId) == nil {+ if authorizePlan(w, planId, currentUserId, auth.OrgId) == nil {return}@@ -61,13 +62,14 @@ func RewindPlanHandler(w http.ResponseWriter, r *http.Request) {if auth == nil {return}+ currentUserId := auth.User.Idvars := mux.Vars(r)planId := vars["planId"]log.Println("planId: ", planId)- if authorizePlan(w, planId, auth.UserId, auth.OrgId) == nil {+ if authorizePlan(w, planId, currentUserId, auth.OrgId) == nil {return}diff --git a/server/handlers/projects.go b/server/handlers/projects.goindex cdf02551..bdb34594 100644--- a/server/handlers/projects.go+++ b/server/handlers/projects.go@@ -18,6 +18,7 @@ func CreateProjectHandler(w http.ResponseWriter, r *http.Request) {if auth == nil {return}+ currentUserId := auth.User.Id// read the request bodybody, err := io.ReadAll(r.Body)@@ -69,7 +70,7 @@ func CreateProjectHandler(w http.ResponseWriter, r *http.Request) {return}- _, err = tx.Exec("INSERT INTO users_projects (user_id, org_id, project_id) VALUES ($1, $2, $3)", auth.UserId, auth.OrgId, projectId)+ _, err = tx.Exec("INSERT INTO users_projects (user_id, org_id, project_id) VALUES ($1, $2, $3)", currentUserId, auth.OrgId, projectId)if err != nil {log.Printf("Error adding owner to project: %v\n", err)@@ -108,8 +109,9 @@ func ListProjectsHandler(w http.ResponseWriter, r *http.Request) {if auth == nil {return}+ currentUserId := auth.User.Id- rows, err := db.Conn.Query("SELECT project.id, project.name FROM users_projects INNER JOIN project ON users_projects.project_id = project.id WHERE users_projects.user_id = $1 AND users_projects.org_id = $2", auth.UserId, auth.OrgId)+ rows, err := db.Conn.Query("SELECT project.id, project.name FROM users_projects INNER JOIN project ON users_projects.project_id = project.id WHERE users_projects.user_id = $1 AND users_projects.org_id = $2", currentUserId, auth.OrgId)if err != nil {log.Printf("Error listing projects: %v\n", err)@@ -146,13 +148,14 @@ func ProjectSetPlanHandler(w http.ResponseWriter, r *http.Request) {if auth == nil {return}+ currentUserId := auth.User.Idvars := mux.Vars(r)projectId := vars["projectId"]log.Println("projectId: ", projectId)- if !authorizeProject(w, projectId, auth.UserId, auth.OrgId) {+ if !authorizeProject(w, projectId, currentUserId, auth.OrgId) {return}@@ -195,13 +198,14 @@ func RenameProjectHandler(w http.ResponseWriter, r *http.Request) {if auth == nil {return}+ currentUserId := auth.User.Idvars := mux.Vars(r)projectId := vars["projectId"]log.Println("projectId: ", projectId)- if !authorizeProject(w, projectId, auth.UserId, auth.OrgId) {+ if !authorizeProject(w, projectId, currentUserId, auth.OrgId) {return}diff --git a/server/handlers/sessions.go b/server/handlers/sessions.gonew file mode 100644index 00000000..95d6be07--- /dev/null+++ b/server/handlers/sessions.go@@ -0,0 +1,221 @@+package handlers++import (+ "crypto/sha256"+ "encoding/hex"+ "encoding/json"+ "io"+ "log"+ "net/http"+ "plandex-server/db"+ "plandex-server/email"+ "strings"++ "github.com/plandex/plandex/shared"+)++func CreateEmailVerificationHandler(w http.ResponseWriter, r *http.Request) {+ log.Println("Received request for CreateEmailVerificationHandler")++ // read the request body+ body, err := io.ReadAll(r.Body)+ if err != nil {+ log.Printf("Error reading request body: %v\n", err)+ http.Error(w, "Error reading request body: "+err.Error(), http.StatusInternalServerError)+ return+ }++ var req shared.CreateEmailVerificationRequest+ err = json.Unmarshal(body, &req)+ if err != nil {+ log.Printf("Error unmarshalling request: %v\n", err)+ http.Error(w, "Error unmarshalling request: "+err.Error(), http.StatusInternalServerError)+ return+ }+ req.Email = strings.ToLower(req.Email)++ // create pin - 6 alphanumeric characters+ pinBytes, err := shared.GetRandomAlphanumeric(6)+ if err != nil {+ log.Printf("Error generating random pin: %v\n", err)+ http.Error(w, "Error generating random pin: "+err.Error(), http.StatusInternalServerError)+ return+ }++ // get sha256 hash of pin+ hashBytes := sha256.Sum256(pinBytes)+ pinHash := hex.EncodeToString(hashBytes[:])++ // create verification+ err = db.CreateEmailVerification(req.Email, pinHash, req.UserId)++ if err != nil {+ log.Printf("Error creating email verification: %v\n", err)+ http.Error(w, "Error creating email verification: "+err.Error(), http.StatusInternalServerError)+ return+ }++ err = email.SendVerificationEmail(req.Email, string(pinBytes))++ if err != nil {+ log.Printf("Error sending verification email: %v\n", err)+ http.Error(w, "Error sending verification email: "+err.Error(), http.StatusInternalServerError)+ return+ }++ res := shared.CreateEmailVerificationResponse{+ HasAccount: true,+ }++ bytes, err := json.Marshal(res)++ if err != nil {+ log.Printf("Error marshalling response: %v\n", err)+ http.Error(w, "Error marshalling response: "+err.Error(), http.StatusInternalServerError)+ return+ }++ log.Println("Successfully created email verification")++ w.Write(bytes)+}++func SignInHandler(w http.ResponseWriter, r *http.Request) {+ log.Println("Received request for SignInHandler")++ // read the request body+ body, err := io.ReadAll(r.Body)+ if err != nil {+ log.Printf("Error reading request body: %v\n", err)+ http.Error(w, "Error reading request body: "+err.Error(), http.StatusInternalServerError)+ return+ }++ var req shared.SignInRequest+ err = json.Unmarshal(body, &req)+ if err != nil {+ log.Printf("Error unmarshalling request: %v\n", err)+ http.Error(w, "Error unmarshalling request: "+err.Error(), http.StatusInternalServerError)+ return+ }++ emailVerificationId, err := db.ValidateEmailVerification(req.Email, req.Pin)++ if err != nil {+ log.Printf("Error validating email verification: %v\n", err)+ http.Error(w, "Error validating email verification: "+err.Error(), http.StatusInternalServerError)+ return+ }++ user, err := db.GetUserByEmail(req.Email)++ if err != nil {+ log.Printf("Error getting user: %v\n", err)+ http.Error(w, "Error getting user: "+err.Error(), http.StatusInternalServerError)+ return+ }++ if user == nil {+ log.Printf("User not found for email: %v\n", req.Email)+ http.Error(w, "Not found", http.StatusNotFound)+ return+ }++ // start a transaction+ tx, err := db.Conn.Begin()+ if err != nil {+ log.Printf("Error starting transaction: %v\n", err)+ http.Error(w, "Error starting transaction: "+err.Error(), http.StatusInternalServerError)+ return+ }++ // Ensure that rollback is attempted in case of failure+ defer func() {+ if err != nil {+ if rbErr := tx.Rollback(); rbErr != nil {+ log.Printf("transaction rollback error: %v\n", rbErr)+ } else {+ log.Println("transaction rolled back")+ }+ }+ }()++ // create auth token+ token, authTokenId, err := db.CreateAuthToken(user.Id, tx)++ if err != nil {+ log.Printf("Error creating auth token: %v\n", err)+ http.Error(w, "Error creating auth token: "+err.Error(), http.StatusInternalServerError)+ return+ }++ // update email verification with user and auth token ids+ _, err = tx.Exec("UPDATE email_verifications SET user_id = $1, auth_token_id = $2 WHERE id = $3", user.Id, authTokenId, emailVerificationId)++ if err != nil {+ log.Printf("Error updating email verification: %v\n", err)+ http.Error(w, "Error updating email verification: "+err.Error(), http.StatusInternalServerError)+ return+ }++ // commit transaction+ err = tx.Commit()+ if err != nil {+ log.Printf("Error committing transaction: %v\n", err)+ http.Error(w, "Error committing transaction: "+err.Error(), http.StatusInternalServerError)+ return+ }++ // get orgs+ orgs, err := db.GetAccessibleOrgsForUser(user)++ if err != nil {+ log.Printf("Error getting orgs for user: %v\n", err)+ http.Error(w, "Error getting orgs for user: "+err.Error(), http.StatusInternalServerError)+ return+ }++ var apiOrgs []*shared.Org+ for _, org := range orgs {+ apiOrgs = append(apiOrgs, org.ToApi())+ }++ resp := shared.SessionResponse{+ UserId: user.Id,+ Token: token,+ Email: user.Email,+ UserName: user.Name,+ Orgs: apiOrgs,+ }++ bytes, err := json.Marshal(resp)++ if err != nil {+ log.Printf("Error marshalling response: %v\n", err)+ http.Error(w, "Error marshalling response: "+err.Error(), http.StatusInternalServerError)+ return+ }++ log.Println("Successfully signed in")++ w.Write(bytes)+}++func SignOutHandler(w http.ResponseWriter, r *http.Request) {+ log.Println("Received request for SignOutHandler")++ auth := authenticate(w, r, false)+ if auth == nil {+ return+ }++ _, err := db.Conn.Exec("UPDATE auth_tokens SET deleted_at = NOW() WHERE token_hash = $1", auth.AuthToken.TokenHash)++ if err != nil {+ log.Printf("Error deleting auth token: %v\n", err)+ http.Error(w, "Error deleting auth token: "+err.Error(), http.StatusInternalServerError)+ return+ }++ log.Println("Successfully signed out")+}diff --git a/server/handlers/users.go b/server/handlers/users.gonew file mode 100644index 00000000..149db53f--- /dev/null+++ b/server/handlers/users.go@@ -0,0 +1,121 @@+package handlers++import (+ "encoding/json"+ "log"+ "net/http"+ "plandex-server/db"++ "github.com/gorilla/mux"+)++func ListUsersHandler(w http.ResponseWriter, r *http.Request) {+ log.Println("Received a request for ListUsersHandler")+ auth := authenticate(w, r, true)+ if auth == nil {+ return+ }++ if auth.User.IsTrial {+ log.Println("Trial user cannot list users")+ http.Error(w, "Trial user cannot list users", http.StatusForbidden)+ return+ }++ users, err := db.ListUsers(auth.OrgId)+ if err != nil {+ log.Println("Error listing users: ", err)+ http.Error(w, "Error listing users: "+err.Error(), http.StatusInternalServerError)+ }++ bytes, err := json.Marshal(users)++ if err != nil {+ log.Println("Error marshalling users: ", err)+ http.Error(w, "Error marshalling users: "+err.Error(), http.StatusInternalServerError)+ return+ }++ log.Println("Successfully processed request for ListUsersHandler")++ w.Write(bytes)+}++func DeleteOrgUserHandler(w http.ResponseWriter, r *http.Request) {+ log.Println("Received a request for DeleteOrgUserHandler")+ auth := authenticate(w, r, true)+ if auth == nil {+ return+ }++ if auth.User.IsTrial {+ log.Println("Trial user cannot delete users")+ http.Error(w, "Trial user cannot delete users", http.StatusForbidden)+ return+ }++ vars := mux.Vars(r)+ userId := vars["userId"]++ // verify user is org member+ isMember, err := db.ValidateOrgMembership(userId, auth.OrgId)++ if err != nil {+ log.Printf("Error validating org membership: %v\n", err)+ http.Error(w, "Error validating org membership: "+err.Error(), http.StatusInternalServerError)+ return+ }++ if !isMember {+ log.Printf("User %s is not a member of org %s\n", userId, auth.OrgId)+ http.Error(w, "User "+userId+" is not a member of org "+auth.OrgId, http.StatusForbidden)+ return+ }++ // start a transaction+ tx, err := db.Conn.Begin()+ if err != nil {+ log.Printf("Error starting transaction: %v\n", err)+ http.Error(w, "Error starting transaction: "+err.Error(), http.StatusInternalServerError)+ return+ }++ // Ensure that rollback is attempted in case of failure+ defer func() {+ if err != nil {+ if rbErr := tx.Rollback(); rbErr != nil {+ log.Printf("transaction rollback error: %v\n", rbErr)+ } else {+ log.Println("transaction rolled back")+ }+ }+ }()++ err = db.DeleteOrgUser(userId, auth.OrgId, tx)++ if err != nil {+ log.Println("Error deleting org user: ", err)+ http.Error(w, "Error deleting org user: "+err.Error(), http.StatusInternalServerError)+ return+ }++ invite, err := db.GetInviteForOrgUser(auth.OrgId, userId)++ if err != nil {+ log.Println("Error getting invite for org user: ", err)+ http.Error(w, "Error getting invite for org user: "+err.Error(), http.StatusInternalServerError)+ return+ }++ if invite != nil {+ err = db.DeleteInvite(invite.Id, tx)++ if err != nil {+ log.Println("Error deleting invite: ", err)+ http.Error(w, "Error deleting invite: "+err.Error(), http.StatusInternalServerError)+ return+ }+ }++ log.Println("Successfully processed request for DeleteOrgUserHandler")+}diff --git a/server/migrations/2023120500_init.down.sql b/server/migrations/2023120500_init.down.sqlindex a89d3a65..2d23a548 100644--- a/server/migrations/2023120500_init.down.sql+++ b/server/migrations/2023120500_init.down.sql@@ -8,6 +8,7 @@ DROP TABLE IF EXISTS orgs_users;DROP TABLE IF EXISTS email_verifications;DROP TABLE IF EXISTS auth_tokens;+DROP TABLE IF EXISTS invites;DROP TABLE IF EXISTS orgs;DROP TABLE IF EXISTS users;diff --git a/server/migrations/2023120500_init.up.sql b/server/migrations/2023120500_init.up.sqlindex c0eb667b..38e7822b 100644--- a/server/migrations/2023120500_init.up.sql+++ b/server/migrations/2023120500_init.up.sql@@ -12,6 +12,7 @@ CREATE TABLE IF NOT EXISTS users (id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),name VARCHAR(255) NOT NULL,email VARCHAR(255) NOT NULL,+ domain VARCHAR(255) NOT NULL,is_trial BOOLEAN NOT NULL,num_non_draft_plans INTEGER NOT NULL DEFAULT 0,created_at TIMESTAMP NOT NULL DEFAULT NOW(),@@ -20,6 +21,7 @@ CREATE TABLE IF NOT EXISTS users (CREATE TRIGGER update_users_modtime BEFORE UPDATE ON users FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();ALTER TABLE users ADD UNIQUE (email);+CREATE INDEX users_domain_idx ON users(domain);CREATE TABLE IF NOT EXISTS orgs (id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),@@ -44,7 +46,25 @@ CREATE TABLE IF NOT EXISTS orgs_users ();CREATE TRIGGER update_orgs_users_modtime BEFORE UPDATE ON orgs_users FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();-CREATE INDEX orgs_users_idx ON orgs_users(user_id);+CREATE INDEX orgs_users_user_idx ON orgs_users(user_id);+CREATE INDEX orgs_users_org_idx ON orgs_users(org_id);++CREATE TABLE IF NOT EXISTS invites (+ id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),+ org_id UUID NOT NULL REFERENCES orgs(id) ON DELETE CASCADE,+ name VARCHAR(255) NOT NULL,+ email VARCHAR(255) NOT NULL,+ inviter_id UUID NOT NULL REFERENCES users(id),+ invitee_id UUID REFERENCES users(id),+ accepted_at TIMESTAMP,+ created_at TIMESTAMP NOT NULL DEFAULT NOW(),+ updated_at TIMESTAMP NOT NULL DEFAULT NOW()+);+CREATE TRIGGER update_invites_modtime BEFORE UPDATE ON invites FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();++CREATE INDEX invites_pending_idx ON invites(org_id, (accepted_at IS NULL));+CREATE INDEX invites_email_idx ON invites(email, (accepted_at IS NULL));+CREATE INDEX invites_org_user_idx ON invites(org_id, invitee_id);CREATE TABLE IF NOT EXISTS auth_tokens (id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),diff --git a/server/routes.go b/server/routes.goindex 9bbb1b20..8eecbbb0 100644--- a/server/routes.go+++ b/server/routes.go@@ -20,9 +20,20 @@ func InitRoutes() *mux.Router {r.HandleFunc("/accounts/sign_in", handlers.SignInHandler).Methods("POST")r.HandleFunc("/accounts/sign_out", handlers.SignOutHandler).Methods("POST")r.HandleFunc("/accounts", handlers.CreateAccountHandler).Methods("POST")+ r.HandleFunc("/accounts/convert_trial", handlers.ConvertTrialHandler).Methods("POST")+ r.HandleFunc("/orgs", handlers.ListOrgsHandler).Methods("GET")r.HandleFunc("/orgs", handlers.CreateOrgHandler).Methods("POST")+ r.HandleFunc("/users", handlers.ListUsersHandler).Methods("GET")+ r.HandleFunc("/orgs/users/{userId}", handlers.DeleteOrgUserHandler).Methods("DELETE")++ r.HandleFunc("/invites", handlers.InviteUserHandler).Methods("POST")+ r.HandleFunc("/invites/pending", handlers.ListPendingInvitesHandler).Methods("GET")+ r.HandleFunc("/invites/accepted", handlers.ListAcceptedInvitesHandler).Methods("GET")+ r.HandleFunc("/invites/all", handlers.ListAllInvitesHandler).Methods("GET")+ r.HandleFunc("/invites/{inviteId}", handlers.DeleteInviteHandler).Methods("DELETE")+r.HandleFunc("/projects", handlers.CreateProjectHandler).Methods("POST")r.HandleFunc("/projects", handlers.ListProjectsHandler).Methods("GET")r.HandleFunc("/projects/{projectId}/set_plan", handlers.ProjectSetPlanHandler).Methods("PUT")diff --git a/server/types/auth.go b/server/types/auth.goindex 7757bf3f..03772793 100644--- a/server/types/auth.go+++ b/server/types/auth.go@@ -1,7 +1,9 @@package types+import "plandex-server/db"+type ServerAuth struct {- UserId string+ AuthToken *db.AuthToken+ User *db.UserOrgId string- TokenHash string}diff --git a/shared/auth.go b/shared/auth.goindex 211152d9..2eddb129 100644--- a/shared/auth.go+++ b/shared/auth.go@@ -4,3 +4,32 @@ type AuthHeader struct {Token string `json:"token"`OrgId string `json:"orgId"`}++type ApiErrorType string++const (+ ApiErrorTypeInvalidToken ApiErrorType = "invalid_token"+ ApiErrorTypeTrialPlansExceeded ApiErrorType = "trial_plans_exceeded"+ ApiErrorTypeTrialMessagesExceeded ApiErrorType = "trial_messages_exceeded"+ ApiErrorTypeOther ApiErrorType = "other"+)++type TrialPlansExceededError struct {+ MaxPlans int `json:"maxPlans"`+}++type TrialMessagesExceededError struct {+ MaxMessages int `json:"maxMessages"`+}++type ApiError struct {+ Type ApiErrorType `json:"type"`+ Status int `json:"status"`+ Msg string `json:"msg"`++ // only used for trial plans exceeded error+ TrialPlansExceededError *TrialPlansExceededError `json:"trialPlansExceededError,omitempty"`++ // only used for trial messages exceeded error+ TrialMessagesExceededError *TrialMessagesExceededError `json:"trialMessagesExceededError,omitempty"`+}diff --git a/shared/email.go b/shared/email.gonew file mode 100644index 00000000..39e61410--- /dev/null+++ b/shared/email.go@@ -0,0 +1,135 @@+package shared++func IsEmailServiceDomain(domain string) bool {+ _, ok := emailServiceDomains[domain]+ return ok+}++var emailServiceDomains = map[string]bool{+ "gmail.com": true,+ "yahoo.com": true,+ "outlook.com": true,+ "hotmail.com": true,+ "icloud.com": true,+ "zoho.com": true,+ "protonmail.com": true,+ "mail.com": true,+ "yandex.com": true,+ "fastmail.com": true,+ "tutanota.com": true,+ "hey.com": true,+ "hushmail.com": true,+ "runbox.com": true,+ "mailfence.com": true,+ "disroot.org": true,+ "posteo.de": true,+ "mailinator.com": true,+ "aol.com": true,+ "hotmail.co.uk": true,+ "hotmail.fr": true,+ "msn.com": true,+ "yahoo.fr": true,+ "wanadoo.fr": true,+ "orange.fr": true,+ "comcast.net": true,+ "yahoo.co.uk": true,+ "yahoo.com.br": true,+ "yahoo.co.in": true,+ "live.com": true,+ "rediffmail.com": true,+ "free.fr": true,+ "gmx.de": true,+ "web.de": true,+ "yandex.ru": true,+ "ymail.com": true,+ "libero.it": true,+ "uol.com.br": true,+ "bol.com.br": true,+ "mail.ru": true,+ "cox.net": true,+ "hotmail.it": true,+ "sbcglobal.net": true,+ "sfr.fr": true,+ "live.fr": true,+ "verizon.net": true,+ "live.co.uk": true,+ "googlemail.com": true,+ "yahoo.es": true,+ "ig.com.br": true,+ "live.nl": true,+ "bigpond.com": true,+ "terra.com.br": true,+ "yahoo.it": true,+ "neuf.fr": true,+ "yahoo.de": true,+ "alice.it": true,+ "rocketmail.com": true,+ "att.net": true,+ "laposte.net": true,+ "facebook.com": true,+ "bellsouth.net": true,+ "yahoo.in": true,+ "hotmail.es": true,+ "charter.net": true,+ "yahoo.ca": true,+ "yahoo.com.au": true,+ "rambler.ru": true,+ "hotmail.de": true,+ "tiscali.it": true,+ "shaw.ca": true,+ "yahoo.co.jp": true,+ "sky.com": true,+ "earthlink.net": true,+ "optonline.net": true,+ "freenet.de": true,+ "t-online.de": true,+ "aliceadsl.fr": true,+ "virgilio.it": true,+ "home.nl": true,+ "qq.com": true,+ "telenet.be": true,+ "me.com": true,+ "yahoo.com.ar": true,+ "tiscali.co.uk": true,+ "yahoo.com.mx": true,+ "voila.fr": true,+ "gmx.net": true,+ "planet.nl": true,+ "tin.it": true,+ "live.it": true,+ "ntlworld.com": true,+ "arcor.de": true,+ "yahoo.co.id": true,+ "frontiernet.net": true,+ "hetnet.nl": true,+ "live.com.au": true,+ "yahoo.com.sg": true,+ "zonnet.nl": true,+ "club-internet.fr": true,+ "juno.com": true,+ "optusnet.com.au": true,+ "blueyonder.co.uk": true,+ "bluewin.ch": true,+ "skynet.be": true,+ "sympatico.ca": true,+ "windstream.net": true,+ "mac.com": true,+ "centurytel.net": true,+ "chello.nl": true,+ "live.ca": true,+ "aim.com": true,+ "bigpond.net.au": true,+ "163.com": true,+ "126.com": true,+ "daum.net": true,+ "naver.com": true,+ "sina.com": true,+ "sohu.com": true,+ "gmx.com": true,+ "yopmail.com": true,+ "bk.ru": true,+ "list.ru": true,+ "seznam.cz": true,+ "nextmail.ru": true,+ "kpnmail.nl": true,+}diff --git a/shared/models.go b/shared/models.goindex f4985ab3..c3ebbded 100644--- a/shared/models.go+++ b/shared/models.go@@ -3,8 +3,9 @@ package sharedimport "time"type Org struct {- Id string `json:"id"`- Name string `json:"name"`+ Id string `json:"id"`+ Name string `json:"name"`+ IsPending bool `json:"isPending"`}type User struct {@@ -15,6 +16,17 @@ type User struct {NumNonDraftPlans int `db:"num_non_draft_plans"`}+type Invite struct {+ Id string `json:"id"`+ OrgId string `json:"orgId"`+ Email string `json:"email"`+ Name string `json:"name"`+ InviterId string `json:"inviterId"`+ InviteeId string `json:"inviteeId"`+ AcceptedAt *time.Time `json:"acceptedAt"`+ CreatedAt time.Time `json:"createdAt"`+}+type Project struct {Id string `json:"id"`Name string `json:"name"`diff --git a/shared/req_res.go b/shared/req_res.goindex e09d6b95..83437527 100644--- a/shared/req_res.go+++ b/shared/req_res.go@@ -14,6 +14,10 @@ type CreateEmailVerificationRequest struct {UserId string `json:"userId"`}+type CreateEmailVerificationResponse struct {+ HasAccount bool `json:"hasAccount"`+}+type SignInRequest struct {Email string `json:"email"`Pin string `json:"pin"`@@ -35,14 +39,26 @@ type SessionResponse struct {type CreateOrgRequest struct {Name string `json:"name"`- Domain string `json:"domain"`AutoAddDomainUsers bool `json:"autoAddDomainUsers"`}+type ConvertTrialRequest struct {+ Email string `json:"email"`+ Pin string `json:"pin"`+ UserName string `json:"userName"`+ OrgName string `json:"orgName"`+ OrgAutoAddDomainUsers bool `json:"orgAutoAddDomainUsers"`+}+type CreateOrgResponse struct {Id string `json:"id"`}+type InviteRequest struct {+ Email string `json:"email"`+ Name string `json:"name"`+}+type CreateProjectRequest struct {Name string `json:"name"`}