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
basic authn/authz implemented
Dane Schneider86d4bdb1a7a1
diff --git a/server/db/auth_helpers.go b/server/db/auth_helpers.goindex 87ae27ec..071ec2aa 100644--- a/server/db/auth_helpers.go+++ b/server/db/auth_helpers.go@@ -5,11 +5,14 @@ import ("database/sql""encoding/hex""fmt"+ "time""github.com/google/uuid")-func GenAuthToken(userId string, tx *sql.Tx) (string, error) {+const tokenExpirationDays = 90++func CreateAuthToken(userId string, tx *sql.Tx) (string, error) {uid := uuid.New()bytes := uid[:]hashBytes := sha256.Sum256(bytes)@@ -23,3 +26,34 @@ func GenAuthToken(userId string, tx *sql.Tx) (string, error) {return uid.String(), nil}++func ValidateAuthToken(token string) (userId string, err error) {+ uid, err := uuid.Parse(token)++ if err != nil {+ return "", fmt.Errorf("error parsing token: %v", err)+ }++ bytes := uid[:]+ hashBytes := sha256.Sum256(bytes)+ hash := 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)++ if err != nil {+ return "", fmt.Errorf("error validating token: %v", err)+ }++ return userId, 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+}diff --git a/server/db/models.go b/server/db/models.goindex 688b8e1d..9cecf918 100644--- a/server/db/models.go+++ b/server/db/models.go@@ -16,7 +16,7 @@ type Org struct {Name string `db:"name"`Domain string `db:"domain"`AutoAddDomainUsers bool `db:"auto_add_domain_users"`- CreatorId string `db:"creator_id"`+ OwnerId string `db:"owner_id"`CreatedAt time.Time `db:"created_at"`UpdatedAt time.Time `db:"updated_at"`}@@ -80,31 +80,33 @@ type UserProject struct {}type Plan struct {- Id string `db:"id"`- OrgId string `db:"org_id"`- CreatorId string `db:"creator_id"`- ProjectId string `db:"project_id"`- Name string `db:"name"`- Status shared.PlanStatus `db:"status"`- Error *string `db:"error"`- ContextTokens int `db:"context_tokens"`- ConvoTokens int `db:"convo_tokens"`- ArchivedAt *time.Time `db:"archived_at,omitempty"`- CreatedAt time.Time `db:"created_at"`- UpdatedAt time.Time `db:"updated_at"`+ Id string `db:"id"`+ OrgId string `db:"org_id"`+ OwnerId string `db:"owner_id"`+ ProjectId string `db:"project_id"`+ Name string `db:"name"`+ Status shared.PlanStatus `db:"status"`+ Error *string `db:"error"`+ ContextTokens int `db:"context_tokens"`+ ConvoTokens int `db:"convo_tokens"`+ SharedWithOrgAt *time.Time `db:"shared_with_org_at,omitempty"`+ ArchivedAt *time.Time `db:"archived_at,omitempty"`+ CreatedAt time.Time `db:"created_at"`+ UpdatedAt time.Time `db:"updated_at"`}func (plan *Plan) ToApi() *shared.Plan {return &shared.Plan{- Id: plan.Id,- CreatorId: plan.CreatorId,- Name: plan.Name,- Status: plan.Status,- ContextTokens: plan.ContextTokens,- ConvoTokens: plan.ConvoTokens,- ArchivedAt: plan.ArchivedAt,- CreatedAt: plan.CreatedAt,- UpdatedAt: plan.UpdatedAt,+ Id: plan.Id,+ OwnerId: plan.OwnerId,+ Name: plan.Name,+ Status: plan.Status,+ ContextTokens: plan.ContextTokens,+ ConvoTokens: plan.ConvoTokens,+ SharedWithOrgAt: plan.SharedWithOrgAt,+ ArchivedAt: plan.ArchivedAt,+ CreatedAt: plan.CreatedAt,+ UpdatedAt: plan.UpdatedAt,}}@@ -160,7 +162,7 @@ func (build *PlanBuild) ToApi() *shared.PlanBuild {type Context struct {Id string `json:"id"`OrgId string `json:"orgId"`- CreatorId string `json:"creatorId"`+ OwnerId string `json:"ownerId"`PlanId string `json:"planId"`ContextType shared.ContextType `json:"contextType"`Name string `json:"name"`@@ -176,7 +178,7 @@ type Context struct {func (context *Context) ToApi() *shared.Context {return &shared.Context{Id: context.Id,- CreatorId: context.CreatorId,+ OwnerId: context.OwnerId,ContextType: context.ContextType,Name: context.Name,Url: context.Url,diff --git a/server/db/plan_helpers.go b/server/db/plan_helpers.goindex 420c8ede..257ce659 100644--- a/server/db/plan_helpers.go+++ b/server/db/plan_helpers.go@@ -13,11 +13,11 @@ import ()func CreatePlan(orgId, projectId, userId, name string) (*Plan, error) {- query := "INSERT INTO plans (org_id, creator_id, project_id, name, status) VALUES (:org_id, :creator_id, :project_id, :name, :status) RETURNING id, created_at, updated_at"+ query := "INSERT INTO plans (org_id, owner_id, project_id, name, status) VALUES (:org_id, :owner_id, :project_id, :name, :status) RETURNING id, created_at, updated_at"plan := &Plan{OrgId: orgId,- CreatorId: userId,+ OwnerId: userId,ProjectId: projectId,Name: name,Status: shared.PlanStatusDraft,@@ -53,7 +53,7 @@ func CreatePlan(orgId, projectId, userId, name string) (*Plan, error) {}func ListPlans(projectId, userId string, archived bool, status string) ([]shared.Plan, error) {- qs := "SELECT id, creator_id, name, status, context_tokens, convo_tokens, archived_at, created_at, updated_at FROM plans WHERE project_id = $1 AND creator_id = $2"+ 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}if archived {@@ -79,7 +79,7 @@ func ListPlans(projectId, userId string, archived bool, status string) ([]sharedfor res.Next() {var plan shared.Plan- err := res.Scan(&plan.Id, &plan.CreatorId, &plan.Name, &plan.Status, &plan.ContextTokens, &plan.ConvoTokens, &plan.ArchivedAt, &plan.CreatedAt, &plan.UpdatedAt)+ err := res.Scan(&plan.Id, &plan.OwnerId, &plan.Name, &plan.Status, &plan.ContextTokens, &plan.ConvoTokens, &plan.SharedWithOrgAt, &plan.ArchivedAt, &plan.CreatedAt, &plan.UpdatedAt)if err != nil {return nil, fmt.Errorf("error scanning plan: %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, creator_id, project_id, name, status, error, context_tokens, convo_tokens, 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, archived_at, created_at, updated_at FROM plans WHERE id = $1", planId)if err != nil {return nil, fmt.Errorf("error getting plan: %v", err)@@ -208,7 +208,7 @@ func StoreDescription(description *ConvoMessageDescription) error {}func DeleteDraftPlans(orgId, projectId, userId string) error {- res, err := Conn.Query("DELETE FROM plans WHERE project_id = $1 AND creator_id = $2 AND name = 'draft' RETURNING id;", projectId, userId)+ res, err := Conn.Query("DELETE FROM plans WHERE project_id = $1 AND owner_id = $2 AND name = 'draft' RETURNING id;", projectId, userId)if err != nil {return fmt.Errorf("error deleting draft plans: %v", err)}@@ -248,8 +248,8 @@ func DeleteDraftPlans(orgId, projectId, userId string) error {return nil}-func DeletePlans(orgId, projectId, userId string) error {- res, err := Conn.Query("DELETE FROM plans WHERE project_id = $1 AND creator_id = $2 RETURNING id;", projectId, userId)+func DeleteOwnerPlans(orgId, projectId, userId string) error {+ res, err := Conn.Query("DELETE FROM plans WHERE project_id = $1 AND owner_id = $2 RETURNING id;", projectId, userId)if err != nil {return fmt.Errorf("error deleting plans: %v", err)}@@ -288,3 +288,42 @@ func DeletePlans(orgId, projectId, userId string) error {return nil}++func ValidatePlanAccess(planId, userId, orgId string) (*Plan, error) {+ // get plan+ plan, err := GetPlan(planId)++ if err != nil {+ return nil, fmt.Errorf("error getting plan: %v", err)+ }++ if plan == nil {+ return nil, nil+ }++ if plan.OrgId != orgId {+ return nil, nil+ }++ hasProjectAccess, err := ValidateProjectAccess(plan.ProjectId, userId, orgId)++ if err != nil {+ return nil, fmt.Errorf("error validating project membership: %v", err)+ }++ if !hasProjectAccess {+ return nil, nil+ }++ // owner has access+ if plan.ProjectId == userId {+ return plan, nil+ }++ // plan is shared with org+ if plan.SharedWithOrgAt != nil {+ return plan, nil+ }++ return nil, nil+}diff --git a/server/db/project_helpers.go b/server/db/project_helpers.gonew file mode 100644index 00000000..552e2624--- /dev/null+++ b/server/db/project_helpers.go@@ -0,0 +1,16 @@+package db++import "fmt"++func ValidateProjectAccess(projectId, userId, orgId string) (bool, error) {++ var count int+ err := Conn.QueryRow("SELECT COUNT(*) FROM users_projects WHERE project_id = $1 AND user_id = $2 AND org_id = $3", projectId, userId, orgId).Scan(&count)++ if err != nil {+ return false, fmt.Errorf("error validating project membership: %v", err)+ }++ return count > 0, nil++}diff --git a/server/handlers/accounts.go b/server/handlers/accounts.goindex 09b026a1..f9af5ab1 100644--- a/server/handlers/accounts.go+++ b/server/handlers/accounts.go@@ -78,7 +78,7 @@ func StartTrialHandler(w http.ResponseWriter, r *http.Request) {// create a new orgorgName := "Trial Org " + tag- orgRow, err := tx.Query("INSERT INTO orgs (name, creator_id, is_trial) VALUES ($1, $2, true) RETURNING id", orgName, userId)+ orgRow, err := tx.Query("INSERT INTO orgs (name, owner_id, is_trial) VALUES ($1, $2, true) RETURNING id", orgName, userId)closedOrgRow := falseif err != nil {@@ -119,7 +119,7 @@ func StartTrialHandler(w http.ResponseWriter, r *http.Request) {}// create auth token- token, err := db.GenAuthToken(userId, tx)+ token, err := db.CreateAuthToken(userId, tx)if err != nil {log.Printf("Error creating auth token: %v\n", err)diff --git a/server/handlers/auth_helpers.go b/server/handlers/auth_helpers.gonew file mode 100644index 00000000..ac18e854--- /dev/null+++ b/server/handlers/auth_helpers.go@@ -0,0 +1,122 @@+package handlers++import (+ "encoding/base64"+ "encoding/json"+ "log"+ "net/http"+ "plandex-server/db"+ "plandex-server/types"+ "strings"++ "github.com/plandex/plandex/shared"+)++func authenticate(w http.ResponseWriter, r *http.Request) *types.ServerAuth {+ log.Println("authenticating request")++ authHeader := r.Header.Get("Authorization")++ if authHeader == "" {+ log.Println("no auth header")+ http.Error(w, "no auth header", http.StatusUnauthorized)+ return nil+ }++ if !strings.HasPrefix(authHeader, "Bearer ") {+ log.Println("invalid auth header")+ http.Error(w, "invalid auth header", http.StatusUnauthorized)+ return nil+ }++ // strip off the "Bearer " prefix+ encoded := strings.TrimPrefix(authHeader, "Bearer ")++ // decode the base64-encoded credentials+ bytes, err := base64.StdEncoding.DecodeString(encoded)++ if err != nil {+ log.Printf("error decoding auth token: %v\n", err)+ http.Error(w, "error decoding auth token", http.StatusUnauthorized)+ return nil+ }++ // parse the credentials+ var parsed shared.AuthHeader+ err = json.Unmarshal(bytes, &parsed)++ if err != nil {+ log.Printf("error parsing auth token: %v\n", err)+ http.Error(w, "error parsing auth token", http.StatusUnauthorized)+ return nil+ }++ // validate the token+ userId, 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)+ return nil+ }++ // validate the org membership+ isMember, err := db.ValidateOrgMembership(userId, parsed.OrgId)++ if err != nil {+ log.Printf("error validating org membership: %v\n", err)+ http.Error(w, "error validating org membership", http.StatusInternalServerError)+ return 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+ }++ return &types.ServerAuth{+ UserId: userId,+ OrgId: parsed.OrgId,+ }+}++func authorizeProject(w http.ResponseWriter, projectId, userId, orgId string) bool {+ log.Println("authorizing project")++ hasProjectAccess, err := db.ValidateProjectAccess(projectId, userId, orgId)++ if err != nil {+ log.Printf("error validating project membership: %v\n", err)+ http.Error(w, "error validating project membership", http.StatusInternalServerError)+ return false+ }++ if !hasProjectAccess {+ log.Println("user is not a member of the project")+ http.Error(w, "not a member of project", http.StatusUnauthorized)+ return false+ }++ return true+}++func authorizePlan(w http.ResponseWriter, planId, userId, orgId string) *db.Plan {+ log.Println("authorizing plan")++ plan, err := db.ValidatePlanAccess(planId, userId, orgId)++ if err != nil {+ log.Printf("error validating plan membership: %v\n", err)+ http.Error(w, "error validating plan membership", http.StatusInternalServerError)+ return nil+ }++ if plan == nil {+ log.Println("user doesn't have access the plan")+ http.Error(w, "no access to plan", http.StatusUnauthorized)+ return nil+ }++ return plan+}diff --git a/server/handlers/plans_changes.go b/server/handlers/plans_changes.goindex 3805947a..4fcfaa0d 100644--- a/server/handlers/plans_changes.go+++ b/server/handlers/plans_changes.go@@ -13,17 +13,21 @@ import (func CurrentPlanHandler(w http.ResponseWriter, r *http.Request) {log.Println("Received request for ListPlanChangesHandler")- // TODO: get this from auth when implemented- currentOrgId := "2ff5bc12-1160-4305-8707-9a165319de5a"-- // TODO: authenticate user and plan access+ auth := authenticate(w, r)+ if auth == nil {+ return+ }vars := mux.Vars(r)planId := vars["planId"]log.Println("planId: ", planId)- contexts, err := db.GetPlanContexts(currentOrgId, planId, true)+ if authorizePlan(w, planId, auth.UserId, auth.OrgId) == nil {+ return+ }++ contexts, err := db.GetPlanContexts(auth.OrgId, planId, true)if err != nil {log.Printf("Error getting plan contexts: %v\n", err)@@ -32,7 +36,7 @@ func CurrentPlanHandler(w http.ResponseWriter, r *http.Request) {}planState, err := db.GetCurrentPlanState(db.CurrentPlanStateParams{- OrgId: currentOrgId,+ OrgId: auth.OrgId,PlanId: planId,Contexts: contexts,})@@ -59,17 +63,20 @@ func CurrentPlanHandler(w http.ResponseWriter, r *http.Request) {func ApplyPlanHandler(w http.ResponseWriter, r *http.Request) {log.Println("Received request for ApplyPlanHandler")- // TODO: get this from auth when implemented- currentOrgId := "2ff5bc12-1160-4305-8707-9a165319de5a"-- // TODO: authenticate user and plan access+ auth := authenticate(w, r)+ if auth == nil {+ return+ }vars := mux.Vars(r)planId := vars["planId"]-log.Println("planId: ", planId)- err := db.ApplyPlan(currentOrgId, planId)+ if authorizePlan(w, planId, auth.UserId, auth.OrgId) == nil {+ return+ }++ err := db.ApplyPlan(auth.OrgId, planId)if err != nil {log.Printf("Error applying plan: %v\n", err)@@ -83,17 +90,20 @@ func ApplyPlanHandler(w http.ResponseWriter, r *http.Request) {func RejectAllChangesHandler(w http.ResponseWriter, r *http.Request) {log.Println("Received request for RejectAllChangesHandler")- // TODO: get this from auth when implemented- currentOrgId := "2ff5bc12-1160-4305-8707-9a165319de5a"-- // TODO: authenticate user and plan access+ auth := authenticate(w, r)+ if auth == nil {+ return+ }vars := mux.Vars(r)planId := vars["planId"]-log.Println("planId: ", planId)- err := db.RejectAllResults(currentOrgId, planId)+ if authorizePlan(w, planId, auth.UserId, auth.OrgId) == nil {+ return+ }++ err := db.RejectAllResults(auth.OrgId, planId)if err != nil {log.Printf("Error rejecting all changes: %v\n", err)@@ -107,10 +117,10 @@ func RejectAllChangesHandler(w http.ResponseWriter, r *http.Request) {func RejectResultHandler(w http.ResponseWriter, r *http.Request) {log.Println("Received request for RejectResultHandler")- // TODO: get this from auth when implemented- currentOrgId := "2ff5bc12-1160-4305-8707-9a165319de5a"-- // TODO: authenticate user and plan access+ auth := authenticate(w, r)+ if auth == nil {+ return+ }vars := mux.Vars(r)planId := vars["planId"]@@ -118,7 +128,11 @@ func RejectResultHandler(w http.ResponseWriter, r *http.Request) {log.Println("planId: ", planId, "resultId: ", resultId)- err := db.RejectPlanFileResult(currentOrgId, planId, resultId, time.Now())+ if authorizePlan(w, planId, auth.UserId, auth.OrgId) == nil {+ return+ }++ err := db.RejectPlanFileResult(auth.OrgId, planId, resultId, time.Now())if err != nil {log.Printf("Error rejecting result: %v\n", err)@@ -132,10 +146,10 @@ func RejectResultHandler(w http.ResponseWriter, r *http.Request) {func RejectReplacementHandler(w http.ResponseWriter, r *http.Request) {log.Println("Received request for RejectReplacementHandler")- // TODO: get this from auth when implemented- currentOrgId := "2ff5bc12-1160-4305-8707-9a165319de5a"-- // TODO: authenticate user and plan access+ auth := authenticate(w, r)+ if auth == nil {+ return+ }vars := mux.Vars(r)planId := vars["planId"]@@ -144,7 +158,11 @@ func RejectReplacementHandler(w http.ResponseWriter, r *http.Request) {log.Println("planId: ", planId, "resultId: ", resultId, "replacementId: ", replacementId)- err := db.RejectReplacement(currentOrgId, planId, resultId, replacementId)+ if authorizePlan(w, planId, auth.UserId, auth.OrgId) == nil {+ return+ }++ err := db.RejectReplacement(auth.OrgId, planId, resultId, replacementId)if err != nil {log.Printf("Error rejecting replacement: %v\n", err)@@ -156,15 +174,36 @@ func RejectReplacementHandler(w http.ResponseWriter, r *http.Request) {}func ArchivePlanHandler(w http.ResponseWriter, r *http.Request) {- log.Println("Received request for ArchivePlanHandler")+ auth := authenticate(w, r)+ if auth == nil {+ return+ }- // TODO: authenticate user and plan access+ log.Println("Received request for ArchivePlanHandler")vars := mux.Vars(r)planId := vars["planId"]-log.Println("planId: ", planId)+ plan := authorizePlan(w, planId, auth.UserId, auth.OrgId)++ if plan == nil {+ return+ }++ // apart from authorization, only the plan owner can archive a plan+ if plan.OwnerId != auth.UserId {+ log.Println("Only the plan owner can archive a plan")+ http.Error(w, "Only the plan owner can archive a plan", http.StatusForbidden)+ return+ }++ if plan.ArchivedAt != nil {+ log.Println("Plan already archived")+ http.Error(w, "Plan already archived", http.StatusBadRequest)+ return+ }+res, err := db.Conn.Exec("UPDATE plans SET archived_at = NOW() WHERE id = $1", planId)if err != nil {diff --git a/server/handlers/plans_context.go b/server/handlers/plans_context.goindex 8adb3562..1b95cf1d 100644--- a/server/handlers/plans_context.go+++ b/server/handlers/plans_context.go@@ -20,17 +20,20 @@ import (func ListContextHandler(w http.ResponseWriter, r *http.Request) {log.Println("Received request for ListContextHandler")- // TODO: get from auth when implemented- // currentUserId := "bc9c75ee-57b0-4552-aa1b-f80cf8c09f3f"- currentOrgId := "2ff5bc12-1160-4305-8707-9a165319de5a"+ auth := authenticate(w, r)+ if auth == nil {+ return+ }- // TODO: authenticate user and plan accessvars := mux.Vars(r)planId := vars["planId"]-log.Println("planId: ", planId)- dbContexts, err := db.GetPlanContexts(currentOrgId, planId, false)+ if authorizePlan(w, planId, auth.UserId, auth.OrgId) == nil {+ return+ }++ dbContexts, err := db.GetPlanContexts(auth.OrgId, planId, false)if err != nil {log.Printf("Error getting contexts: %v\n", err)@@ -58,15 +61,19 @@ func ListContextHandler(w http.ResponseWriter, r *http.Request) {func LoadContextHandler(w http.ResponseWriter, r *http.Request) {log.Println("Received request for LoadContextHandler")- // TODO: get from auth when implemented- currentUserId := "bc9c75ee-57b0-4552-aa1b-f80cf8c09f3f"- currentOrgId := "2ff5bc12-1160-4305-8707-9a165319de5a"+ auth := authenticate(w, r)+ if auth == nil {+ return+ }vars := mux.Vars(r)planId := vars["planId"]-log.Println("planId: ", planId)+ if authorizePlan(w, planId, auth.UserId, auth.OrgId) == nil {+ return+ }+// read the request bodybody, err := io.ReadAll(r.Body)if err != nil {@@ -145,8 +152,8 @@ func LoadContextHandler(w http.ResponseWriter, r *http.Request) {context := db.Context{// Id generated by db layer- OrgId: currentOrgId,- CreatorId: currentUserId,+ OrgId: auth.OrgId,+ OwnerId: auth.UserId,PlanId: planId,ContextType: params.ContextType,Name: params.Name,@@ -185,7 +192,7 @@ func LoadContextHandler(w http.ResponseWriter, r *http.Request) {}commitMsg := shared.SummaryForLoadContext(apiContexts, tokensAdded, totalTokens) + "\n\n" + shared.TableForLoadContext(apiContexts)- err = db.GitAddAndCommit(currentOrgId, planId, commitMsg)+ err = db.GitAddAndCommit(auth.OrgId, planId, commitMsg)if err != nil {log.Printf("Error committing changes: %v\n", err)@@ -222,15 +229,19 @@ func LoadContextHandler(w http.ResponseWriter, r *http.Request) {func UpdateContextHandler(w http.ResponseWriter, r *http.Request) {log.Println("Received request for UpdateContextHandler")- // TODO: get from auth when implemented- // currentUserId := "bc9c75ee-57b0-4552-aa1b-f80cf8c09f3f"- currentOrgId := "2ff5bc12-1160-4305-8707-9a165319de5a"+ auth := authenticate(w, r)+ if auth == nil {+ return+ }vars := mux.Vars(r)planId := vars["planId"]-log.Println("planId: ", planId)+ if authorizePlan(w, planId, auth.UserId, auth.OrgId) == nil {+ return+ }+// read the request bodybody, err := io.ReadAll(r.Body)if err != nil {@@ -271,7 +282,7 @@ func UpdateContextHandler(w http.ResponseWriter, r *http.Request) {for id, params := range requestBody {go func(id string, params *shared.UpdateContextParams) {- context, err := db.GetContext(currentOrgId, planId, id, true)+ context, err := db.GetContext(auth.OrgId, planId, id, true)if err != nil {errCh <- fmt.Errorf("error getting context: %v", err)@@ -378,7 +389,7 @@ func UpdateContextHandler(w http.ResponseWriter, r *http.Request) {}commitMsg := shared.SummaryForUpdateContext(updateRes) + "\n\n" + shared.TableForContextUpdate(updateRes)- err = db.GitAddAndCommit(currentOrgId, planId, commitMsg)+ err = db.GitAddAndCommit(auth.OrgId, planId, commitMsg)if err != nil {log.Printf("Error committing changes: %v\n", err)@@ -415,21 +426,18 @@ func UpdateContextHandler(w http.ResponseWriter, r *http.Request) {func DeleteContextHandler(w http.ResponseWriter, r *http.Request) {log.Println("Received request for DeleteContextHandler")- // TODO: get from auth when implemented- // currentUserId := "bc9c75ee-57b0-4552-aa1b-f80cf8c09f3f"- currentOrgId := "2ff5bc12-1160-4305-8707-9a165319de5a"+ auth := authenticate(w, r)+ if auth == nil {+ return+ }vars := mux.Vars(r)planId := vars["planId"]-log.Println("planId: ", planId)- // load plan- plan, err := db.GetPlan(planId)+ plan := authorizePlan(w, planId, auth.UserId, auth.OrgId)- if err != nil {- log.Printf("Plan not found: %v\n", err)- http.Error(w, "Plan not found: "+err.Error(), http.StatusBadRequest)+ if plan == nil {return}@@ -449,7 +457,7 @@ func DeleteContextHandler(w http.ResponseWriter, r *http.Request) {return}- dbContexts, err := db.GetPlanContexts(currentOrgId, planId, false)+ dbContexts, err := db.GetPlanContexts(auth.OrgId, planId, false)if err != nil {log.Printf("Error getting contexts: %v\n", err)@@ -480,7 +488,7 @@ func DeleteContextHandler(w http.ResponseWriter, r *http.Request) {}commitMsg := shared.SummaryForRemoveContext(toRemoveApiContexts, plan.ContextTokens) + "\n\n" + shared.TableForRemoveContext(toRemoveApiContexts)- err = db.GitAddAndCommit(currentOrgId, planId, commitMsg)+ err = db.GitAddAndCommit(auth.OrgId, planId, commitMsg)if err != nil {log.Printf("Error committing changes: %v\n", err)diff --git a/server/handlers/plans_convo.go b/server/handlers/plans_convo.goindex 38165a21..18e90ff2 100644--- a/server/handlers/plans_convo.go+++ b/server/handlers/plans_convo.go@@ -7,52 +7,20 @@ import ("github.com/gorilla/mux")-// func ConvoSummaryHandler(w http.ResponseWriter, r *http.Request) {-// log.Println("Received a request for ConvoSummaryHandler")--// // get the rootId from the request-// vars := mux.Vars(r)-// rootId := vars["rootId"]--// if rootId == "" {-// log.Println("Received empty rootId field")-// http.Error(w, "rootId field is required", http.StatusBadRequest)-// return-// }--// latestTimestamp := r.URL.Query().Get("latestTimestamp")--// summary := plan.GetConvoSummary(rootId)--// if summary == nil {-// log.Printf("No summary found for rootId %s\n", rootId)-// w.WriteHeader(http.StatusNoContent)-// return-// }--// if latestTimestamp != "" && latestTimestamp == summary.LastMessageTimestamp {-// log.Printf("No new messages found for rootId %s\n", rootId)-// w.WriteHeader(http.StatusNoContent)-// return-// }--// jsonBytes, err := json.Marshal(summary)-// if err != nil {-// log.Printf("Error marshalling summary: %v\n", err)-// http.Error(w, "Error marshalling summary: "+err.Error(), http.StatusInternalServerError)-// return-// }--// log.Println("Successfully processed ConvoSummaryHandler request")-// w.Write(jsonBytes)-// }-func ListConvoHandler(w http.ResponseWriter, r *http.Request) {log.Println("Received a request for ListConvoHandler")+ auth := authenticate(w, r)+ if auth == nil {+ return+ }vars := mux.Vars(r)planId := vars["planId"]log.Println("planId: ", planId)+ if authorizePlan(w, planId, auth.UserId, auth.OrgId) == nil {+ return+ }+}diff --git a/server/handlers/plans_crud.go b/server/handlers/plans_crud.goindex 544e6c90..874ef3fd 100644--- a/server/handlers/plans_crud.go+++ b/server/handlers/plans_crud.go@@ -15,15 +15,20 @@ import (func CreatePlanHandler(w http.ResponseWriter, r *http.Request) {log.Println("Received request for CreatePlanHandler")- // TODO: get from auth when implemented- currentUserId := "bc9c75ee-57b0-4552-aa1b-f80cf8c09f3f"- currentOrgId := "2ff5bc12-1160-4305-8707-9a165319de5a"+ auth := authenticate(w, r)+ if auth == nil {+ return+ }vars := mux.Vars(r)projectId := vars["projectId"]log.Println("projectId: ", projectId)+ if !authorizeProject(w, projectId, auth.UserId, auth.OrgId) {+ return+ }+// read the request bodybody, err := io.ReadAll(r.Body)if err != nil {@@ -47,7 +52,7 @@ func CreatePlanHandler(w http.ResponseWriter, r *http.Request) {if name == "draft" {// delete any existing draft plans- err = db.DeleteDraftPlans(currentOrgId, projectId, currentUserId)+ err = db.DeleteDraftPlans(auth.OrgId, projectId, auth.UserId)if err != nil {log.Printf("Error deleting draft plans: %v\n", err)@@ -59,7 +64,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 creator_id = $2 AND name = $3", projectId, currentUserId, name)+ err := db.Conn.Get(&count, "SELECT COUNT(*) FROM plans WHERE project_id = $1 AND owner_id = $2 AND name = $3", projectId, auth.UserId, name)if err != nil {log.Printf("Error checking if plan exists: %v\n", err)@@ -76,7 +81,7 @@ func CreatePlanHandler(w http.ResponseWriter, r *http.Request) {}}- plan, err := db.CreatePlan(currentOrgId, projectId, currentUserId, name)+ plan, err := db.CreatePlan(auth.OrgId, projectId, auth.UserId, name)if err != nil {log.Printf("Error creating plan: %v\n", err)@@ -105,16 +110,19 @@ 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)+ if auth == nil {+ return+ }+vars := mux.Vars(r)planId := vars["planId"]log.Println("planId: ", planId)- plan, err := db.GetPlan(planId)+ plan := authorizePlan(w, planId, auth.UserId, auth.OrgId)- if err != nil {- log.Printf("Error getting plan: %v\n", err)- http.Error(w, "Error getting plan: "+err.Error(), http.StatusInternalServerError)+ if plan == nil {return}@@ -132,14 +140,28 @@ func GetPlanHandler(w http.ResponseWriter, r *http.Request) {func DeletePlanHandler(w http.ResponseWriter, r *http.Request) {log.Println("Received request for DeletePlanHandler")- // TODO: get from auth when implemented- currentOrgId := "2ff5bc12-1160-4305-8707-9a165319de5a"+ auth := authenticate(w, r)+ if auth == nil {+ return+ }vars := mux.Vars(r)planId := vars["planId"]log.Println("planId: ", planId)+ plan := authorizePlan(w, planId, auth.UserId, auth.OrgId)++ if plan == nil {+ return+ }++ if plan.OwnerId != auth.UserId {+ log.Println("Only the plan owner can delete a plan")+ http.Error(w, "Only the plan owner can delete a plan", http.StatusForbidden)+ return+ }+res, err := db.Conn.Exec("DELETE FROM plans WHERE id = $1", planId)if err != nil {@@ -161,7 +183,7 @@ func DeletePlanHandler(w http.ResponseWriter, r *http.Request) {return}- err = db.DeletePlanDir(currentOrgId, planId)+ err = db.DeletePlanDir(auth.OrgId, planId)if err != nil {log.Printf("Error deleting plan dir: %v\n", err)@@ -175,14 +197,21 @@ func DeletePlanHandler(w http.ResponseWriter, r *http.Request) {func DeleteAllPlansHandler(w http.ResponseWriter, r *http.Request) {log.Println("Received request for DeleteAllPlansHandler")- // TODO: get from auth when implemented- currentOrgId := "2ff5bc12-1160-4305-8707-9a165319de5a"- currentUserId := "bc9c75ee-57b0-4552-aa1b-f80cf8c09f3f"+ auth := authenticate(w, r)+ if auth == nil {+ return+ }vars := mux.Vars(r)projectId := vars["projectId"]- err := db.DeletePlans(currentOrgId, projectId, currentUserId)+ log.Println("projectId: ", projectId)++ if !authorizeProject(w, projectId, auth.UserId, auth.OrgId) {+ return+ }++ err := db.DeleteOwnerPlans(auth.OrgId, projectId, auth.UserId)if err != nil {log.Printf("Error deleting plans: %v\n", err)@@ -195,14 +224,21 @@ func DeleteAllPlansHandler(w http.ResponseWriter, r *http.Request) {func ListPlansHandler(w http.ResponseWriter, r *http.Request) {log.Println("Received request for ListPlansHandler")- currentUserId := "bc9c75ee-57b0-4552-aa1b-f80cf8c09f3f" // TODO: get from auth when implemented+ auth := authenticate(w, r)+ if auth == nil {+ return+ }vars := mux.Vars(r)projectId := vars["projectId"]log.Println("projectId: ", projectId)- plans, err := db.ListPlans(projectId, currentUserId, false, "")+ if !authorizeProject(w, projectId, auth.UserId, auth.OrgId) {+ return+ }++ plans, err := db.ListPlans(projectId, auth.UserId, false, "")if err != nil {log.Printf("Error listing plans: %v\n", err)@@ -224,12 +260,20 @@ 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)+ if auth == nil {+ return+ }vars := mux.Vars(r)projectId := vars["projectId"]log.Println("projectId: ", projectId)+ if !authorizeProject(w, projectId, auth.UserId, auth.OrgId) {+ return+ }+plans, err := db.ListPlans(projectId, "", true, "")if err != nil {@@ -252,12 +296,20 @@ 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)+ if auth == nil {+ return+ }vars := mux.Vars(r)projectId := vars["projectId"]log.Println("projectId: ", projectId)+ if !authorizeProject(w, projectId, auth.UserId, auth.OrgId) {+ return+ }+// TODO: implement when status is figured out}diff --git a/server/handlers/plans_exec.go b/server/handlers/plans_exec.goindex f64d7df5..03bf9cd0 100644--- a/server/handlers/plans_exec.go+++ b/server/handlers/plans_exec.go@@ -14,17 +14,20 @@ import (func TellPlanHandler(w http.ResponseWriter, r *http.Request) {log.Println("Received request for TellPlanHandler")- // TODO: get this from auth when implemented- currentOrgId := "2ff5bc12-1160-4305-8707-9a165319de5a"- currentUserId := "bc9c75ee-57b0-4552-aa1b-f80cf8c09f3f"-- // TODO: authenticate user and plan access+ auth := authenticate(w, r)+ if auth == nil {+ return+ }vars := mux.Vars(r)planId := vars["planId"]log.Println("planId: ", planId)+ if authorizePlan(w, planId, auth.UserId, auth.OrgId) == nil {+ return+ }+body, err := io.ReadAll(r.Body)if err != nil {log.Printf("Error reading request body: %v\n", err)@@ -43,7 +46,7 @@ func TellPlanHandler(w http.ResponseWriter, r *http.Request) {return}- err = plan.Tell(planId, currentUserId, currentOrgId, &requestBody)+ err = plan.Tell(planId, auth.UserId, auth.OrgId, &requestBody)if err != nil {log.Printf("Error telling plan: %v\n", err)@@ -64,30 +67,54 @@ 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)+ if auth == nil {+ return+ }vars := mux.Vars(r)planId := vars["planId"]log.Println("planId: ", planId)+ if authorizePlan(w, planId, auth.UserId, auth.OrgId) == nil {+ return+ }+}func ConnectPlanHandler(w http.ResponseWriter, r *http.Request) {log.Println("Received request for ConnectPlanHandler")+ auth := authenticate(w, r)+ if auth == nil {+ return+ }vars := mux.Vars(r)planId := vars["planId"]log.Println("planId: ", planId)+ if authorizePlan(w, planId, auth.UserId, auth.OrgId) == nil {+ return+ }+}func StopPlanHandler(w http.ResponseWriter, r *http.Request) {log.Println("Received request for StopPlanHandler")+ auth := authenticate(w, r)+ if auth == nil {+ return+ }vars := mux.Vars(r)planId := vars["planId"]log.Println("planId: ", planId)+ if authorizePlan(w, planId, auth.UserId, auth.OrgId) == nil {+ return+ }+}diff --git a/server/handlers/plans_versions.go b/server/handlers/plans_versions.goindex 3f3818d9..c87ea1e3 100644--- a/server/handlers/plans_versions.go+++ b/server/handlers/plans_versions.go@@ -14,15 +14,21 @@ import (func ListLogsHandler(w http.ResponseWriter, r *http.Request) {log.Println("Received request for ListLogsHandler")- // TODO: get from auth when implemented- currentOrgId := "2ff5bc12-1160-4305-8707-9a165319de5a"+ auth := authenticate(w, r)+ if auth == nil {+ return+ }vars := mux.Vars(r)planId := vars["planId"]log.Println("planId: ", planId)- body, shas, err := db.GetGitCommitHistory(currentOrgId, planId)+ if authorizePlan(w, planId, auth.UserId, auth.OrgId) == nil {+ return+ }++ body, shas, err := db.GetGitCommitHistory(auth.OrgId, planId)if err != nil {log.Println("Error getting logs: ", err)@@ -51,14 +57,20 @@ func ListLogsHandler(w http.ResponseWriter, r *http.Request) {func RewindPlanHandler(w http.ResponseWriter, r *http.Request) {log.Println("Received request for RewindPlanHandler")- // TODO: get from auth when implemented- currentOrgId := "2ff5bc12-1160-4305-8707-9a165319de5a"+ auth := authenticate(w, r)+ if auth == nil {+ return+ }vars := mux.Vars(r)planId := vars["planId"]log.Println("planId: ", planId)+ if authorizePlan(w, planId, auth.UserId, auth.OrgId) == nil {+ return+ }+// read the request bodybody, err := io.ReadAll(r.Body)if err != nil {@@ -75,7 +87,7 @@ func RewindPlanHandler(w http.ResponseWriter, r *http.Request) {return}- err = db.GitRewindToSha(currentOrgId, planId, requestBody.Sha)+ err = db.GitRewindToSha(auth.OrgId, planId, requestBody.Sha)if err != nil {log.Println("Error rewinding plan: ", err)@@ -83,7 +95,7 @@ func RewindPlanHandler(w http.ResponseWriter, r *http.Request) {return}- err = db.SyncPlanTokens(currentOrgId, planId)+ err = db.SyncPlanTokens(auth.OrgId, planId)if err != nil {log.Println("Error syncing plan tokens: ", err)@@ -91,7 +103,7 @@ func RewindPlanHandler(w http.ResponseWriter, r *http.Request) {return}- sha, latest, err := db.GetLatestCommit(currentOrgId, planId)+ sha, latest, err := db.GetLatestCommit(auth.OrgId, planId)if err != nil {log.Println("Error getting latest commit: ", err)diff --git a/server/handlers/projects.go b/server/handlers/projects.goindex c6fedd08..a2ba13e5 100644--- a/server/handlers/projects.go+++ b/server/handlers/projects.go@@ -15,7 +15,10 @@ import (func CreateProjectHandler(w http.ResponseWriter, r *http.Request) {log.Println("Received request for CreateProjectHandler")- currentOrgId := "2ff5bc12-1160-4305-8707-9a165319de5a" // TODO: get from auth when implemented+ auth := authenticate(w, r)+ if auth == nil {+ return+ }// read the request bodybody, err := io.ReadAll(r.Body)@@ -41,7 +44,7 @@ func CreateProjectHandler(w http.ResponseWriter, r *http.Request) {id := uuid.New().String()- _, err = db.Conn.Exec("INSERT INTO projects (id, org_id, name) VALUES ($1, $2, $3)", id, currentOrgId, requestBody.Name)+ _, err = db.Conn.Exec("INSERT INTO projects (id, org_id, name) VALUES ($1, $2, $3)", id, auth.OrgId, requestBody.Name)if err != nil {log.Printf("Error creating project: %v\n", err)@@ -70,9 +73,12 @@ func CreateProjectHandler(w http.ResponseWriter, r *http.Request) {func ListProjectsHandler(w http.ResponseWriter, r *http.Request) {log.Println("Received request for ListProjectsHandler")- userId := "bc9c75ee-57b0-4552-aa1b-f80cf8c09f3f" // TODO: get from auth when implemented+ auth := authenticate(w, r)+ if auth == nil {+ return+ }- 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", userId)+ 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)if err != nil {log.Printf("Error listing projects: %v\n", err)@@ -105,12 +111,20 @@ 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)+ if auth == nil {+ return+ }vars := mux.Vars(r)projectId := vars["projectId"]log.Println("projectId: ", projectId)+ if !authorizeProject(w, projectId, auth.UserId, auth.OrgId) {+ return+ }+// read the request bodybody, err := io.ReadAll(r.Body)if err != nil {@@ -146,12 +160,20 @@ 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)+ if auth == nil {+ return+ }vars := mux.Vars(r)projectId := vars["projectId"]log.Println("projectId: ", projectId)+ if !authorizeProject(w, projectId, auth.UserId, auth.OrgId) {+ return+ }+// read the request bodybody, err := io.ReadAll(r.Body)if err != nil {diff --git a/server/migrations/2023120500_init.up.sql b/server/migrations/2023120500_init.up.sqlindex ea5227a3..055cc1df 100644--- a/server/migrations/2023120500_init.up.sql+++ b/server/migrations/2023120500_init.up.sql@@ -23,7 +23,7 @@ CREATE TABLE IF NOT EXISTS orgs (name VARCHAR(255) NOT NULL,domain VARCHAR(255),auto_add_domain_users BOOLEAN NOT NULL DEFAULT FALSE,- creator_id UUID NOT NULL REFERENCES users(id),+ owner_id UUID NOT NULL REFERENCES users(id),is_trial BOOLEAN NOT NULL,created_at TIMESTAMP NOT NULL DEFAULT NOW(),updated_at TIMESTAMP NOT NULL DEFAULT NOW()@@ -59,21 +59,22 @@ CREATE TRIGGER update_projects_modtime BEFORE UPDATE ON projects FOR EACH ROW EXCREATE TABLE IF NOT EXISTS plans (id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),org_id UUID NOT NULL REFERENCES orgs(id) ON DELETE CASCADE,- creator_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,+ owner_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,project_id UUID NOT NULL REFERENCES projects(id) ON DELETE CASCADE,name VARCHAR(255) NOT NULL,status VARCHAR(32) NOT NULL,error TEXT,context_tokens INTEGER NOT NULL DEFAULT 0,convo_tokens INTEGER NOT NULL DEFAULT 0,+ shared_with_org_at TIMESTAMP,archived_at TIMESTAMP,created_at TIMESTAMP NOT NULL DEFAULT NOW(),updated_at TIMESTAMP NOT NULL DEFAULT NOW());CREATE TRIGGER update_plans_modtime BEFORE UPDATE ON plans FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();-CREATE INDEX plans_name_idx ON plans(project_id, creator_id, name);-CREATE INDEX plans_archived_idx ON plans(project_id, creator_id, archived_at);+CREATE INDEX plans_name_idx ON plans(project_id, owner_id, name);+CREATE INDEX plans_archived_idx ON plans(project_id, owner_id, archived_at);CREATE TABLE IF NOT EXISTS users_projects (id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),@@ -86,7 +87,7 @@ CREATE TABLE IF NOT EXISTS users_projects ();CREATE TRIGGER update_users_projects_modtime BEFORE UPDATE ON users_projects FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();-CREATE INDEX users_projects_idx ON users_projects(project_id);+CREATE INDEX users_projects_idx ON users_projects(user_id, org_id, project_id);CREATE TABLE IF NOT EXISTS convo_summaries (id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),diff --git a/server/types/auth.go b/server/types/auth.gonew file mode 100644index 00000000..9139ca29--- /dev/null+++ b/server/types/auth.go@@ -0,0 +1,6 @@+package types++type ServerAuth struct {+ UserId string+ OrgId string+}diff --git a/shared/models.go b/shared/models.goindex 9b3d5d3b..aeb86751 100644--- a/shared/models.go+++ b/shared/models.go@@ -32,15 +32,16 @@ const ()type Plan struct {- Id string `json:"id"`- CreatorId string `json:"creatorId"`- Name string `json:"name"`- Status PlanStatus `json:"status"`- ContextTokens int `json:"contextTokens"`- ConvoTokens int `json:"convoTokens"`- ArchivedAt *time.Time `json:"archivedAt,omitempty"`- CreatedAt time.Time `json:"createdAt"`- UpdatedAt time.Time `json:"updatedAt"`+ Id string `json:"id"`+ OwnerId string `json:"ownerId"`+ Name string `json:"name"`+ Status PlanStatus `json:"status"`+ ContextTokens int `json:"contextTokens"`+ ConvoTokens int `json:"convoTokens"`+ SharedWithOrgAt *time.Time `json:"sharedWithOrgAt,omitempty"`+ ArchivedAt *time.Time `json:"archivedAt,omitempty"`+ CreatedAt time.Time `json:"createdAt"`+ UpdatedAt time.Time `json:"updatedAt"`}type ContextType string@@ -55,7 +56,7 @@ const (type Context struct {Id string `json:"id"`- CreatorId string `json:"creatorId"`+ OwnerId string `json:"ownerId"`ContextType ContextType `json:"contextType"`Name string `json:"name"`Url string `json:"url"`