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 accounts/auth
Dane Schneidere76ca895dba2
diff --git a/cli/api/clients.go b/cli/api/clients.goindex 0a88c30d..fd71e507 100644--- a/cli/api/clients.go+++ b/cli/api/clients.go@@ -3,7 +3,6 @@ package apiimport ("net""net/http"- "os""plandex/auth""plandex/types""time"@@ -15,16 +14,23 @@ const slowReqTimeout = 5 * time.Minutetype Api struct{}-var apiHost string+var cloudApiHost stringvar Client types.ApiClient = (*Api)(nil)func init() {- var port = os.Getenv("PORT")- if port == "" {- port = "8088"+ // TODO: set this to the actual cloud api host in production+ cloudApiHost = "http://localhost:8088"+}++func getApiHost() string {+ if auth.Current == nil {+ return ""+ } else if auth.Current.IsCloud {+ return cloudApiHost+ } else {+ return auth.Current.Host}- apiHost = "http://localhost:" + port}type authenticatedTransport struct {diff --git a/cli/api/methods.go b/cli/api/methods.goindex 5afe5f92..af656596 100644--- a/cli/api/methods.go+++ b/cli/api/methods.go@@ -13,7 +13,7 @@ import ()func (a *Api) StartTrial() (*shared.StartTrialResponse, error) {- serverUrl := apiHost + "/accounts/start-trial"+ serverUrl := cloudApiHost + "/accounts/start_trial"resp, err := unauthenticatedClient.Post(serverUrl, "application/json", nil)if err != nil {@@ -37,7 +37,7 @@ func (a *Api) StartTrial() (*shared.StartTrialResponse, error) {}func (a *Api) CreateProject(req shared.CreateProjectRequest) (*shared.CreateProjectResponse, error) {- serverUrl := apiHost + "/projects"+ serverUrl := getApiHost() + "/projects"reqBytes, err := json.Marshal(req)if err != nil {return nil, fmt.Errorf("error marshalling request: %v", err)@@ -64,7 +64,7 @@ func (a *Api) CreateProject(req shared.CreateProjectRequest) (*shared.CreateProj}func (a *Api) ListProjects() ([]*shared.Project, error) {- serverUrl := apiHost + "/projects"+ serverUrl := getApiHost() + "/projects"resp, err := authenticatedFastClient.Get(serverUrl)if err != nil {return nil, fmt.Errorf("error sending request: %v", err)@@ -86,7 +86,7 @@ func (a *Api) ListProjects() ([]*shared.Project, error) {}func (a *Api) SetProjectPlan(projectId string, req shared.SetProjectPlanRequest) error {- serverUrl := fmt.Sprintf("%s/projects/%s/set-plan", apiHost, projectId)+ 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)@@ -113,7 +113,7 @@ func (a *Api) SetProjectPlan(projectId string, req shared.SetProjectPlanRequest)}func (a *Api) RenameProject(projectId string, req shared.RenameProjectRequest) error {- serverUrl := fmt.Sprintf("%s/projects/%s/rename", apiHost, projectId)+ 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)@@ -140,7 +140,7 @@ func (a *Api) RenameProject(projectId string, req shared.RenameProjectRequest) e}func (a *Api) ListPlans(projectId string) ([]*shared.Plan, error) {- serverUrl := fmt.Sprintf("%s/projects/%s/plans", apiHost, projectId)+ serverUrl := fmt.Sprintf("%s/projects/%s/plans", getApiHost(), projectId)resp, err := authenticatedFastClient.Get(serverUrl)if err != nil {@@ -163,7 +163,7 @@ func (a *Api) ListPlans(projectId string) ([]*shared.Plan, error) {}func (a *Api) ListArchivedPlans(projectId string) ([]*shared.Plan, error) {- serverUrl := fmt.Sprintf("%s/projects/%s/plans/archive", apiHost, projectId)+ serverUrl := fmt.Sprintf("%s/projects/%s/plans/archive", getApiHost(), projectId)resp, err := authenticatedFastClient.Get(serverUrl)if err != nil {@@ -186,7 +186,7 @@ func (a *Api) ListArchivedPlans(projectId string) ([]*shared.Plan, error) {}func (a *Api) ListPlansRunning(projectId string) ([]*shared.Plan, error) {- serverUrl := fmt.Sprintf("%s/projects/%s/plans/ps", apiHost, projectId)+ serverUrl := fmt.Sprintf("%s/projects/%s/plans/ps", getApiHost(), projectId)resp, err := authenticatedFastClient.Get(serverUrl)if err != nil {@@ -209,7 +209,7 @@ func (a *Api) ListPlansRunning(projectId string) ([]*shared.Plan, error) {}func (a *Api) CreatePlan(projectId string, req shared.CreatePlanRequest) (*shared.CreatePlanResponse, error) {- serverUrl := fmt.Sprintf("%s/projects/%s/plans", apiHost, projectId)+ 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)@@ -236,7 +236,7 @@ func (a *Api) CreatePlan(projectId string, req shared.CreatePlanRequest) (*share}func (a *Api) GetPlan(planId string) (*shared.Plan, error) {- serverUrl := fmt.Sprintf("%s/plans/%s", apiHost, planId)+ serverUrl := fmt.Sprintf("%s/plans/%s", getApiHost(), planId)resp, err := authenticatedFastClient.Get(serverUrl)if err != nil {@@ -260,7 +260,7 @@ func (a *Api) GetPlan(planId string) (*shared.Plan, error) {}func (a *Api) DeletePlan(planId string) error {- serverUrl := fmt.Sprintf("%s/plans/%s", apiHost, planId)+ serverUrl := fmt.Sprintf("%s/plans/%s", getApiHost(), planId)req, err := http.NewRequest(http.MethodDelete, serverUrl, nil)if err != nil {@@ -282,7 +282,7 @@ func (a *Api) DeletePlan(planId string) error {}func (a *Api) DeleteAllPlans(projectId string) error {- serverUrl := fmt.Sprintf("%s/projects/%s/plans", apiHost, projectId)+ serverUrl := fmt.Sprintf("%s/projects/%s/plans", getApiHost(), projectId)req, err := http.NewRequest(http.MethodDelete, serverUrl, nil)if err != nil {@@ -305,7 +305,7 @@ func (a *Api) DeleteAllPlans(projectId string) error {func (a *Api) TellPlan(planId string, req shared.TellPlanRequest, onStream types.OnStreamPlan) error {- serverUrl := fmt.Sprintf("%s/plans/%s/tell", apiHost, planId)+ 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)@@ -343,7 +343,7 @@ func (a *Api) TellPlan(planId string, req shared.TellPlanRequest, onStream types}func (a *Api) ConnectPlan(planId string, onStream types.OnStreamPlan) error {- serverUrl := fmt.Sprintf("%s/plans/%s/connect", apiHost, planId)+ serverUrl := fmt.Sprintf("%s/plans/%s/connect", getApiHost(), planId)req, err := http.NewRequest(http.MethodPatch, serverUrl, nil)if err != nil {@@ -367,7 +367,7 @@ func (a *Api) ConnectPlan(planId string, onStream types.OnStreamPlan) error {}func (a *Api) StopPlan(planId string) error {- serverUrl := fmt.Sprintf("%s/plans/%s/stop", apiHost, planId)+ serverUrl := fmt.Sprintf("%s/plans/%s/stop", getApiHost(), planId)req, err := http.NewRequest(http.MethodDelete, serverUrl, nil)if err != nil {@@ -389,7 +389,7 @@ func (a *Api) StopPlan(planId string) error {}func (a *Api) GetCurrentPlanState(planId string) (*shared.CurrentPlanState, error) {- serverUrl := fmt.Sprintf("%s/plans/%s/current_plan", apiHost, planId)+ serverUrl := fmt.Sprintf("%s/plans/%s/current_plan", getApiHost(), planId)resp, err := authenticatedFastClient.Get(serverUrl)if err != nil {@@ -412,7 +412,7 @@ func (a *Api) GetCurrentPlanState(planId string) (*shared.CurrentPlanState, erro}func (a *Api) ApplyPlan(planId string) error {- serverUrl := fmt.Sprintf("%s/plans/%s/apply", apiHost, planId)+ serverUrl := fmt.Sprintf("%s/plans/%s/apply", getApiHost(), planId)req, err := http.NewRequest(http.MethodPatch, serverUrl, nil)if err != nil {@@ -434,7 +434,7 @@ func (a *Api) ApplyPlan(planId string) error {}func (a *Api) ArchivePlan(planId string) error {- serverUrl := fmt.Sprintf("%s/plans/%s/archive", apiHost, planId)+ serverUrl := fmt.Sprintf("%s/plans/%s/archive", getApiHost(), planId)req, err := http.NewRequest(http.MethodPatch, serverUrl, nil)if err != nil {@@ -456,7 +456,7 @@ func (a *Api) ArchivePlan(planId string) error {}func (a *Api) RejectAllChanges(planId string) error {- serverUrl := fmt.Sprintf("%s/plans/%s/reject_all", apiHost, planId)+ serverUrl := fmt.Sprintf("%s/plans/%s/reject_all", getApiHost(), planId)req, err := http.NewRequest(http.MethodPatch, serverUrl, nil)if err != nil {@@ -478,7 +478,7 @@ func (a *Api) RejectAllChanges(planId string) error {}func (a *Api) RejectResult(planId, resultId string) error {- serverUrl := fmt.Sprintf("%s/plans/%s/results/%s/reject", apiHost, planId, resultId)+ serverUrl := fmt.Sprintf("%s/plans/%s/results/%s/reject", getApiHost(), planId, resultId)req, err := http.NewRequest(http.MethodPatch, serverUrl, nil)if err != nil {@@ -500,7 +500,7 @@ func (a *Api) RejectResult(planId, resultId string) error {}func (a *Api) RejectReplacement(planId, resultId, replacementId string) error {- serverUrl := fmt.Sprintf("%s/plans/%s/results/%s/replacements/%s/reject", apiHost, planId, resultId, replacementId)+ 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 {@@ -522,7 +522,7 @@ func (a *Api) RejectReplacement(planId, resultId, replacementId string) error {}func (a *Api) LoadContext(planId string, req shared.LoadContextRequest) (*shared.LoadContextResponse, error) {- serverUrl := fmt.Sprintf("%s/plans/%s/context", apiHost, planId)+ 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)@@ -550,7 +550,7 @@ func (a *Api) LoadContext(planId string, req shared.LoadContextRequest) (*shared}func (a *Api) UpdateContext(planId string, req shared.UpdateContextRequest) (*shared.UpdateContextResponse, error) {- serverUrl := fmt.Sprintf("%s/plans/%s/context", apiHost, planId)+ serverUrl := fmt.Sprintf("%s/plans/%s/context", getApiHost(), planId)reqBytes, err := json.Marshal(req)if err != nil {@@ -587,7 +587,7 @@ func (a *Api) UpdateContext(planId string, req shared.UpdateContextRequest) (*sh}func (a *Api) DeleteContext(planId string, req shared.DeleteContextRequest) (*shared.DeleteContextResponse, error) {- serverUrl := fmt.Sprintf("%s/plans/%s/context", apiHost, planId)+ 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)@@ -620,7 +620,7 @@ func (a *Api) DeleteContext(planId string, req shared.DeleteContextRequest) (*sh}func (a *Api) ListContext(planId string) ([]*shared.Context, error) {- serverUrl := fmt.Sprintf("%s/plans/%s/context", apiHost, planId)+ serverUrl := fmt.Sprintf("%s/plans/%s/context", getApiHost(), planId)resp, err := authenticatedFastClient.Get(serverUrl)if err != nil {@@ -643,7 +643,7 @@ func (a *Api) ListContext(planId string) ([]*shared.Context, error) {}func (a *Api) ListConvo(planId string) ([]*shared.ConvoMessage, error) {- serverUrl := fmt.Sprintf("%s/plans/%s/convo", apiHost, planId)+ serverUrl := fmt.Sprintf("%s/plans/%s/convo", getApiHost(), planId)resp, err := authenticatedFastClient.Get(serverUrl)if err != nil {@@ -666,7 +666,7 @@ func (a *Api) ListConvo(planId string) ([]*shared.ConvoMessage, error) {}func (a *Api) ListLogs(planId string) (*shared.LogResponse, error) {- serverUrl := fmt.Sprintf("%s/plans/%s/logs", apiHost, planId)+ serverUrl := fmt.Sprintf("%s/plans/%s/logs", getApiHost(), planId)resp, err := authenticatedFastClient.Get(serverUrl)if err != nil {@@ -690,7 +690,7 @@ func (a *Api) ListLogs(planId string) (*shared.LogResponse, error) {}func (a *Api) RewindPlan(planId string, req shared.RewindPlanRequest) (*shared.RewindPlanResponse, error) {- serverUrl := fmt.Sprintf("%s/plans/%s/rewind", apiHost, planId)+ 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)diff --git a/cli/auth/auth.go b/cli/auth/auth.goindex 50d0c6de..80dc4b6f 100644--- a/cli/auth/auth.go+++ b/cli/auth/auth.go@@ -180,6 +180,72 @@ func promptAuth() error {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)+ }+ }++ 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)+ }+ } 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)+ }++ }+}++func createAccount() error {++ return nil+}+func startTrial() error {term.StartSpinner("🌟 Starting trial...")@@ -193,6 +259,7 @@ func startTrial() error {term.StopSpinner()err = StoreAccountIfNew(&types.ClientAccount{+ Email: res.Email,UserId: res.UserId,UserName: res.UserName,Token: res.Token,@@ -204,6 +271,7 @@ func startTrial() error {}Current = &types.ClientAuth{+ Email: res.Email,UserId: res.UserId,UserName: res.UserName,OrgId: res.OrgId,diff --git a/cli/cmd/sign_in.go b/cli/cmd/sign_in.goindex 1d619dd0..0ddf3d44 100644--- a/cli/cmd/sign_in.go+++ b/cli/cmd/sign_in.go@@ -1 +1,18 @@package cmd++import "github.com/spf13/cobra"++var signInCmd = &cobra.Command{+ Use: "sign-in",+ Short: "Sign in to a Plandex account",+ Args: cobra.NoArgs,+ Run: signIn,+}++func init() {+ RootCmd.AddCommand(signInCmd)+}++func signIn(cmd *cobra.Command, args []string) {++}diff --git a/cli/go.mod b/cli/go.modindex 57e977f4..8089e318 100644--- a/cli/go.mod+++ b/cli/go.mod@@ -20,6 +20,7 @@ require (github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirectgithub.com/aymerick/douceur v0.2.0 // indirectgithub.com/containerd/console v1.0.4-0.20230313162750-1ae8d489ac81 // indirect+ github.com/cqroot/multichoose v0.1.1 // indirectgithub.com/dlclark/regexp2 v1.10.0 // indirectgithub.com/google/uuid v1.4.0 // indirectgithub.com/gorilla/css v1.0.1 // indirect@@ -49,6 +50,7 @@ require (github.com/charmbracelet/bubbletea v0.24.2github.com/charmbracelet/glamour v0.6.0github.com/charmbracelet/glow v1.5.1+ github.com/cqroot/prompt v0.9.3github.com/eiannone/keyboard v0.0.0-20220611211555-0d226195f203github.com/inconshreveable/mousetrap v1.1.0 // indirectgithub.com/mattn/go-runewidth v0.0.15 // indirectdiff --git a/cli/go.sum b/cli/go.sumindex bfcd19f4..515874be 100644--- a/cli/go.sum+++ b/cli/go.sum@@ -274,6 +274,10 @@ github.com/coreos/pkg v0.0.0-20180928190104-399ea9e2e55f/go.mod h1:E3G3o1h8I7cfcgithub.com/cpuguy83/go-md2man/v2 v2.0.0/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU=github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=github.com/cpuguy83/go-md2man/v2 v2.0.3/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=+github.com/cqroot/multichoose v0.1.1 h1:diGuKYKea9ePOTwUyUDor9zKRqKFWXGkYGqUa9+firU=+github.com/cqroot/multichoose v0.1.1/go.mod h1:BJzIGqbQZNADPDuA3IzhmTMpRc2F3fZKysMRYP+Ydw8=+github.com/cqroot/prompt v0.9.3 h1:00Sjiasl1QL7ttEphJ+1xAl0fKQi+7s2F3aY0x7wnz4=+github.com/cqroot/prompt v0.9.3/go.mod h1:NZvCTeuvR9ew9Hkk7xlrZ9xdVH4AmkO9R0eeBkzOHXQ=github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=github.com/creack/pty v1.1.17 h1:QeVUsEDNrLBW4tMgZHvxy18sKtr6VI492kBhUfhDJNI=github.com/creack/pty v1.1.17/go.mod h1:MOBLtS5ELjhRRrroQr9kyvTxUAFNvYEK993ew/Vr4O4=@@ -667,8 +671,8 @@ github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/github.com/stretchr/testify v1.7.5/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=-github.com/stretchr/testify v1.8.2 h1:+h33VjcLVPDHtOdpUCuF+7gSuG3yGIftsP1YvFihtJ8=-github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=+github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=+github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=github.com/subosito/gotenv v1.4.1/go.mod h1:ayKnFf/c6rvx/2iiLrJUk1e6plDbT3edrFNGqEflhK0=github.com/tmc/grpc-websocket-proxy v0.0.0-20190109142713-0ad062ec5ee5/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U=github.com/tv42/httpunix v0.0.0-20150427012821-b75d8614f926/go.mod h1:9ESjWnEqriFuLhtthL60Sar/7RFoluCcXsuvEwTV5KM=diff --git a/cli/term/term.go b/cli/term/term.goindex 431508bf..5689a3ac 100644--- a/cli/term/term.go+++ b/cli/term/term.go@@ -9,6 +9,8 @@ import ("github.com/eiannone/keyboard""github.com/fatih/color""golang.org/x/term"++ "github.com/cqroot/prompt")var CmdDesc = map[string][2]string{@@ -109,7 +111,11 @@ func PageOutputReverse(output string) {}}-func GetUserInput() (rune, error) {+func GetUserStringInput(msg string) (string, error) {+ return prompt.New().Ask(msg).Input("")+}++func GetUserKeyInput() (rune, error) {if err := keyboard.Open(); err != nil {return 0, fmt.Errorf("failed to open keyboard: %s", err)}@@ -129,7 +135,7 @@ func ConfirmYesNo(fmtStr string, fmtArgs ...interface{}) (bool, error) {color.New(color.FgHiMagenta, color.Bold).Printf(fmtStr+" (y)es | (n)o", fmtArgs...)color.New(color.FgHiMagenta, color.Bold).Print("> ")- char, err := GetUserInput()+ char, err := GetUserKeyInput()if err != nil {return false, fmt.Errorf("failed to get user input: %s", err)}@@ -150,7 +156,7 @@ func ConfirmYesNoCancel(fmtStr string, fmtArgs ...interface{}) (bool, bool, errocolor.New(color.FgHiMagenta, color.Bold).Printf(fmtStr+" (y)es | (n)o | (c)ancel", fmtArgs...)color.New(color.FgHiMagenta, color.Bold).Print("> ")- char, err := GetUserInput()+ char, err := GetUserKeyInput()if err != nil {return false, false, fmt.Errorf("failed to get user input: %s", err)}diff --git a/cli/types/types.go b/cli/types/types.goindex 3136dddf..22ea8059 100644--- a/cli/types/types.go+++ b/cli/types/types.go@@ -3,6 +3,9 @@ package typesimport "github.com/plandex/plandex/shared"type ClientAccount struct {+ IsCloud bool `json:"isCloud"`+ Host string `json:"host"`+ Email string `json:"email"`UserName string `json:"userName"`UserId string `json:"userId"`Token string `json:"token"`@@ -10,6 +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"`diff --git a/server/db/auth_helpers.go b/server/db/auth_helpers.goindex 071ec2aa..699ad40a 100644--- a/server/db/auth_helpers.go+++ b/server/db/auth_helpers.go@@ -8,52 +8,86 @@ import ("time""github.com/google/uuid"+ "github.com/pkg/errors")const tokenExpirationDays = 90-func CreateAuthToken(userId string, tx *sql.Tx) (string, error) {+func CreateAuthToken(userId string, tx *sql.Tx) (token, id string, err error) {uid := uuid.New()bytes := uid[:]hashBytes := sha256.Sum256(bytes)hash := hex.EncodeToString(hashBytes[:])- _, err := tx.Exec("INSERT INTO auth_tokens (user_id, token_hash) VALUES ($1, $2)", userId, hash)+ err = tx.QueryRow("INSERT INTO auth_tokens (user_id, token_hash) VALUES ($1, $2) RETURNING id", userId, hash).Scan(&id)if err != nil {- return "", fmt.Errorf("error creating auth token: %v", err)+ return "", "", fmt.Errorf("error creating auth token: %v", err)}- return uid.String(), nil+ return uid.String(), id, nil}-func ValidateAuthToken(token string) (userId string, err error) {+func ValidateAuthToken(token string) (userId, tokenHash string, err error) {uid, err := uuid.Parse(token)if err != nil {- return "", fmt.Errorf("error parsing token: %v", err)+ return "", "", errors.New("invalid token")}bytes := uid[:]hashBytes := sha256.Sum256(bytes)- hash := hex.EncodeToString(hashBytes[:])+ tokenHash = hex.EncodeToString(hashBytes[:])- err = Conn.QueryRow("SELECT user_id FROM auth_tokens WHERE token_hash = $1 AND created_at > $2", hash, time.Now().AddDate(0, 0, -tokenExpirationDays)).Scan(&userId)+ 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)if err != nil {- return "", fmt.Errorf("error validating token: %v", err)+ if err == sql.ErrNoRows {+ return "", "", errors.New("invalid token")+ }++ return "", "", fmt.Errorf("error validating token: %v", err)}- return userId, nil+ return userId, tokenHash, 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)+func CreateEmailVerification(email string, userId, pinHash string) error {+ _, err := Conn.Exec("INSERT INTO email_verifications (email, pin_hash, user_id) VALUES ($1, $2, $3)", email, pinHash, userId)if err != nil {- return false, fmt.Errorf("error validating org membership: %v", err)+ return fmt.Errorf("error creating email verification: %v", err)+ }++ return nil+}++// email verifications expire in 5 minutes+const emailVerificationExpirationMinutes = 5++func ValidateEmailVerification(email, pin string) (id string, err error) {+ pinHashBytes := sha256.Sum256([]byte(pin))+ pinHash := hex.EncodeToString(pinHashBytes[:])++ var authTokenId string++ query := `SELECT id, auth_token_id+ FROM email_verifications+ WHERE pin_hash = $1+ AND email = $2+ AND created_at > $3`++ err = Conn.QueryRow(query, pinHash, email, time.Now().Add(-emailVerificationExpirationMinutes*time.Minute)).Scan(&id, &authTokenId)+ if err != nil {+ if err == sql.ErrNoRows {+ return "", errors.New("invalid pin")+ }+ return "", fmt.Errorf("error validating email verification: %v", err)+ }++ if authTokenId != "" {+ return "", errors.New("pin already verified")}- return count > 0, nil+ return id, nil}diff --git a/server/db/convo_helpers.go b/server/db/convo_helpers.goindex 885282a7..661cfe56 100644--- a/server/db/convo_helpers.go+++ b/server/db/convo_helpers.go@@ -83,7 +83,7 @@ func StoreConvoMessage(message *ConvoMessage, commit bool) (string, error) {return "", fmt.Errorf("error writing convo message: %v", err)}- err = AddPlanConvoTokens(message.PlanId, message.Tokens)+ err = AddPlanConvoMessage(message.PlanId, message.Tokens)if err != nil {return "", fmt.Errorf("error adding convo tokens: %v", err)diff --git a/server/db/db.go b/server/db/db.goindex cfec0ad4..816efb1d 100644--- a/server/db/db.go+++ b/server/db/db.go@@ -63,7 +63,7 @@ func MigrationsUp() error {// return fmt.Errorf("error running down migrations: %v", err)// }// }- // log.Println("database reset")+ // log.Println("ran down migrations - database was reset")// }err = m.Up()diff --git a/server/db/models.go b/server/db/models.goindex 9cecf918..efed01f3 100644--- a/server/db/models.go+++ b/server/db/models.go@@ -29,18 +29,22 @@ func (org *Org) ToApi() *shared.Org {}type User struct {- Id string `db:"id"`- Name string `db:"name"`- Email string `db:"email"`- CreatedAt time.Time `db:"created_at"`- UpdatedAt time.Time `db:"updated_at"`+ Id string `db:"id"`+ Name string `db:"name"`+ Email string `db:"email"`+ NumNonDraftPlans int `db:"num_non_draft_plans"`+ IsTrial bool `db:"is_trial"`+ CreatedAt time.Time `db:"created_at"`+ UpdatedAt time.Time `db:"updated_at"`}func (user *User) ToApi() *shared.User {return &shared.User{- Id: user.Id,- Name: user.Name,- Email: user.Email,+ Id: user.Id,+ Name: user.Name,+ Email: user.Email,+ NumNonDraftPlans: user.NumNonDraftPlans,+ IsTrial: user.IsTrial,}}@@ -90,6 +94,7 @@ type Plan struct {ContextTokens int `db:"context_tokens"`ConvoTokens int `db:"convo_tokens"`SharedWithOrgAt *time.Time `db:"shared_with_org_at,omitempty"`+ TotalMessages int `db:"total_messages"`ArchivedAt *time.Time `db:"archived_at,omitempty"`CreatedAt time.Time `db:"created_at"`UpdatedAt time.Time `db:"updated_at"`@@ -104,6 +109,7 @@ func (plan *Plan) ToApi() *shared.Plan {ContextTokens: plan.ContextTokens,ConvoTokens: plan.ConvoTokens,SharedWithOrgAt: plan.SharedWithOrgAt,+ TotalMessages: plan.TotalMessages,ArchivedAt: plan.ArchivedAt,CreatedAt: plan.CreatedAt,UpdatedAt: plan.UpdatedAt,diff --git a/server/db/plan_helpers.go b/server/db/plan_helpers.goindex 257ce659..c26b1b13 100644--- a/server/db/plan_helpers.go+++ b/server/db/plan_helpers.go@@ -52,7 +52,7 @@ func CreatePlan(orgId, projectId, userId, name string) (*Plan, error) {return plan, nil}-func ListPlans(projectId, userId string, archived bool, status string) ([]shared.Plan, error) {+func ListOwnedPlans(projectId, userId string, archived bool, status string) ([]shared.Plan, error) {qs := "SELECT id, owner_id, name, status, context_tokens, convo_tokens, shared_with_org_at, archived_at, created_at, updated_at FROM plans WHERE project_id = $1 AND owner_id = $2"qargs := []interface{}{projectId, userId}@@ -98,8 +98,8 @@ func AddPlanContextTokens(planId string, addTokens int) error {return nil}-func AddPlanConvoTokens(planId string, addTokens int) error {- _, err := Conn.Exec("UPDATE plans SET convo_tokens = convo_tokens + $1 WHERE id = $2", addTokens, planId)+func AddPlanConvoMessage(planId string, addTokens int) error {+ _, err := Conn.Exec("UPDATE plans SET convo_tokens = convo_tokens + $1, total_messages = total_messages + 1 WHERE id = $2", addTokens, planId)if err != nil {return fmt.Errorf("error updating plan tokens: %v", err)}@@ -152,7 +152,7 @@ func SyncPlanTokens(orgId, planId string) error {func GetPlan(planId string) (*Plan, error) {var plan Plan- err := Conn.Get(&plan, "SELECT id, org_id, owner_id, project_id, name, status, error, context_tokens, convo_tokens, shared_with_org_at, archived_at, created_at, updated_at FROM plans WHERE id = $1", planId)+ err := Conn.Get(&plan, "SELECT id, org_id, owner_id, project_id, name, status, error, context_tokens, convo_tokens, shared_with_org_at, total_messages, archived_at, created_at, updated_at FROM plans WHERE id = $1", planId)if err != nil {return nil, fmt.Errorf("error getting plan: %v", err)@@ -181,6 +181,16 @@ func RenamePlan(planId string, name string) error {return nil}+func IncNumNonDraftPlans(userId string) error {+ _, err := Conn.Exec("UPDATE users SET num_non_draft_plans = num_non_draft_plans + 1 WHERE id = $1", userId)++ if err != nil {+ return fmt.Errorf("error updating user num_non_draft_plans: %v", err)+ }++ return nil+}+func StoreDescription(description *ConvoMessageDescription) error {descriptionsDir := getPlanDescriptionsDir(description.OrgId, description.PlanId)diff --git a/server/db/user_helpers.go b/server/db/user_helpers.gonew file mode 100644index 00000000..6bb7187c--- /dev/null+++ b/server/db/user_helpers.go@@ -0,0 +1,109 @@+package db++import (+ "database/sql"+ "fmt"+ "log"++ "github.com/plandex/plandex/shared"+)++func GetUser(userId string) (*User, error) {+ var user User+ err := Conn.Get(&user, "SELECT * FROM users WHERE id = $1", userId)++ if err != nil {+ return nil, fmt.Errorf("error getting user: %v", err)+ }++ return &user, nil+}++func GetUserByEmail(email string) (*User, error) {+ var user User+ err := Conn.Get(&user, "SELECT * FROM users WHERE email = $1", email)++ if err != nil {+ if err == sql.ErrNoRows {+ return nil, nil+ }++ return nil, fmt.Errorf("error getting user: %v", err)+ }++ 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)++ 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 != nil {+ return false, fmt.Errorf("error validating org membership: %v", err)+ }++ return count > 0, nil+}++func CreateOrg(req *shared.CreateOrgRequest, userId string) (*Org, error) {+ org := &Org{+ Name: req.Name,+ Domain: req.Domain,+ AutoAddDomainUsers: req.AutoAddDomainUsers,+ OwnerId: userId,+ }++ // start a transaction+ tx, err := Conn.Begin()+ if err != nil {+ return nil, 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.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 org, nil+}diff --git a/server/db/utils.go b/server/db/utils.gonew file mode 100644index 00000000..39d8e543--- /dev/null+++ b/server/db/utils.go@@ -0,0 +1,12 @@+package db++import "github.com/lib/pq"++func IsNonUniqueErr(err error) bool {+ if err, ok := err.(*pq.Error); ok {+ if err.Code == "23505" {+ return true+ }+ }+ return false+}diff --git a/server/email/email.go b/server/email/email.gonew file mode 100644index 00000000..02e4227e--- /dev/null+++ b/server/email/email.go@@ -0,0 +1,34 @@+package email++import (+ "fmt"+ "os"++ "github.com/atotto/clipboard"+ "github.com/gen2brain/beeep"+)++func SendVerificationEmail(email string, pin string) error {+ // Check if the environment is production+ if os.Getenv("GOENV") == "production" {+ // TODO: send email in production+ return nil+ }++ if os.Getenv("GOENV") == "development" {+ // Development environment+ // Copy pin to clipboard+ if err := clipboard.WriteAll(pin); err != nil {+ return fmt.Errorf("error copying pin to clipboard in dev: %v", err)+ }++ // Send notification+ err := beeep.Notify("Verification Pin", fmt.Sprintf("Verification pin %s copied to clipboard %s", pin, email), "")+ if err != nil {+ return fmt.Errorf("error sending notification in dev: %v", err)+ }++ }++ return nil+}diff --git a/server/go.mod b/server/go.modindex f052e33f..6a29c27d 100644--- a/server/go.mod+++ b/server/go.mod@@ -6,25 +6,32 @@ require (github.com/davecgh/go-spew v1.1.1github.com/google/uuid v1.4.0github.com/gorilla/mux v1.8.1+ github.com/pkg/errors v0.9.1github.com/plandex/plandex/shared v0.0.0-00010101000000-000000000000github.com/sashabaranov/go-openai v1.17.5)require (github.com/dlclark/regexp2 v1.10.0 // indirect+ github.com/go-toast/toast v0.0.0-20190211030409-01e6764cf0a4 // indirect+ github.com/godbus/dbus/v5 v5.1.0 // indirectgithub.com/hashicorp/errwrap v1.1.0 // indirectgithub.com/hashicorp/go-multierror v1.1.1 // indirectgithub.com/mattn/go-colorable v0.1.13 // indirectgithub.com/mattn/go-isatty v0.0.20 // indirectgithub.com/mattn/go-runewidth v0.0.9 // indirect+ github.com/nu7hatch/gouuid v0.0.0-20131221200532-179d4d0c4d8d // indirectgithub.com/olekukonko/tablewriter v0.0.5 // indirectgithub.com/pkoukk/tiktoken-go v0.1.6 // indirect+ github.com/tadvi/systray v0.0.0-20190226123456-11a2b8fa57af // indirectgo.uber.org/atomic v1.7.0 // indirectgolang.org/x/sys v0.14.0 // indirect)require (+ github.com/atotto/clipboard v0.1.4github.com/fatih/color v1.16.0+ github.com/gen2brain/beeep v0.0.0-20230907135156-1a38885a97fcgithub.com/golang-migrate/migrate/v4 v4.16.2github.com/jmoiron/sqlx v1.3.5github.com/lib/pq v1.10.9diff --git a/server/go.sum b/server/go.sumindex 4cc6876f..62fc0f88 100644--- a/server/go.sum+++ b/server/go.sum@@ -2,6 +2,8 @@ github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161 h1:L/gRVlceqvL25github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E=github.com/Microsoft/go-winio v0.6.1 h1:9/kr64B9VUZrLm5YYwbGtUJnMgqWVOdUAXu6Migciow=github.com/Microsoft/go-winio v0.6.1/go.mod h1:LRdKpFKfdobln8UmuiYcKPot9D2v6svN5+sAH+4kjUM=+github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z4=+github.com/atotto/clipboard v0.1.4/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn0Yu86PYI=github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=@@ -19,8 +21,14 @@ github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4github.com/docker/go-units v0.5.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk=github.com/fatih/color v1.16.0 h1:zmkK9Ngbjj+K0yRhTVONQh1p/HknKYSlNT+vZCzyokM=github.com/fatih/color v1.16.0/go.mod h1:fL2Sau1YI5c0pdGEVCbKQbLXB6edEj1ZgiY4NijnWvE=+github.com/gen2brain/beeep v0.0.0-20230907135156-1a38885a97fc h1:NNgdMgPX3j33uEAoVVxNxillDPnxT0xbGv8uh4CKIAo=+github.com/gen2brain/beeep v0.0.0-20230907135156-1a38885a97fc/go.mod h1:0W7dI87PvXJ1Sjs0QPvWXKcQmNERY77e8l7GFhZB/s4=github.com/go-sql-driver/mysql v1.6.0 h1:BCTh4TKNUYmOmMUcQ3IipzF5prigylS7XXjEkfCHuOE=github.com/go-sql-driver/mysql v1.6.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg=+github.com/go-toast/toast v0.0.0-20190211030409-01e6764cf0a4 h1:qZNfIGkIANxGv/OqtnntR4DfOY2+BgwR60cAcu/i3SE=+github.com/go-toast/toast v0.0.0-20190211030409-01e6764cf0a4/go.mod h1:kW3HQ4UdaAyrUCSSDR4xUzBKW6O2iA4uHhk7AtyYp10=+github.com/godbus/dbus/v5 v5.1.0 h1:4KLkAxT3aOY8Li4FRJe/KvhoNFFxo0m6fNuFUO8QJUk=+github.com/godbus/dbus/v5 v5.1.0/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q=github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q=github.com/golang-migrate/migrate/v4 v4.16.2 h1:8coYbMKUyInrFk1lfGfRovTLAW7PhWp8qQDT2iKfuoA=@@ -55,6 +63,8 @@ github.com/moby/term v0.5.0 h1:xt8Q1nalod/v7BqbG21f8mQPqH+xAaC9C3N3wfWbVP0=github.com/moby/term v0.5.0/go.mod h1:8FzsFHVUBGZdbDsJw/ot+X+d5HLUbvklYLJ9uGfcI3Y=github.com/morikuni/aec v1.0.0 h1:nP9CBfwrvYnBRgY6qfDQkygYDmYwOilePFkwzv4dU8A=github.com/morikuni/aec v1.0.0/go.mod h1:BbKIizmSmc5MMPqRYbxO4ZU0S0+P200+tUnFx7PXmsc=+github.com/nu7hatch/gouuid v0.0.0-20131221200532-179d4d0c4d8d h1:VhgPp6v9qf9Agr/56bj7Y/xa04UccTW04VP0Qed4vnQ=+github.com/nu7hatch/gouuid v0.0.0-20131221200532-179d4d0c4d8d/go.mod h1:YUTz3bUH2ZwIWBy3CJBeOBEugqcmXREj14T+iG/4k4U=github.com/olekukonko/tablewriter v0.0.5 h1:P2Ga83D34wi1o9J6Wh1mRuqd4mF/x/lgBS7N7AbDhec=github.com/olekukonko/tablewriter v0.0.5/go.mod h1:hPp6KlRPjbx+hW8ykQs1w3UBbZlj6HuIJcUGPhkA7kY=github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U=@@ -75,6 +85,8 @@ github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=github.com/stretchr/testify v1.8.2 h1:+h33VjcLVPDHtOdpUCuF+7gSuG3yGIftsP1YvFihtJ8=github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=+github.com/tadvi/systray v0.0.0-20190226123456-11a2b8fa57af h1:6yITBqGTE2lEeTPG04SN9W+iWHCRyHqlVYILiSXziwk=+github.com/tadvi/systray v0.0.0-20190226123456-11a2b8fa57af/go.mod h1:4F09kP5F+am0jAwlQLddpoMDM+iewkxxt6nxUQ5nq5o=go.uber.org/atomic v1.7.0 h1:ADUqmZGgLDDfbSL9ZmPxKTybcoEYHgpYfELNoN+7hsw=go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc=golang.org/x/mod v0.10.0 h1:lFO9qtOdlre5W1jxS3r/4szv2/6iXxScdzjoBMXNhYk=@@ -83,8 +95,6 @@ golang.org/x/net v0.10.0 h1:X2//UzNDwYmtCLn7To6G58Wr6f5ahEAQgKNzv9Y951M=golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=-golang.org/x/sys v0.8.0 h1:EBmGv8NaZBZTWvrbjNoL6HVt+IVy3QDQpJs7VRIw3tU=-golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=golang.org/x/sys v0.14.0 h1:Vz7Qs629MkJkGyHxUlRHizWJRG2j8fbQKjELVSNhy7Q=golang.org/x/sys v0.14.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=golang.org/x/tools v0.9.1 h1:8WMNJAz3zrtPmnYC7ISf5dEn3MT0gY7jBJfw27yrrLo=diff --git a/server/handlers/accounts.go b/server/handlers/accounts.goindex f9af5ab1..22457e57 100644--- a/server/handlers/accounts.go+++ b/server/handlers/accounts.go@@ -1,12 +1,16 @@package handlersimport (- "crypto/rand"+ "crypto/sha256"+ "encoding/hex""encoding/json""fmt"+ "io""log""net/http""plandex-server/db"+ "plandex-server/email"+ "strings""github.com/plandex/plandex/shared")@@ -33,8 +37,8 @@ func StartTrialHandler(w http.ResponseWriter, r *http.Request) {}}()- b := make([]byte, 3)- if _, err := rand.Read(b); err != nil {+ b, err := shared.GetRandomAlphanumeric(6)+ if err != nil {log.Printf("Error generating random tag: %v\n", err)http.Error(w, "Error generating random tag: "+err.Error(), http.StatusInternalServerError)return@@ -45,8 +49,7 @@ func StartTrialHandler(w http.ResponseWriter, r *http.Request) {email := tag + "@trial.plandex.ai"var userId string- userRow, err := tx.Query("INSERT INTO users (name, email, is_trial) VALUES ($1, $2, true) RETURNING id", name, email)- closedUserRow := false+ err = tx.QueryRow("INSERT INTO users (name, email, is_trial) VALUES ($1, $2, true) RETURNING id", name, email).Scan(&userId)if err != nil {log.Printf("Error creating user: %v\n", err)@@ -54,72 +57,320 @@ func StartTrialHandler(w http.ResponseWriter, r *http.Request) {return}- defer func() {- if !closedUserRow {- userRow.Close()- }- }()+ // create a new org+ var orgId string+ orgName := "Trial Org " + tag+ err = tx.QueryRow("INSERT INTO orgs (name, owner_id, is_trial) VALUES ($1, $2, true) RETURNING id", orgName, userId).Scan(&orgId)- if userRow.Next() {- if err := userRow.Scan(&userId); err != nil {- log.Printf("Error scanning user: %v\n", err)- http.Error(w, "Error scanning user: "+err.Error(), http.StatusInternalServerError)- return- }+ if err != nil {+ log.Printf("Error creating org: %v\n", err)+ http.Error(w, "Error creating org: "+err.Error(), http.StatusInternalServerError)+ return}- err = userRow.Close()+ // insert org user+ _, err = tx.Exec("INSERT INTO orgs_users (org_id, user_id) VALUES ($1, $2)", orgId, userId)if err != nil {- log.Printf("Error closing user row: %v\n", err)- http.Error(w, "Error closing user row: "+err.Error(), http.StatusInternalServerError)+ log.Printf("Error inserting org user: %v\n", err)+ http.Error(w, "Error inserting org user: "+err.Error(), http.StatusInternalServerError)return}- closedUserRow = true- // create a new org- orgName := "Trial Org " + tag- orgRow, err := tx.Query("INSERT INTO orgs (name, owner_id, is_trial) VALUES ($1, $2, true) RETURNING id", orgName, userId)- closedOrgRow := false+ // create auth token+ token, _, err := db.CreateAuthToken(userId, tx)if err != nil {- log.Printf("Error creating org: %v\n", err)- http.Error(w, "Error creating org: "+err.Error(), http.StatusInternalServerError)+ log.Printf("Error creating auth token: %v\n", err)+ http.Error(w, "Error creating auth token: "+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+ }++ resp := shared.StartTrialResponse{+ UserId: userId,+ OrgId: orgId,+ Token: token,+ UserName: name,+ OrgName: orgName,+ Email: email,+ }++ 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 started trial")++ 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")++ // 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 failuredefer func() {- if !closedOrgRow {- orgRow.Close()+ if err != nil {+ if rbErr := tx.Rollback(); rbErr != nil {+ log.Printf("transaction rollback error: %v\n", rbErr)+ } else {+ log.Println("transaction rolled back")+ }}}()- var orgId string- if orgRow.Next() {- if err := orgRow.Scan(&orgId); err != nil {- log.Printf("Error scanning org: %v\n", err)- http.Error(w, "Error scanning org: "+err.Error(), http.StatusInternalServerError)- return- }+ // 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}- err = orgRow.Close()+ // 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 closing org row: %v\n", err)- http.Error(w, "Error closing org row: "+err.Error(), http.StatusInternalServerError)+ log.Printf("Error updating email verification: %v\n", err)+ http.Error(w, "Error updating email verification: "+err.Error(), http.StatusInternalServerError)return}- closedOrgRow = true- // insert org user- _, err = tx.Exec("INSERT INTO orgs_users (org_id, user_id) VALUES ($1, $2)", orgId, userId)+ // commit transaction+ err = tx.Commit()if err != nil {- log.Printf("Error inserting org user: %v\n", err)- http.Error(w, "Error inserting org user: "+err.Error(), http.StatusInternalServerError)+ log.Printf("Error committing transaction: %v\n", err)+ http.Error(w, "Error committing transaction: "+err.Error(), http.StatusInternalServerError)+ return+ }++ // get orgs+ orgs, err := db.GetOrgsForUser(user.Id)++ 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.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)+ return+ }++ var req shared.CreateAccountRequest+ 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+ }++ // 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 user+ var userId string+ err = tx.QueryRow("INSERT INTO users (name, email) VALUES ($1, $2) RETURNING id", req.UserName, req.Email).Scan(&userId)++ 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}// create auth token- token, err := db.CreateAuthToken(userId, tx)+ token, authTokenId, err := db.CreateAuthToken(userId, tx)if err != nil {log.Printf("Error creating auth token: %v\n", err)@@ -127,6 +378,15 @@ func StartTrialHandler(w http.ResponseWriter, r *http.Request) {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)++ 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 transactionerr = tx.Commit()if err != nil {@@ -135,12 +395,11 @@ func StartTrialHandler(w http.ResponseWriter, r *http.Request) {return}- resp := shared.StartTrialResponse{+ resp := shared.SessionResponse{UserId: userId,- OrgId: orgId,Token: token,- UserName: name,- OrgName: orgName,+ Email: req.Email,+ UserName: req.UserName,}bytes, err := json.Marshal(resp)@@ -151,7 +410,77 @@ func StartTrialHandler(w http.ResponseWriter, r *http.Request) {return}- log.Println("Successfully started trial")+ 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+ }++ 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)+ 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)+ 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/auth_helpers.go b/server/handlers/auth_helpers.goindex ac18e854..eb549771 100644--- a/server/handlers/auth_helpers.go+++ b/server/handlers/auth_helpers.go@@ -12,7 +12,7 @@ import ("github.com/plandex/plandex/shared")-func authenticate(w http.ResponseWriter, r *http.Request) *types.ServerAuth {+func authenticate(w http.ResponseWriter, r *http.Request, requireOrg bool) *types.ServerAuth {log.Println("authenticating request")authHeader := r.Header.Get("Authorization")@@ -52,7 +52,7 @@ func authenticate(w http.ResponseWriter, r *http.Request) *types.ServerAuth {}// validate the token- userId, err := db.ValidateAuthToken(parsed.Token)+ userId, tokenHash, err := db.ValidateAuthToken(parsed.Token)if err != nil {log.Printf("error validating auth token: %v\n", err)@@ -60,6 +60,19 @@ func authenticate(w http.ResponseWriter, r *http.Request) *types.ServerAuth {return nil}+ if !requireOrg {+ return &types.ServerAuth{+ UserId: userId,+ TokenHash: tokenHash,+ }+ }++ if parsed.OrgId == "" {+ log.Println("no org id")+ http.Error(w, "no org id", http.StatusUnauthorized)+ return nil+ }+// validate the org membershipisMember, err := db.ValidateOrgMembership(userId, parsed.OrgId)@@ -76,8 +89,9 @@ func authenticate(w http.ResponseWriter, r *http.Request) *types.ServerAuth {}return &types.ServerAuth{- UserId: userId,- OrgId: parsed.OrgId,+ UserId: userId,+ OrgId: parsed.OrgId,+ TokenHash: tokenHash,}}diff --git a/server/handlers/plans_changes.go b/server/handlers/plans_changes.goindex 4fcfaa0d..3e49100a 100644--- a/server/handlers/plans_changes.go+++ b/server/handlers/plans_changes.go@@ -13,7 +13,7 @@ import (func CurrentPlanHandler(w http.ResponseWriter, r *http.Request) {log.Println("Received request for ListPlanChangesHandler")- auth := authenticate(w, r)+ auth := authenticate(w, r, true)if auth == nil {return}@@ -63,7 +63,7 @@ func CurrentPlanHandler(w http.ResponseWriter, r *http.Request) {func ApplyPlanHandler(w http.ResponseWriter, r *http.Request) {log.Println("Received request for ApplyPlanHandler")- auth := authenticate(w, r)+ auth := authenticate(w, r, true)if auth == nil {return}@@ -90,7 +90,7 @@ func ApplyPlanHandler(w http.ResponseWriter, r *http.Request) {func RejectAllChangesHandler(w http.ResponseWriter, r *http.Request) {log.Println("Received request for RejectAllChangesHandler")- auth := authenticate(w, r)+ auth := authenticate(w, r, true)if auth == nil {return}@@ -117,7 +117,7 @@ func RejectAllChangesHandler(w http.ResponseWriter, r *http.Request) {func RejectResultHandler(w http.ResponseWriter, r *http.Request) {log.Println("Received request for RejectResultHandler")- auth := authenticate(w, r)+ auth := authenticate(w, r, true)if auth == nil {return}@@ -146,7 +146,7 @@ func RejectResultHandler(w http.ResponseWriter, r *http.Request) {func RejectReplacementHandler(w http.ResponseWriter, r *http.Request) {log.Println("Received request for RejectReplacementHandler")- auth := authenticate(w, r)+ auth := authenticate(w, r, true)if auth == nil {return}@@ -174,7 +174,7 @@ func RejectReplacementHandler(w http.ResponseWriter, r *http.Request) {}func ArchivePlanHandler(w http.ResponseWriter, r *http.Request) {- auth := authenticate(w, r)+ auth := authenticate(w, r, true)if auth == nil {return}diff --git a/server/handlers/plans_context.go b/server/handlers/plans_context.goindex 1b95cf1d..225db09e 100644--- a/server/handlers/plans_context.go+++ b/server/handlers/plans_context.go@@ -20,7 +20,7 @@ import (func ListContextHandler(w http.ResponseWriter, r *http.Request) {log.Println("Received request for ListContextHandler")- auth := authenticate(w, r)+ auth := authenticate(w, r, true)if auth == nil {return}@@ -61,7 +61,7 @@ func ListContextHandler(w http.ResponseWriter, r *http.Request) {func LoadContextHandler(w http.ResponseWriter, r *http.Request) {log.Println("Received request for LoadContextHandler")- auth := authenticate(w, r)+ auth := authenticate(w, r, true)if auth == nil {return}@@ -229,7 +229,7 @@ func LoadContextHandler(w http.ResponseWriter, r *http.Request) {func UpdateContextHandler(w http.ResponseWriter, r *http.Request) {log.Println("Received request for UpdateContextHandler")- auth := authenticate(w, r)+ auth := authenticate(w, r, true)if auth == nil {return}@@ -426,7 +426,7 @@ func UpdateContextHandler(w http.ResponseWriter, r *http.Request) {func DeleteContextHandler(w http.ResponseWriter, r *http.Request) {log.Println("Received request for DeleteContextHandler")- auth := authenticate(w, r)+ auth := authenticate(w, r, true)if auth == nil {return}diff --git a/server/handlers/plans_convo.go b/server/handlers/plans_convo.goindex 18e90ff2..919476e4 100644--- a/server/handlers/plans_convo.go+++ b/server/handlers/plans_convo.go@@ -9,7 +9,7 @@ import (func ListConvoHandler(w http.ResponseWriter, r *http.Request) {log.Println("Received a request for ListConvoHandler")- auth := authenticate(w, r)+ auth := authenticate(w, r, true)if auth == nil {return}diff --git a/server/handlers/plans_crud.go b/server/handlers/plans_crud.goindex 874ef3fd..89786911 100644--- a/server/handlers/plans_crud.go+++ b/server/handlers/plans_crud.go@@ -6,6 +6,7 @@ import ("io""log""net/http"+ "os""plandex-server/db""github.com/gorilla/mux"@@ -15,7 +16,7 @@ import (func CreatePlanHandler(w http.ResponseWriter, r *http.Request) {log.Println("Received request for CreatePlanHandler")- auth := authenticate(w, r)+ auth := authenticate(w, r, true)if auth == nil {return}@@ -29,6 +30,24 @@ func CreatePlanHandler(w http.ResponseWriter, r *http.Request) {return}+ if os.Getenv("IS_CLOUD") != "" {+ 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+ }++ 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)+ return+ }+ }+ }+// read the request bodybody, err := io.ReadAll(r.Body)if err != nil {@@ -110,7 +129,7 @@ func CreatePlanHandler(w http.ResponseWriter, r *http.Request) {func GetPlanHandler(w http.ResponseWriter, r *http.Request) {log.Println("Received request for GetPlanHandler")- auth := authenticate(w, r)+ auth := authenticate(w, r, true)if auth == nil {return}@@ -140,7 +159,7 @@ func GetPlanHandler(w http.ResponseWriter, r *http.Request) {func DeletePlanHandler(w http.ResponseWriter, r *http.Request) {log.Println("Received request for DeletePlanHandler")- auth := authenticate(w, r)+ auth := authenticate(w, r, true)if auth == nil {return}@@ -197,7 +216,7 @@ func DeletePlanHandler(w http.ResponseWriter, r *http.Request) {func DeleteAllPlansHandler(w http.ResponseWriter, r *http.Request) {log.Println("Received request for DeleteAllPlansHandler")- auth := authenticate(w, r)+ auth := authenticate(w, r, true)if auth == nil {return}@@ -224,7 +243,7 @@ func DeleteAllPlansHandler(w http.ResponseWriter, r *http.Request) {func ListPlansHandler(w http.ResponseWriter, r *http.Request) {log.Println("Received request for ListPlansHandler")- auth := authenticate(w, r)+ auth := authenticate(w, r, true)if auth == nil {return}@@ -238,7 +257,7 @@ func ListPlansHandler(w http.ResponseWriter, r *http.Request) {return}- plans, err := db.ListPlans(projectId, auth.UserId, false, "")+ plans, err := db.ListOwnedPlans(projectId, auth.UserId, false, "")if err != nil {log.Printf("Error listing plans: %v\n", err)@@ -260,7 +279,7 @@ func ListPlansHandler(w http.ResponseWriter, r *http.Request) {func ListArchivedPlansHandler(w http.ResponseWriter, r *http.Request) {log.Println("Received request for ListArchivedPlansHandler")- auth := authenticate(w, r)+ auth := authenticate(w, r, true)if auth == nil {return}@@ -274,7 +293,7 @@ func ListArchivedPlansHandler(w http.ResponseWriter, r *http.Request) {return}- plans, err := db.ListPlans(projectId, "", true, "")+ plans, err := db.ListOwnedPlans(projectId, "", true, "")if err != nil {log.Printf("Error listing plans: %v\n", err)@@ -296,7 +315,7 @@ func ListArchivedPlansHandler(w http.ResponseWriter, r *http.Request) {func ListPlansRunningHandler(w http.ResponseWriter, r *http.Request) {log.Println("Received request for ListPlansRunningHandler")- auth := authenticate(w, r)+ auth := authenticate(w, r, true)if auth == nil {return}diff --git a/server/handlers/plans_exec.go b/server/handlers/plans_exec.goindex 03bf9cd0..b6ed845c 100644--- a/server/handlers/plans_exec.go+++ b/server/handlers/plans_exec.go@@ -5,7 +5,9 @@ import ("io""log""net/http"- "plandex-server/model/plan"+ "os"+ "plandex-server/db"+ model "plandex-server/model/plan""github.com/gorilla/mux""github.com/plandex/plandex/shared"@@ -14,7 +16,7 @@ import (func TellPlanHandler(w http.ResponseWriter, r *http.Request) {log.Println("Received request for TellPlanHandler")- auth := authenticate(w, r)+ auth := authenticate(w, r, true)if auth == nil {return}@@ -24,7 +26,9 @@ func TellPlanHandler(w http.ResponseWriter, r *http.Request) {log.Println("planId: ", planId)- if authorizePlan(w, planId, auth.UserId, auth.OrgId) == nil {+ plan := authorizePlan(w, planId, auth.UserId, auth.OrgId)++ if plan == nil {return}@@ -46,7 +50,25 @@ func TellPlanHandler(w http.ResponseWriter, r *http.Request) {return}- err = plan.Tell(planId, auth.UserId, auth.OrgId, &requestBody)+ if os.Getenv("IS_CLOUD") != "" {+ 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+ }++ 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)+ return+ }+ }+ }++ err = model.Tell(plan, auth.UserId, auth.OrgId, &requestBody)if err != nil {log.Printf("Error telling plan: %v\n", err)@@ -55,11 +77,11 @@ func TellPlanHandler(w http.ResponseWriter, r *http.Request) {}if requestBody.ConnectStream {- active := plan.Active.Get(planId)- subscriptionId, ch := plan.SubscribePlan(planId)+ active := model.Active.Get(planId)+ subscriptionId, ch := model.SubscribePlan(planId)startResponseStream(w, ch, active.Ctx, func() {- plan.UnsubscribePlan(planId, subscriptionId)+ model.UnsubscribePlan(planId, subscriptionId)})}@@ -67,7 +89,7 @@ func TellPlanHandler(w http.ResponseWriter, r *http.Request) {func BuildPlanHandler(w http.ResponseWriter, r *http.Request) {log.Println("Received request for BuildPlanHandler")- auth := authenticate(w, r)+ auth := authenticate(w, r, true)if auth == nil {return}@@ -85,7 +107,7 @@ func BuildPlanHandler(w http.ResponseWriter, r *http.Request) {func ConnectPlanHandler(w http.ResponseWriter, r *http.Request) {log.Println("Received request for ConnectPlanHandler")- auth := authenticate(w, r)+ auth := authenticate(w, r, true)if auth == nil {return}@@ -103,7 +125,7 @@ func ConnectPlanHandler(w http.ResponseWriter, r *http.Request) {func StopPlanHandler(w http.ResponseWriter, r *http.Request) {log.Println("Received request for StopPlanHandler")- auth := authenticate(w, r)+ auth := authenticate(w, r, true)if auth == nil {return}diff --git a/server/handlers/plans_versions.go b/server/handlers/plans_versions.goindex c87ea1e3..593a03a8 100644--- a/server/handlers/plans_versions.go+++ b/server/handlers/plans_versions.go@@ -14,7 +14,7 @@ import (func ListLogsHandler(w http.ResponseWriter, r *http.Request) {log.Println("Received request for ListLogsHandler")- auth := authenticate(w, r)+ auth := authenticate(w, r, true)if auth == nil {return}@@ -57,7 +57,7 @@ func ListLogsHandler(w http.ResponseWriter, r *http.Request) {func RewindPlanHandler(w http.ResponseWriter, r *http.Request) {log.Println("Received request for RewindPlanHandler")- auth := authenticate(w, r)+ auth := authenticate(w, r, true)if auth == nil {return}diff --git a/server/handlers/projects.go b/server/handlers/projects.goindex a2ba13e5..cdf02551 100644--- a/server/handlers/projects.go+++ b/server/handlers/projects.go@@ -7,7 +7,6 @@ import ("net/http""plandex-server/db"- "github.com/google/uuid""github.com/gorilla/mux""github.com/plandex/plandex/shared")@@ -15,7 +14,7 @@ import (func CreateProjectHandler(w http.ResponseWriter, r *http.Request) {log.Println("Received request for CreateProjectHandler")- auth := authenticate(w, r)+ auth := authenticate(w, r, true)if auth == nil {return}@@ -42,9 +41,27 @@ func CreateProjectHandler(w http.ResponseWriter, r *http.Request) {return}- id := uuid.New().String()+ // 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.Conn.Exec("INSERT INTO projects (id, org_id, name) VALUES ($1, $2, $3)", id, auth.OrgId, requestBody.Name)+ var projectId string+ err = tx.QueryRow("INSERT INTO projects (org_id, name) VALUES ($1, $2) RETURNING id", auth.OrgId, requestBody.Name).Scan(&projectId)if err != nil {log.Printf("Error creating project: %v\n", err)@@ -52,8 +69,23 @@ 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)++ if err != nil {+ log.Printf("Error adding owner to project: %v\n", err)+ http.Error(w, "Error adding owner to project: "+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.CreateProjectResponse{- Id: id,+ Id: projectId,}bytes, err := json.Marshal(resp)@@ -66,14 +98,13 @@ func CreateProjectHandler(w http.ResponseWriter, r *http.Request) {w.Write(bytes)- log.Println("Successfully created project", id)-+ log.Println("Successfully created project", projectId)}func ListProjectsHandler(w http.ResponseWriter, r *http.Request) {log.Println("Received request for ListProjectsHandler")- auth := authenticate(w, r)+ auth := authenticate(w, r, true)if auth == nil {return}@@ -111,7 +142,7 @@ func ListProjectsHandler(w http.ResponseWriter, r *http.Request) {func ProjectSetPlanHandler(w http.ResponseWriter, r *http.Request) {log.Println("Received request for UpdateProjectSetPlanHandler")- auth := authenticate(w, r)+ auth := authenticate(w, r, true)if auth == nil {return}@@ -160,7 +191,7 @@ func ProjectSetPlanHandler(w http.ResponseWriter, r *http.Request) {func RenameProjectHandler(w http.ResponseWriter, r *http.Request) {log.Println("Received request for RenameProjectHandler")- auth := authenticate(w, r)+ auth := authenticate(w, r, true)if auth == nil {return}diff --git a/server/migrations/2023120500_init.down.sql b/server/migrations/2023120500_init.down.sqlindex 1e55a0ab..a89d3a65 100644--- a/server/migrations/2023120500_init.down.sql+++ b/server/migrations/2023120500_init.down.sql@@ -6,6 +6,7 @@ DROP TABLE IF EXISTS plans;DROP TABLE IF EXISTS projects;DROP TABLE IF EXISTS orgs_users;+DROP TABLE IF EXISTS email_verifications;DROP TABLE IF EXISTS auth_tokens;DROP TABLE IF EXISTS orgs;diff --git a/server/migrations/2023120500_init.up.sql b/server/migrations/2023120500_init.up.sqlindex 055cc1df..c0eb667b 100644--- a/server/migrations/2023120500_init.up.sql+++ b/server/migrations/2023120500_init.up.sql@@ -13,11 +13,14 @@ CREATE TABLE IF NOT EXISTS users (name VARCHAR(255) NOT NULL,email 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(),updated_at TIMESTAMP NOT NULL DEFAULT NOW());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 TABLE IF NOT EXISTS orgs (id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),name VARCHAR(255) NOT NULL,@@ -30,6 +33,8 @@ CREATE TABLE IF NOT EXISTS orgs ();CREATE TRIGGER update_orgs_modtime BEFORE UPDATE ON orgs FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();+ALTER TABLE orgs ADD UNIQUE (domain);+CREATE TABLE IF NOT EXISTS orgs_users (id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),org_id UUID NOT NULL REFERENCES orgs(id) ON DELETE CASCADE,@@ -39,13 +44,29 @@ 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 TABLE IF NOT EXISTS auth_tokens (id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,token_hash VARCHAR(64) NOT NULL,- created_at TIMESTAMP NOT NULL DEFAULT NOW()+ created_at TIMESTAMP NOT NULL DEFAULT NOW(),+ deleted_at TIMESTAMP+);+ALTER TABLE auth_tokens ADD UNIQUE (token_hash);++CREATE TABLE IF NOT EXISTS email_verifications (+ id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),+ email VARCHAR(255) NOT NULL,+ pin_hash VARCHAR(64) NOT NULL,+ user_id UUID REFERENCES users(id),+ auth_token_id UUID REFERENCES auth_tokens(id),+ created_at TIMESTAMP NOT NULL DEFAULT NOW(),+ updated_at TIMESTAMP NOT NULL DEFAULT NOW());-CREATE INDEX auth_tokens_hash_idx ON auth_tokens(token_hash);+CREATE TRIGGER update_email_verifications_modtime BEFORE UPDATE ON email_verifications FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();++CREATE UNIQUE INDEX email_verifications_idx ON email_verifications(token_hash, email, created_at DESC);CREATE TABLE IF NOT EXISTS projects (id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),@@ -67,6 +88,7 @@ CREATE TABLE IF NOT EXISTS plans (context_tokens INTEGER NOT NULL DEFAULT 0,convo_tokens INTEGER NOT NULL DEFAULT 0,shared_with_org_at TIMESTAMP,+ total_messages INTEGER NOT NULL DEFAULT 0,archived_at TIMESTAMP,created_at TIMESTAMP NOT NULL DEFAULT NOW(),updated_at TIMESTAMP NOT NULL DEFAULT NOW()diff --git a/server/model/plan/tell.go b/server/model/plan/tell.goindex 7283553f..d24ecdd2 100644--- a/server/model/plan/tell.go+++ b/server/model/plan/tell.go@@ -18,7 +18,7 @@ import ()// Proposal function to create a new proposal-func Tell(planId, currentUserId, currentOrgId string, req *shared.TellPlanRequest) error {+func Tell(plan *db.Plan, currentUserId, currentOrgId string, req *shared.TellPlanRequest) error {// goEnv := os.Getenv("GOENV") // Fetch the GO_ENV environment variable// log.Println("GOENV: " + goEnv)@@ -27,6 +27,8 @@ func Tell(planId, currentUserId, currentOrgId string, req *shared.TellPlanReques// return nil// }+ planId := plan.Id+active := Active.Get(planId)if active != nil {return fmt.Errorf("plan %s already has an active stream", planId)@@ -34,12 +36,13 @@ func Tell(planId, currentUserId, currentOrgId string, req *shared.TellPlanRequesactive = CreateActivePlan(planId, req.Prompt)- go execTellPlan(planId, currentUserId, currentOrgId, req, active)+ go execTellPlan(plan, currentUserId, currentOrgId, req, active)return nil}-func execTellPlan(planId, currentUserId, currentOrgId string, req *shared.TellPlanRequest, active *types.ActivePlan) {+func execTellPlan(plan *db.Plan, currentUserId, currentOrgId string, req *shared.TellPlanRequest, active *types.ActivePlan) {+ planId := plan.Iderr := db.SetPlanStatus(planId, shared.PlanStatusReplying, "")if err != nil {log.Printf("Error setting plan %s status to replying: %v\n", planId, err)@@ -54,13 +57,6 @@ func execTellPlan(planId, currentUserId, currentOrgId string, req *shared.TellPl// get name for plan and rename it's a draftgo func() {- plan, err := db.GetPlan(planId)- if err != nil {- log.Printf("Error getting plan: %v\n", err)- errCh <- fmt.Errorf("error getting plan: %v", err)- return- }-if plan.Name == "draft" {name, err := model.GenPlanName(req.Prompt)@@ -77,6 +73,14 @@ func execTellPlan(planId, currentUserId, currentOrgId string, req *shared.TellPlerrCh <- fmt.Errorf("error renaming plan: %v", err)return}++ err = db.IncNumNonDraftPlans(currentUserId)++ if err != nil {+ log.Printf("Error incrementing num non draft plans: %v\n", err)+ errCh <- fmt.Errorf("error incrementing num non draft plans: %v", err)+ return+ }}errCh <- nildiff --git a/server/routes.go b/server/routes.goindex d8f0a933..9bbb1b20 100644--- a/server/routes.go+++ b/server/routes.go@@ -15,11 +15,17 @@ func InitRoutes() *mux.Router {fmt.Fprintf(w, "OK")})- r.HandleFunc("/accounts/start-trial", handlers.StartTrialHandler).Methods("POST")+ r.HandleFunc("/accounts/start_trial", handlers.StartTrialHandler).Methods("POST")+ r.HandleFunc("/accounts/email_verifications", handlers.CreateEmailVerificationHandler).Methods("POST")+ 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("/orgs", handlers.CreateOrgHandler).Methods("POST")r.HandleFunc("/projects", handlers.CreateProjectHandler).Methods("POST")r.HandleFunc("/projects", handlers.ListProjectsHandler).Methods("GET")- r.HandleFunc("/projects/{projectId}/set-plan", handlers.ProjectSetPlanHandler).Methods("PUT")+ r.HandleFunc("/projects/{projectId}/set_plan", handlers.ProjectSetPlanHandler).Methods("PUT")r.HandleFunc("/projects/{projectId}/rename", handlers.RenameProjectHandler).Methods("PUT")r.HandleFunc("/projects/{projectId}/plans", handlers.ListPlansHandler).Methods("GET")r.HandleFunc("/projects/{projectId}/plans/archive", handlers.ListArchivedPlansHandler).Methods("GET")diff --git a/server/types/auth.go b/server/types/auth.goindex 9139ca29..7757bf3f 100644--- a/server/types/auth.go+++ b/server/types/auth.go@@ -1,6 +1,7 @@package typestype ServerAuth struct {- UserId string- OrgId string+ UserId string+ OrgId string+ TokenHash string}diff --git a/shared/models.go b/shared/models.goindex aeb86751..f4985ab3 100644--- a/shared/models.go+++ b/shared/models.go@@ -8,9 +8,11 @@ type Org struct {}type User struct {- Id string `json:"id"`- Name string `json:"name"`- Email string `json:"email"`+ Id string `json:"id"`+ Name string `json:"name"`+ Email string `json:"email"`+ IsTrial bool `json:"isTrial"`+ NumNonDraftPlans int `db:"num_non_draft_plans"`}type Project struct {@@ -39,6 +41,7 @@ type Plan struct {ContextTokens int `json:"contextTokens"`ConvoTokens int `json:"convoTokens"`SharedWithOrgAt *time.Time `json:"sharedWithOrgAt,omitempty"`+ TotalMessages int `json:"totalMessages"`ArchivedAt *time.Time `json:"archivedAt,omitempty"`CreatedAt time.Time `json:"createdAt"`UpdatedAt time.Time `json:"updatedAt"`diff --git a/shared/req_res.go b/shared/req_res.goindex fa49900b..e09d6b95 100644--- a/shared/req_res.go+++ b/shared/req_res.go@@ -4,10 +4,45 @@ type StartTrialResponse struct {UserId string `json:"userId"`Token string `json:"token"`OrgId string `json:"orgId"`+ Email string `json:"email"`UserName string `json:"userName"`OrgName string `json:"orgName"`}+type CreateEmailVerificationRequest struct {+ Email string `json:"email"`+ UserId string `json:"userId"`+}++type SignInRequest struct {+ Email string `json:"email"`+ Pin string `json:"pin"`+}++type CreateAccountRequest struct {+ Email string `json:"email"`+ Pin string `json:"pin"`+ UserName string `json:"userName"`+}++type SessionResponse struct {+ UserId string `json:"userId"`+ Token string `json:"token"`+ Email string `json:"email"`+ UserName string `json:"userName"`+ Orgs []*Org `json:"orgs"`+}++type CreateOrgRequest struct {+ Name string `json:"name"`+ Domain string `json:"domain"`+ AutoAddDomainUsers bool `json:"autoAddDomainUsers"`+}++type CreateOrgResponse struct {+ Id string `json:"id"`+}+type CreateProjectRequest struct {Name string `json:"name"`}diff --git a/shared/utils.go b/shared/utils.goindex ac3c4220..ad2aa233 100644--- a/shared/utils.go+++ b/shared/utils.go@@ -1,9 +1,25 @@package shared-import "time"+import (+ "crypto/rand"+ "time"+)const TsFormat = "2006-01-02T15:04:05.999Z"func StringTs() string {return time.Now().UTC().Format(TsFormat)}++var letters = []byte("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")++func GetRandomAlphanumeric(n int) ([]byte, error) {+ bytes := make([]byte, n)+ if _, err := rand.Read(bytes); err != nil {+ return nil, err+ }+ for i, b := range bytes {+ bytes[i] = letters[int(b)%len(letters)]+ }+ return bytes, nil+}