Skip to content

Open source AI coding agent. Designed for large projects and real world tasks.

rbac, auth, and error handling

Dane Schneiderc818cfcacb9a
diff --git a/cli/api/errors.go b/cli/api/errors.go
index 08709850..add9455d 100644
--- a/cli/api/errors.go
+++ b/cli/api/errors.go
@@ -2,8 +2,10 @@ package api
import (
"encoding/json"
+ "fmt"
"log"
"net/http"
+ "plandex/auth"
"github.com/plandex/plandex/shared"
)
@@ -30,3 +32,14 @@ func handleApiError(r *http.Response, errBody []byte) *shared.ApiError {
return &apiError
}
+
+func refreshTokenIfNeeded(apiErr *shared.ApiError) (bool, *shared.ApiError) {
+ if apiErr.Type == shared.ApiErrorTypeInvalidToken {
+ err := auth.RefreshInvalidToken()
+ if err != nil {
+ return false, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error refreshing invalid token")}
+ }
+ return true, nil
+ }
+ return false, apiErr
+}
diff --git a/cli/api/methods.go b/cli/api/methods.go
index 73135472..67e438eb 100644
--- a/cli/api/methods.go
+++ b/cli/api/methods.go
@@ -53,6 +53,10 @@ func (a *Api) CreateProject(req shared.CreateProjectRequest) (*shared.CreateProj
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
apiErr := handleApiError(resp, errorBody)
+ tokenRefreshed, apiErr := refreshTokenIfNeeded(apiErr)
+ if tokenRefreshed {
+ return a.CreateProject(req)
+ }
return nil, apiErr
}
@@ -76,6 +80,10 @@ func (a *Api) ListProjects() ([]*shared.Project, *shared.ApiError) {
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
apiErr := handleApiError(resp, errorBody)
+ tokenRefreshed, apiErr := refreshTokenIfNeeded(apiErr)
+ if tokenRefreshed {
+ return a.ListProjects()
+ }
return nil, apiErr
}
@@ -109,7 +117,12 @@ func (a *Api) SetProjectPlan(projectId string, req shared.SetProjectPlanRequest)
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
- return handleApiError(resp, errorBody)
+ apiErr := handleApiError(resp, errorBody)
+ didRefresh, apiErr := refreshTokenIfNeeded(apiErr)
+ if didRefresh {
+ return a.SetProjectPlan(projectId, req)
+ }
+ return apiErr
}
return nil
@@ -136,7 +149,13 @@ func (a *Api) RenameProject(projectId string, req shared.RenameProjectRequest) *
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
- return handleApiError(resp, errorBody)
+ apiErr := handleApiError(resp, errorBody)
+
+ didRefresh, apiErr := refreshTokenIfNeeded(apiErr)
+ if didRefresh {
+ return a.RenameProject(projectId, req)
+ }
+ return apiErr
}
return nil
@@ -154,6 +173,10 @@ func (a *Api) ListPlans(projectId string) ([]*shared.Plan, *shared.ApiError) {
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
apiErr := handleApiError(resp, errorBody)
+ tokenRefreshed, apiErr := refreshTokenIfNeeded(apiErr)
+ if tokenRefreshed {
+ return a.ListPlans(projectId)
+ }
return nil, apiErr
}
@@ -178,6 +201,10 @@ func (a *Api) ListArchivedPlans(projectId string) ([]*shared.Plan, *shared.ApiEr
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
apiErr := handleApiError(resp, errorBody)
+ tokenRefreshed, apiErr := refreshTokenIfNeeded(apiErr)
+ if tokenRefreshed {
+ return a.ListArchivedPlans(projectId)
+ }
return nil, apiErr
}
@@ -202,6 +229,10 @@ func (a *Api) ListPlansRunning(projectId string) ([]*shared.Plan, *shared.ApiErr
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
apiErr := handleApiError(resp, errorBody)
+ tokenRefreshed, apiErr := refreshTokenIfNeeded(apiErr)
+ if tokenRefreshed {
+ return a.ListPlansRunning(projectId)
+ }
return nil, apiErr
}
@@ -230,6 +261,10 @@ func (a *Api) CreatePlan(projectId string, req shared.CreatePlanRequest) (*share
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
apiErr := handleApiError(resp, errorBody)
+ tokenRefreshed, apiErr := refreshTokenIfNeeded(apiErr)
+ if tokenRefreshed {
+ return a.CreatePlan(projectId, req)
+ }
return nil, apiErr
}
@@ -255,6 +290,10 @@ func (a *Api) GetPlan(planId string) (*shared.Plan, *shared.ApiError) {
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
apiErr := handleApiError(resp, errorBody)
+ tokenRefreshed, apiErr := refreshTokenIfNeeded(apiErr)
+ if tokenRefreshed {
+ return a.GetPlan(planId)
+ }
return nil, apiErr
}
@@ -283,7 +322,13 @@ func (a *Api) DeletePlan(planId string) *shared.ApiError {
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
- return handleApiError(resp, errorBody)
+ apiErr := handleApiError(resp, errorBody)
+
+ didRefresh, apiErr := refreshTokenIfNeeded(apiErr)
+ if didRefresh {
+ return a.DeletePlan(planId)
+ }
+ return apiErr
}
return nil
@@ -305,7 +350,14 @@ func (a *Api) DeleteAllPlans(projectId string) *shared.ApiError {
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
- return handleApiError(resp, errorBody)
+ apiErr := handleApiError(resp, errorBody)
+
+ didRefresh, apiErr := refreshTokenIfNeeded(apiErr)
+
+ if didRefresh {
+ return a.DeleteAllPlans(projectId)
+ }
+ return apiErr
}
return nil
@@ -339,7 +391,14 @@ func (a *Api) TellPlan(planId string, req shared.TellPlanRequest, onStream types
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
- return handleApiError(resp, errorBody)
+ apiErr := handleApiError(resp, errorBody)
+
+ didRefresh, apiErr := refreshTokenIfNeeded(apiErr)
+
+ if didRefresh {
+ return a.TellPlan(planId, req, onStream)
+ }
+ return apiErr
}
if req.ConnectStream {
@@ -366,7 +425,15 @@ func (a *Api) ConnectPlan(planId string, onStream types.OnStreamPlan) *shared.Ap
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
- return handleApiError(resp, errorBody)
+ apiErr := handleApiError(resp, errorBody)
+
+ didRefresh, apiErr := refreshTokenIfNeeded(apiErr)
+
+ if didRefresh {
+ return a.ConnectPlan(planId, onStream)
+ }
+
+ return apiErr
}
connectPlanRespStream(resp.Body, onStream)
@@ -390,7 +457,12 @@ func (a *Api) StopPlan(planId string) *shared.ApiError {
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
- return handleApiError(resp, errorBody)
+ apiErr := handleApiError(resp, errorBody)
+ didRefresh, apiErr := refreshTokenIfNeeded(apiErr)
+ if didRefresh {
+ return a.StopPlan(planId)
+ }
+ return apiErr
}
return nil
@@ -408,6 +480,10 @@ func (a *Api) GetCurrentPlanState(planId string) (*shared.CurrentPlanState, *sha
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
apiErr := handleApiError(resp, errorBody)
+ tokenRefreshed, apiErr := refreshTokenIfNeeded(apiErr)
+ if tokenRefreshed {
+ return a.GetCurrentPlanState(planId)
+ }
return nil, apiErr
}
@@ -436,7 +512,13 @@ func (a *Api) ApplyPlan(planId string) *shared.ApiError {
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
- return handleApiError(resp, errorBody)
+ apiErr := handleApiError(resp, errorBody)
+
+ didRefresh, apiErr := refreshTokenIfNeeded(apiErr)
+ if didRefresh {
+ return a.ApplyPlan(planId)
+ }
+ return apiErr
}
return nil
@@ -458,7 +540,13 @@ func (a *Api) ArchivePlan(planId string) *shared.ApiError {
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
- return handleApiError(resp, errorBody)
+ apiErr := handleApiError(resp, errorBody)
+
+ didRefresh, apiErr := refreshTokenIfNeeded(apiErr)
+ if didRefresh {
+ return a.ArchivePlan(planId)
+ }
+ return apiErr
}
return nil
@@ -480,7 +568,13 @@ func (a *Api) RejectAllChanges(planId string) *shared.ApiError {
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
- return handleApiError(resp, errorBody)
+ apiErr := handleApiError(resp, errorBody)
+
+ didRefresh, apiErr := refreshTokenIfNeeded(apiErr)
+ if didRefresh {
+ return a.RejectAllChanges(planId)
+ }
+ return apiErr
}
return nil
@@ -502,7 +596,12 @@ func (a *Api) RejectResult(planId, resultId string) *shared.ApiError {
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
- return handleApiError(resp, errorBody)
+ apiErr := handleApiError(resp, errorBody)
+ didRefresh, apiErr := refreshTokenIfNeeded(apiErr)
+ if didRefresh {
+ a.RejectResult(planId, resultId)
+ }
+ return apiErr
}
return nil
@@ -524,7 +623,13 @@ func (a *Api) RejectReplacement(planId, resultId, replacementId string) *shared.
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
- return handleApiError(resp, errorBody)
+ apiErr := handleApiError(resp, errorBody)
+
+ didRefresh, apiErr := refreshTokenIfNeeded(apiErr)
+ if didRefresh {
+ a.RejectReplacement(planId, resultId, replacementId)
+ }
+ return apiErr
}
return nil
@@ -547,6 +652,10 @@ func (a *Api) LoadContext(planId string, req shared.LoadContextRequest) (*shared
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
apiErr := handleApiError(resp, errorBody)
+ tokenRefreshed, apiErr := refreshTokenIfNeeded(apiErr)
+ if tokenRefreshed {
+ return a.LoadContext(planId, req)
+ }
return nil, apiErr
}
@@ -585,6 +694,10 @@ func (a *Api) UpdateContext(planId string, req shared.UpdateContextRequest) (*sh
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
apiErr := handleApiError(resp, errorBody)
+ tokenRefreshed, apiErr := refreshTokenIfNeeded(apiErr)
+ if tokenRefreshed {
+ return a.UpdateContext(planId, req)
+ }
return nil, apiErr
}
@@ -619,6 +732,10 @@ func (a *Api) DeleteContext(planId string, req shared.DeleteContextRequest) (*sh
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
apiErr := handleApiError(resp, errorBody)
+ tokenRefreshed, apiErr := refreshTokenIfNeeded(apiErr)
+ if tokenRefreshed {
+ return a.DeleteContext(planId, req)
+ }
return nil, apiErr
}
@@ -643,6 +760,10 @@ func (a *Api) ListContext(planId string) ([]*shared.Context, *shared.ApiError) {
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
apiErr := handleApiError(resp, errorBody)
+ tokenRefreshed, apiErr := refreshTokenIfNeeded(apiErr)
+ if tokenRefreshed {
+ return a.ListContext(planId)
+ }
return nil, apiErr
}
@@ -667,6 +788,10 @@ func (a *Api) ListConvo(planId string) ([]*shared.ConvoMessage, *shared.ApiError
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
apiErr := handleApiError(resp, errorBody)
+ tokenRefreshed, apiErr := refreshTokenIfNeeded(apiErr)
+ if tokenRefreshed {
+ return a.ListConvo(planId)
+ }
return nil, apiErr
}
@@ -692,6 +817,10 @@ func (a *Api) ListLogs(planId string) (*shared.LogResponse, *shared.ApiError) {
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
apiErr := handleApiError(resp, errorBody)
+ tokenRefreshed, apiErr := refreshTokenIfNeeded(apiErr)
+ if tokenRefreshed {
+ return a.ListLogs(planId)
+ }
return nil, apiErr
}
@@ -727,6 +856,10 @@ func (a *Api) RewindPlan(planId string, req shared.RewindPlanRequest) (*shared.R
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
apiErr := handleApiError(resp, errorBody)
+ tokenRefreshed, apiErr := refreshTokenIfNeeded(apiErr)
+ if tokenRefreshed {
+ return a.RewindPlan(planId, req)
+ }
return nil, apiErr
}
@@ -839,6 +972,10 @@ func (a *Api) CreateOrg(req shared.CreateOrgRequest) (*shared.CreateOrgResponse,
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
apiErr := handleApiError(resp, errorBody)
+ tokenRefreshed, apiErr := refreshTokenIfNeeded(apiErr)
+ if tokenRefreshed {
+ return a.CreateOrg(req)
+ }
return nil, apiErr
}
@@ -862,6 +999,10 @@ func (a *Api) ListOrgs() ([]*shared.Org, *shared.ApiError) {
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
apiErr := handleApiError(resp, errorBody)
+ tokenRefreshed, apiErr := refreshTokenIfNeeded(apiErr)
+ if tokenRefreshed {
+ return a.ListOrgs()
+ }
return nil, apiErr
}
@@ -889,12 +1030,45 @@ func (a *Api) DeleteUser(userId string) *shared.ApiError {
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
- return handleApiError(resp, errorBody)
+ apiErr := handleApiError(resp, errorBody)
+ tokenRefreshed, apiErr := refreshTokenIfNeeded(apiErr)
+ if tokenRefreshed {
+ return a.DeleteUser(userId)
+ }
+ return apiErr
}
return nil
}
+func (a *Api) ListOrgRoles() ([]*shared.OrgRole, *shared.ApiError) {
+ serverUrl := getApiHost() + "/orgs/roles"
+ resp, err := authenticatedFastClient.Get(serverUrl)
+ if err != nil {
+ return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error sending request: %s", err)}
+ }
+ defer resp.Body.Close()
+
+ if resp.StatusCode >= 400 {
+ errorBody, _ := io.ReadAll(resp.Body)
+
+ apiErr := handleApiError(resp, errorBody)
+ tokenRefreshed, apiErr := refreshTokenIfNeeded(apiErr)
+ if tokenRefreshed {
+ return a.ListOrgRoles()
+ }
+ return nil, apiErr
+ }
+
+ var roles []*shared.OrgRole
+ err = json.NewDecoder(resp.Body).Decode(&roles)
+ if err != nil {
+ return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error decoding response: %s", err)}
+ }
+
+ return roles, nil
+}
+
func (a *Api) InviteUser(req shared.InviteRequest) *shared.ApiError {
serverUrl := getApiHost() + "/invites"
reqBytes, err := json.Marshal(req)
@@ -910,7 +1084,13 @@ func (a *Api) InviteUser(req shared.InviteRequest) *shared.ApiError {
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
- return handleApiError(resp, errorBody)
+ apiErr := handleApiError(resp, errorBody)
+
+ tokenRefreshed, apiErr := refreshTokenIfNeeded(apiErr)
+ if tokenRefreshed {
+ return a.InviteUser(req)
+ }
+ return apiErr
}
return nil
@@ -927,6 +1107,10 @@ func (a *Api) ListPendingInvites() ([]*shared.Invite, *shared.ApiError) {
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
apiErr := handleApiError(resp, errorBody)
+ tokenRefreshed, apiErr := refreshTokenIfNeeded(apiErr)
+ if tokenRefreshed {
+ return a.ListPendingInvites()
+ }
return nil, apiErr
}
@@ -950,6 +1134,10 @@ func (a *Api) ListAcceptedInvites() ([]*shared.Invite, *shared.ApiError) {
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
apiErr := handleApiError(resp, errorBody)
+ tokenRefreshed, apiErr := refreshTokenIfNeeded(apiErr)
+ if tokenRefreshed {
+ return a.ListAcceptedInvites()
+ }
return nil, apiErr
}
@@ -973,6 +1161,10 @@ func (a *Api) ListAllInvites() ([]*shared.Invite, *shared.ApiError) {
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
apiErr := handleApiError(resp, errorBody)
+ tokenRefreshed, apiErr := refreshTokenIfNeeded(apiErr)
+ if tokenRefreshed {
+ return a.ListAllInvites()
+ }
return nil, apiErr
}
@@ -1000,7 +1192,13 @@ func (a *Api) DeleteInvite(inviteId string) *shared.ApiError {
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
- return handleApiError(resp, errorBody)
+ apiErr := handleApiError(resp, errorBody)
+
+ tokenRefreshed, apiErr := refreshTokenIfNeeded(apiErr)
+ if tokenRefreshed {
+ return a.DeleteInvite(inviteId)
+ }
+ return apiErr
}
return nil
@@ -1022,8 +1220,7 @@ func (a *Api) CreateEmailVerification(email, customHost, userId string) (*shared
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
- apiErr := handleApiError(resp, errorBody)
- return nil, apiErr
+ return nil, handleApiError(resp, errorBody)
}
var verificationResponse shared.CreateEmailVerificationResponse
@@ -1068,6 +1265,10 @@ func (a *Api) ListUsers() ([]*shared.User, *shared.ApiError) {
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
apiErr := handleApiError(resp, errorBody)
+ tokenRefreshed, apiErr := refreshTokenIfNeeded(apiErr)
+ if tokenRefreshed {
+ return a.ListUsers()
+ }
return nil, apiErr
}
diff --git a/cli/types/api.go b/cli/types/api.go
index af5ac997..17940660 100644
--- a/cli/types/api.go
+++ b/cli/types/api.go
@@ -29,6 +29,8 @@ type ApiClient interface {
ListUsers() ([]*shared.User, *shared.ApiError)
DeleteUser(userId string) *shared.ApiError
+ ListOrgRoles() ([]*shared.OrgRole, *shared.ApiError)
+
InviteUser(req shared.InviteRequest) *shared.ApiError
ListPendingInvites() ([]*shared.Invite, *shared.ApiError)
ListAcceptedInvites() ([]*shared.Invite, *shared.ApiError)
diff --git a/server/db/auth_helpers.go b/server/db/auth_helpers.go
index 376c7cc0..4db6dd52 100644
--- a/server/db/auth_helpers.go
+++ b/server/db/auth_helpers.go
@@ -11,15 +11,15 @@ import (
"github.com/pkg/errors"
)
-const tokenExpirationDays = 90
+const tokenExpirationDays = 90 // (free trial tokens don't expire)
-func CreateAuthToken(userId string, tx *sql.Tx) (token, id string, err error) {
+func CreateAuthToken(userId string, isTrial bool, tx *sql.Tx) (token, id string, err error) {
uid := uuid.New()
bytes := uid[:]
hashBytes := sha256.Sum256(bytes)
hash := hex.EncodeToString(hashBytes[:])
- err = tx.QueryRow("INSERT INTO auth_tokens (user_id, token_hash) VALUES ($1, $2) RETURNING id", userId, hash).Scan(&id)
+ err = tx.QueryRow("INSERT INTO auth_tokens (user_id, token_hash, is_trial) VALUES ($1, $2, $3) RETURNING id", userId, hash, isTrial).Scan(&id)
if err != nil {
return "", "", fmt.Errorf("error creating auth token: %v", err)
@@ -40,7 +40,8 @@ func ValidateAuthToken(token string) (*AuthToken, error) {
tokenHash := hex.EncodeToString(hashBytes[:])
var authToken AuthToken
- err = Conn.Get(&authToken, "SELECT * FROM auth_tokens WHERE token_hash = $1 AND created_at > $2 AND deleted_at IS NULL", tokenHash, time.Now().AddDate(0, 0, -tokenExpirationDays))
+ // free trial tokens don't expire
+ err = Conn.Get(&authToken, "SELECT * FROM auth_tokens WHERE token_hash = $1 AND (created_at > $2 OR is_trial = FALSE) AND deleted_at IS NULL", tokenHash, time.Now().AddDate(0, 0, -tokenExpirationDays))
if err != nil {
if err == sql.ErrNoRows {
@@ -92,3 +93,43 @@ func ValidateEmailVerification(email, pin string) (id string, err error) {
return id, nil
}
+
+func GetUserPermissions(userId, orgId string) ([]string, error) {
+ var permissions []string
+
+ query := `
+ SELECT p.name, p.resource_id
+ FROM permissions p
+ JOIN org_roles_permissions orp ON p.id = orp.permission_id
+ JOIN orgs_users ou ON orp.org_role_id = ou.org_role_id
+ WHERE ou.user_id = $1 AND ou.org_id = $2
+ `
+
+ rows, err := Conn.Query(query, userId, orgId)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+
+ for rows.Next() {
+ var permission string
+ var resourceId sql.NullString
+ if err := rows.Scan(&permission, &resourceId); err != nil {
+ return nil, err
+ }
+
+ toAdd := permission
+ if resourceId.Valid {
+ toAdd = toAdd + "|" + resourceId.String
+ }
+
+ permissions = append(permissions, toAdd)
+ }
+
+ // Check for errors from iterating over rows.
+ if err = rows.Err(); err != nil {
+ return nil, err
+ }
+
+ return permissions, nil
+}
diff --git a/server/db/db.go b/server/db/db.go
index 816efb1d..bd83bd1c 100644
--- a/server/db/db.go
+++ b/server/db/db.go
@@ -49,22 +49,22 @@ func MigrationsUp() error {
}
// Uncomment below to reset migration state to a specific version after a failure
- // if err := m.Force(); err != nil {
+ // if err := m.Force(2024011700); err != nil {
// return fmt.Errorf("error forcing migration version: %v", err)
// }
// Uncomment below to run down migrations in development (resets database)
- // if os.Getenv("GOENV") == "development" {
- // err = m.Down()
- // if err != nil {
- // if err == migrate.ErrNoChange {
- // log.Println("no migrations to run down")
- // } else {
- // return fmt.Errorf("error running down migrations: %v", err)
- // }
- // }
- // log.Println("ran down migrations - database was reset")
- // }
+ if os.Getenv("GOENV") == "development" {
+ err = m.Down()
+ if err != nil {
+ if err == migrate.ErrNoChange {
+ log.Println("no migrations to run down")
+ } else {
+ return fmt.Errorf("error running down migrations: %v", err)
+ }
+ }
+ log.Println("ran down migrations - database was reset")
+ }
err = m.Up()
diff --git a/server/db/invite_helpers.go b/server/db/invite_helpers.go
index b90f0099..194d92cb 100644
--- a/server/db/invite_helpers.go
+++ b/server/db/invite_helpers.go
@@ -131,7 +131,7 @@ func AcceptInvite(invite *Invite, inviteeId string) error {
}
// create org user
- err = CreateOrgUser(invite.OrgId, invite.InviteeId, tx)
+ err = CreateOrgUser(invite.OrgId, invite.InviteeId, invite.OrgRoleId, tx)
if err != nil {
return fmt.Errorf("error creating org user: %v", err)
diff --git a/server/db/models.go b/server/db/models.go
index 08250bd0..0f183011 100644
--- a/server/db/models.go
+++ b/server/db/models.go
@@ -15,6 +15,7 @@ type AuthToken struct {
Id string `db:"id"`
UserId string `db:"user_id"`
TokenHash string `db:"token_hash"`
+ IsTrial bool `db:"is_trial"`
CreatedAt time.Time `db:"created_at"`
DeletedAt time.Time `db:"deleted_at"`
}
@@ -43,6 +44,7 @@ type User struct {
Domain string `db:"domain"`
NumNonDraftPlans int `db:"num_non_draft_plans"`
IsTrial bool `db:"is_trial"`
+ OrgRoleId string `db:"org_role_id"`
CreatedAt time.Time `db:"created_at"`
UpdatedAt time.Time `db:"updated_at"`
}
@@ -52,6 +54,7 @@ func (user *User) ToApi() *shared.User {
Id: user.Id,
Name: user.Name,
Email: user.Email,
+ OrgRoleId: user.OrgRoleId,
NumNonDraftPlans: user.NumNonDraftPlans,
IsTrial: user.IsTrial,
}
@@ -64,6 +67,7 @@ type Invite struct {
Name string `db:"name"`
InviterId string `db:"inviter_id"`
InviteeId string `db:"invitee_id"`
+ OrgRoleId string `db:"org_role_id"`
AcceptedAt *time.Time `db:"accepted_at"`
CreatedAt time.Time `db:"created_at"`
UpdatedAt time.Time `db:"updated_at"`
@@ -77,6 +81,7 @@ func (invite *Invite) ToApi() *shared.Invite {
Name: invite.Name,
InviterId: invite.InviterId,
InviteeId: invite.InviteeId,
+ OrgRoleId: invite.OrgRoleId,
AcceptedAt: invite.AcceptedAt,
CreatedAt: invite.CreatedAt,
}
@@ -196,6 +201,25 @@ func (build *PlanBuild) ToApi() *shared.PlanBuild {
}
}
+type OrgRole struct {
+ Id string `db:"id"`
+ OrgId *string `db:"org_id"`
+ Name string `db:"name"`
+ Label string `db:"label"`
+ Description string `db:"description"`
+ CreatedAt time.Time `db:"created_at"`
+ UpdatedAt time.Time `db:"updated_at"`
+}
+
+func (role *OrgRole) ToApi() *shared.OrgRole {
+ return &shared.OrgRole{
+ Id: role.Id,
+ IsDefault: role.OrgId == nil,
+ Label: role.Label,
+ Description: role.Description,
+ }
+}
+
// Models below are stored in files, not in the database.
// This allows us to store them in a git repo and use git to manage history.
diff --git a/server/db/org_helpers.go b/server/db/org_helpers.go
index 226c14f9..e3e62062 100644
--- a/server/db/org_helpers.go
+++ b/server/db/org_helpers.go
@@ -150,8 +150,8 @@ func DeleteOrgUser(orgId, userId string, tx *sql.Tx) error {
return nil
}
-func CreateOrgUser(orgId, userId string, tx *sql.Tx) error {
- query := "INSERT INTO orgs_users (org_id, user_id) VALUES ($1, $2)"
+func CreateOrgUser(orgId, userId, orgRoleId string, tx *sql.Tx) error {
+ query := "INSERT INTO orgs_users (org_id, user_id, org_role_id) VALUES ($1, $2, $3)"
var err error
if tx == nil {
_, err = Conn.Exec(query, orgId, userId)
@@ -165,3 +165,14 @@ func CreateOrgUser(orgId, userId string, tx *sql.Tx) error {
return nil
}
+
+func ListOrgRoles(orgId string) ([]*OrgRole, error) {
+ var orgRoles []*OrgRole
+ err := Conn.Select(&orgRoles, "SELECT * FROM org_roles WHERE org_id IS NULL OR org_id = $1", orgId)
+
+ if err != nil {
+ return nil, fmt.Errorf("error listing org roles: %v", err)
+ }
+
+ return orgRoles, nil
+}
diff --git a/server/db/rbac_helpers.go b/server/db/rbac_helpers.go
new file mode 100644
index 00000000..ef46e791
--- /dev/null
+++ b/server/db/rbac_helpers.go
@@ -0,0 +1,14 @@
+package db
+
+import "fmt"
+
+func GetOrgOwnerRoleId(orgId string) (string, error) {
+ var roleId string
+ err := Conn.Get(&roleId, "SELECT id FROM org_roles WHERE name = 'owner'", orgId)
+
+ if err != nil {
+ return "", fmt.Errorf("error getting owner role id: %v", err)
+ }
+
+ return roleId, nil
+}
diff --git a/server/handlers/accounts.go b/server/handlers/accounts.go
index d0df1fc5..20c55503 100644
--- a/server/handlers/accounts.go
+++ b/server/handlers/accounts.go
@@ -66,8 +66,17 @@ func StartTrialHandler(w http.ResponseWriter, r *http.Request) {
return
}
+ // get org owner role id
+ orgOwnerRoleId, err := db.GetOrgOwnerRoleId(orgId)
+
+ if err != nil {
+ log.Printf("Error getting org owner role: %v\n", err)
+ http.Error(w, "Error getting org owner role: "+err.Error(), http.StatusInternalServerError)
+ return
+ }
+
// insert org user
- err = db.CreateOrgUser(userId, orgId, tx)
+ err = db.CreateOrgUser(userId, orgId, orgOwnerRoleId, tx)
if err != nil {
log.Printf("Error inserting org user: %v\n", err)
http.Error(w, "Error inserting org user: "+err.Error(), http.StatusInternalServerError)
@@ -75,7 +84,7 @@ func StartTrialHandler(w http.ResponseWriter, r *http.Request) {
}
// create auth token
- token, _, err := db.CreateAuthToken(userId, tx)
+ token, _, err := db.CreateAuthToken(userId, true, tx)
if err != nil {
log.Printf("Error creating auth token: %v\n", err)
@@ -191,7 +200,7 @@ func CreateAccountHandler(w http.ResponseWriter, r *http.Request) {
userId := user.Id
// create auth token
- token, authTokenId, err := db.CreateAuthToken(userId, tx)
+ token, authTokenId, err := db.CreateAuthToken(userId, false, tx)
if err != nil {
log.Printf("Error creating auth token: %v\n", err)
@@ -218,7 +227,16 @@ func CreateAccountHandler(w http.ResponseWriter, r *http.Request) {
}
if org != nil && org.AutoAddDomainUsers {
- err = db.CreateOrgUser(userId, org.Id, tx)
+ // get org owner role id
+ orgOwnerRoleId, err := db.GetOrgOwnerRoleId(org.Id)
+
+ if err != nil {
+ log.Printf("Error getting org owner role: %v\n", err)
+ http.Error(w, "Error getting org owner role: "+err.Error(), http.StatusInternalServerError)
+ return
+ }
+
+ err = db.CreateOrgUser(userId, org.Id, orgOwnerRoleId, tx)
if err != nil {
log.Printf("Error adding org user: %v\n", err)
diff --git a/server/handlers/auth_helpers.go b/server/handlers/auth_helpers.go
index 30bf739a..61e56a70 100644
--- a/server/handlers/auth_helpers.go
+++ b/server/handlers/auth_helpers.go
@@ -55,7 +55,7 @@ func authenticate(w http.ResponseWriter, r *http.Request, requireOrg bool) *type
authToken, err := db.ValidateAuthToken(parsed.Token)
if err != nil {
- writeApiError(w, shared.ApiErr{
+ writeApiError(w, shared.ApiError{
Type: shared.ApiErrorTypeInvalidToken,
Status: http.StatusUnauthorized,
Msg: "Invalid auth token",
@@ -93,13 +93,7 @@ func authenticate(w http.ResponseWriter, r *http.Request, requireOrg bool) *type
return nil
}
- if isMember {
- return &types.ServerAuth{
- AuthToken: authToken,
- User: user,
- OrgId: parsed.OrgId,
- }
- } else {
+ if !isMember {
// check if there's an invite for this user and accept it if so (adds the user to the org)
invite, err := db.GetInviteForOrgUser(parsed.OrgId, authToken.UserId)
@@ -118,11 +112,6 @@ func authenticate(w http.ResponseWriter, r *http.Request, requireOrg bool) *type
return nil
}
- return &types.ServerAuth{
- AuthToken: authToken,
- User: user,
- OrgId: parsed.OrgId,
- }
} else {
log.Println("user is not a member of the org")
http.Error(w, "not a member of org", http.StatusUnauthorized)
@@ -130,12 +119,34 @@ func authenticate(w http.ResponseWriter, r *http.Request, requireOrg bool) *type
}
}
+ // get user permissions
+ permissions, err := db.GetUserPermissions(authToken.UserId, parsed.OrgId)
+
+ if err != nil {
+ log.Printf("error getting user permissions: %v\n", err)
+ http.Error(w, "error getting user permissions", http.StatusInternalServerError)
+ return nil
+ }
+
+ // build the permissions map
+ permissionsMap := make(map[string]bool)
+ for _, permission := range permissions {
+ permissionsMap[permission] = true
+ }
+
+ return &types.ServerAuth{
+ AuthToken: authToken,
+ User: user,
+ OrgId: parsed.OrgId,
+ Permissions: permissionsMap,
+ }
+
}
-func authorizeProject(w http.ResponseWriter, projectId, userId, orgId string) bool {
+func authorizeProject(w http.ResponseWriter, projectId string, auth *types.ServerAuth) bool {
log.Println("authorizing project")
- hasProjectAccess, err := db.ValidateProjectAccess(projectId, userId, orgId)
+ hasProjectAccess, err := db.ValidateProjectAccess(projectId, auth.User.Id, auth.OrgId)
if err != nil {
log.Printf("error validating project membership: %v\n", err)
@@ -152,10 +163,38 @@ func authorizeProject(w http.ResponseWriter, projectId, userId, orgId string) bo
return true
}
-func authorizePlan(w http.ResponseWriter, planId, userId, orgId string) *db.Plan {
+func authorizeProjectRename(w http.ResponseWriter, projectId string, auth *types.ServerAuth) bool {
+ if !authorizeProject(w, projectId, auth) {
+ return false
+ }
+
+ if !auth.HasPermission("rename_any_project") {
+ log.Println("User does not have permission to rename project")
+ http.Error(w, "User does not have permission to rename project", http.StatusForbidden)
+ return false
+ }
+
+ return true
+}
+
+func authorizeProjectDelete(w http.ResponseWriter, projectId string, auth *types.ServerAuth) bool {
+ if !authorizeProject(w, projectId, auth) {
+ return false
+ }
+
+ if !auth.HasPermission("delete_any_project") {
+ log.Println("User does not have permission to delete project")
+ http.Error(w, "User does not have permission to delete project", http.StatusForbidden)
+ return false
+ }
+
+ return true
+}
+
+func authorizePlan(w http.ResponseWriter, planId string, auth *types.ServerAuth) *db.Plan {
log.Println("authorizing plan")
- plan, err := db.ValidatePlanAccess(planId, userId, orgId)
+ plan, err := db.ValidatePlanAccess(planId, auth.User.Id, auth.OrgId)
if err != nil {
log.Printf("error validating plan membership: %v\n", err)
@@ -171,3 +210,67 @@ func authorizePlan(w http.ResponseWriter, planId, userId, orgId string) *db.Plan
return plan
}
+
+func authorizePlanUpdate(w http.ResponseWriter, planId string, auth *types.ServerAuth) *db.Plan {
+ plan := authorizePlan(w, planId, auth)
+
+ if plan == nil {
+ return nil
+ }
+
+ if plan.OwnerId != auth.User.Id && !auth.HasPermission("update_any_plan") {
+ log.Println("User does not have permission to update plan")
+ http.Error(w, "User does not have permission to update plan", http.StatusForbidden)
+ return nil
+ }
+
+ return plan
+}
+
+func authorizePlanDelete(w http.ResponseWriter, planId string, auth *types.ServerAuth) *db.Plan {
+ plan := authorizePlan(w, planId, auth)
+
+ if plan == nil {
+ return nil
+ }
+
+ if plan.OwnerId != auth.User.Id && !auth.HasPermission("delete_any_plan") {
+ log.Println("User does not have permission to delete plan")
+ http.Error(w, "User does not have permission to delete plan", http.StatusForbidden)
+ return nil
+ }
+
+ return plan
+}
+
+func authorizePlanRename(w http.ResponseWriter, planId string, auth *types.ServerAuth) *db.Plan {
+ plan := authorizePlan(w, planId, auth)
+
+ if plan == nil {
+ return nil
+ }
+
+ if plan.OwnerId != auth.User.Id && !auth.HasPermission("rename_any_plan") {
+ log.Println("User does not have permission to rename plan")
+ http.Error(w, "User does not have permission to rename plan", http.StatusForbidden)
+ return nil
+ }
+
+ return plan
+}
+
+func authorizePlanArchive(w http.ResponseWriter, planId string, auth *types.ServerAuth) *db.Plan {
+ plan := authorizePlan(w, planId, auth)
+
+ if plan == nil {
+ return nil
+ }
+
+ if plan.OwnerId != auth.User.Id && !auth.HasPermission("archive_any_plan") {
+ log.Println("User does not have permission to archive plan")
+ http.Error(w, "User does not have permission to archive plan", http.StatusForbidden)
+ return nil
+ }
+
+ return plan
+}
diff --git a/server/handlers/err_helper.go b/server/handlers/err_helper.go
index 5af081e1..276b6157 100644
--- a/server/handlers/err_helper.go
+++ b/server/handlers/err_helper.go
@@ -8,7 +8,7 @@ import (
"github.com/plandex/plandex/shared"
)
-func writeApiError(w http.ResponseWriter, apiErr shared.ApiErr) {
+func writeApiError(w http.ResponseWriter, apiErr shared.ApiError) {
bytes, err := json.Marshal(apiErr)
if err != nil {
log.Printf("Error marshalling response: %v\n", err)
diff --git a/server/handlers/invites.go b/server/handlers/invites.go
index 8c356dad..c29be4f4 100644
--- a/server/handlers/invites.go
+++ b/server/handlers/invites.go
@@ -19,8 +19,12 @@ func InviteUserHandler(w http.ResponseWriter, r *http.Request) {
}
if auth.User.IsTrial {
- log.Println("Trial user can't invite other users")
- http.Error(w, "Trial user can't invite other users", http.StatusForbidden)
+ writeApiError(w, shared.ApiError{
+ Type: shared.ApiErrorTypeTrialActionNotAllowed,
+ Status: http.StatusForbidden,
+ Msg: "Free trial user can't invite other users",
+ })
+
return
}
@@ -35,6 +39,13 @@ func InviteUserHandler(w http.ResponseWriter, r *http.Request) {
}
req.Email = strings.ToLower(req.Email)
+ // ensure current user can invite target user
+ if !auth.HasPermission(strings.Join([]string{"invite_user", req.OrgRoleId}, "|")) {
+ log.Printf("User does not have permission to invite user with role: %v\n", req.OrgRoleId)
+ http.Error(w, "User does not have permission to invite user with role: "+req.OrgRoleId, http.StatusForbidden)
+ return
+ }
+
// ensure user doesn't already have access to org via domain
split := strings.Split(req.Email, "@")
if len(split) != 2 {
@@ -98,6 +109,7 @@ func InviteUserHandler(w http.ResponseWriter, r *http.Request) {
err = db.CreateInvite(&db.Invite{
OrgId: auth.OrgId,
+ OrgRoleId: req.OrgRoleId,
Email: req.Email,
Name: req.Name,
InviterId: currentUserId,
@@ -120,8 +132,11 @@ func ListPendingInvitesHandler(w http.ResponseWriter, r *http.Request) {
}
if auth.User.IsTrial {
- log.Println("Trial user can't list invites")
- http.Error(w, "Trial user can't list invites", http.StatusForbidden)
+ writeApiError(w, shared.ApiError{
+ Type: shared.ApiErrorTypeTrialActionNotAllowed,
+ Status: http.StatusForbidden,
+ Msg: "Free trial user can't list invites",
+ })
return
}
@@ -158,8 +173,11 @@ func ListAcceptedInvitesHandler(w http.ResponseWriter, r *http.Request) {
}
if auth.User.IsTrial {
- log.Println("Trial user can't list invites")
- http.Error(w, "Trial user can't list invites", http.StatusForbidden)
+ writeApiError(w, shared.ApiError{
+ Type: shared.ApiErrorTypeTrialActionNotAllowed,
+ Status: http.StatusForbidden,
+ Msg: "Free trial user can't list invites",
+ })
return
}
@@ -196,8 +214,11 @@ func ListAllInvitesHandler(w http.ResponseWriter, r *http.Request) {
}
if auth.User.IsTrial {
- log.Println("Trial user can't list invites")
- http.Error(w, "Trial user can't list invites", http.StatusForbidden)
+ writeApiError(w, shared.ApiError{
+ Type: shared.ApiErrorTypeTrialActionNotAllowed,
+ Status: http.StatusForbidden,
+ Msg: "Free trial user can't list invites",
+ })
return
}
@@ -234,8 +255,11 @@ func DeleteInviteHandler(w http.ResponseWriter, r *http.Request) {
}
if auth.User.IsTrial {
- log.Println("Trial user can't delete invites")
- http.Error(w, "Trial user can't delete invites", http.StatusForbidden)
+ writeApiError(w, shared.ApiError{
+ Type: shared.ApiErrorTypeTrialActionNotAllowed,
+ Status: http.StatusForbidden,
+ Msg: "Free trial user can't delete invites",
+ })
return
}
@@ -256,6 +280,14 @@ func DeleteInviteHandler(w http.ResponseWriter, r *http.Request) {
return
}
+ // ensure current user can remove target invite
+ if !(auth.HasPermission(strings.Join([]string{"remove_user", invite.OrgRoleId}, "|")) ||
+ (auth.User.Id == invite.InviterId && auth.HasPermission(strings.Join([]string{"invite_user", invite.OrgRoleId}, "|")))) {
+ log.Printf("User does not have permission to remove invite with role: %v\n", invite.OrgRoleId)
+ http.Error(w, "User does not have permission to remove invite with role: "+invite.OrgRoleId, http.StatusForbidden)
+ return
+ }
+
err = db.DeleteInvite(inviteId, nil)
if err != nil {
diff --git a/server/handlers/orgs.go b/server/handlers/orgs.go
index a96a2257..aa591291 100644
--- a/server/handlers/orgs.go
+++ b/server/handlers/orgs.go
@@ -53,8 +53,11 @@ func CreateOrgHandler(w http.ResponseWriter, r *http.Request) {
}
if auth.User.IsTrial {
- log.Println("Trial user cannot create org")
- http.Error(w, "Trial user cannot create org", http.StatusForbidden)
+ writeApiError(w, shared.ApiError{
+ Type: shared.ApiErrorTypeTrialActionNotAllowed,
+ Status: http.StatusForbidden,
+ Msg: "Free trial user can't create org",
+ })
return
}
@@ -147,3 +150,52 @@ func CreateOrgHandler(w http.ResponseWriter, r *http.Request) {
w.Write(bytes)
}
+
+func ListOrgRolesHandler(w http.ResponseWriter, r *http.Request) {
+ log.Println("Received request for ListOrgRolesHandler")
+
+ auth := authenticate(w, r, true)
+ if auth == nil {
+ return
+ }
+
+ if auth.User.IsTrial {
+ writeApiError(w, shared.ApiError{
+ Type: shared.ApiErrorTypeTrialActionNotAllowed,
+ Status: http.StatusForbidden,
+ Msg: "Free trial user can't list org roles",
+ })
+ return
+ }
+
+ if !auth.HasPermission("list_org_roles") {
+ log.Println("User cannot list org roles")
+ http.Error(w, "User cannot list org roles", http.StatusForbidden)
+ return
+ }
+
+ roles, err := db.ListOrgRoles(auth.OrgId)
+
+ if err != nil {
+ log.Printf("Error listing org roles: %v\n", err)
+ http.Error(w, "Error listing org roles: "+err.Error(), http.StatusInternalServerError)
+ return
+ }
+
+ var apiRoles []*shared.OrgRole
+ for _, role := range roles {
+ apiRoles = append(apiRoles, role.ToApi())
+ }
+
+ bytes, err := json.Marshal(apiRoles)
+
+ if err != nil {
+ log.Printf("Error marshalling response: %v\n", err)
+ http.Error(w, "Error marshalling response: "+err.Error(), http.StatusInternalServerError)
+ return
+ }
+
+ log.Println("Successfully listed org roles")
+
+ w.Write(bytes)
+}
diff --git a/server/handlers/plans_changes.go b/server/handlers/plans_changes.go
index 9ced53d8..2b076c9a 100644
--- a/server/handlers/plans_changes.go
+++ b/server/handlers/plans_changes.go
@@ -17,14 +17,13 @@ func CurrentPlanHandler(w http.ResponseWriter, r *http.Request) {
if auth == nil {
return
}
- currentUserId := auth.User.Id
vars := mux.Vars(r)
planId := vars["planId"]
log.Println("planId: ", planId)
- if authorizePlan(w, planId, currentUserId, auth.OrgId) == nil {
+ if authorizePlan(w, planId, auth) == nil {
return
}
@@ -68,13 +67,12 @@ func ApplyPlanHandler(w http.ResponseWriter, r *http.Request) {
if auth == nil {
return
}
- currentUserId := auth.User.Id
vars := mux.Vars(r)
planId := vars["planId"]
log.Println("planId: ", planId)
- if authorizePlan(w, planId, currentUserId, auth.OrgId) == nil {
+ if authorizePlan(w, planId, auth) == nil {
return
}
@@ -96,13 +94,12 @@ func RejectAllChangesHandler(w http.ResponseWriter, r *http.Request) {
if auth == nil {
return
}
- currentUserId := auth.User.Id
vars := mux.Vars(r)
planId := vars["planId"]
log.Println("planId: ", planId)
- if authorizePlan(w, planId, currentUserId, auth.OrgId) == nil {
+ if authorizePlan(w, planId, auth) == nil {
return
}
@@ -124,7 +121,6 @@ func RejectResultHandler(w http.ResponseWriter, r *http.Request) {
if auth == nil {
return
}
- currentUserId := auth.User.Id
vars := mux.Vars(r)
planId := vars["planId"]
@@ -132,7 +128,7 @@ func RejectResultHandler(w http.ResponseWriter, r *http.Request) {
log.Println("planId: ", planId, "resultId: ", resultId)
- if authorizePlan(w, planId, currentUserId, auth.OrgId) == nil {
+ if authorizePlan(w, planId, auth) == nil {
return
}
@@ -154,7 +150,6 @@ func RejectReplacementHandler(w http.ResponseWriter, r *http.Request) {
if auth == nil {
return
}
- currentUserId := auth.User.Id
vars := mux.Vars(r)
planId := vars["planId"]
@@ -163,7 +158,7 @@ func RejectReplacementHandler(w http.ResponseWriter, r *http.Request) {
log.Println("planId: ", planId, "resultId: ", resultId, "replacementId: ", replacementId)
- if authorizePlan(w, planId, currentUserId, auth.OrgId) == nil {
+ if authorizePlan(w, planId, auth) == nil {
return
}
@@ -183,7 +178,6 @@ func ArchivePlanHandler(w http.ResponseWriter, r *http.Request) {
if auth == nil {
return
}
- currentUserId := auth.User.Id
log.Println("Received request for ArchivePlanHandler")
@@ -191,19 +185,12 @@ func ArchivePlanHandler(w http.ResponseWriter, r *http.Request) {
planId := vars["planId"]
log.Println("planId: ", planId)
- plan := authorizePlan(w, planId, currentUserId, auth.OrgId)
+ plan := authorizePlanArchive(w, planId, auth)
if plan == nil {
return
}
- // apart from authorization, only the plan owner can archive a plan
- if plan.OwnerId != currentUserId {
- log.Println("Only the plan owner can archive a plan")
- http.Error(w, "Only the plan owner can archive a plan", http.StatusForbidden)
- return
- }
-
if plan.ArchivedAt != nil {
log.Println("Plan already archived")
http.Error(w, "Plan already archived", http.StatusBadRequest)
diff --git a/server/handlers/plans_context.go b/server/handlers/plans_context.go
index ab7c2f34..13a0ffda 100644
--- a/server/handlers/plans_context.go
+++ b/server/handlers/plans_context.go
@@ -24,13 +24,12 @@ func ListContextHandler(w http.ResponseWriter, r *http.Request) {
if auth == nil {
return
}
- currentUserId := auth.User.Id
vars := mux.Vars(r)
planId := vars["planId"]
log.Println("planId: ", planId)
- if authorizePlan(w, planId, currentUserId, auth.OrgId) == nil {
+ if authorizePlan(w, planId, auth) == nil {
return
}
@@ -72,7 +71,7 @@ func LoadContextHandler(w http.ResponseWriter, r *http.Request) {
planId := vars["planId"]
log.Println("planId: ", planId)
- if authorizePlan(w, planId, currentUserId, auth.OrgId) == nil {
+ if authorizePlan(w, planId, auth) == nil {
return
}
@@ -235,13 +234,12 @@ func UpdateContextHandler(w http.ResponseWriter, r *http.Request) {
if auth == nil {
return
}
- currentUserId := auth.User.Id
vars := mux.Vars(r)
planId := vars["planId"]
log.Println("planId: ", planId)
- if authorizePlan(w, planId, currentUserId, auth.OrgId) == nil {
+ if authorizePlan(w, planId, auth) == nil {
return
}
@@ -433,13 +431,12 @@ func DeleteContextHandler(w http.ResponseWriter, r *http.Request) {
if auth == nil {
return
}
- currentUserId := auth.User.Id
vars := mux.Vars(r)
planId := vars["planId"]
log.Println("planId: ", planId)
- plan := authorizePlan(w, planId, currentUserId, auth.OrgId)
+ plan := authorizePlan(w, planId, auth)
if plan == nil {
return
diff --git a/server/handlers/plans_convo.go b/server/handlers/plans_convo.go
index 5810f1bd..78786bdb 100644
--- a/server/handlers/plans_convo.go
+++ b/server/handlers/plans_convo.go
@@ -13,14 +13,13 @@ func ListConvoHandler(w http.ResponseWriter, r *http.Request) {
if auth == nil {
return
}
- currentUserId := auth.User.Id
vars := mux.Vars(r)
planId := vars["planId"]
log.Println("planId: ", planId)
- if authorizePlan(w, planId, currentUserId, auth.OrgId) == nil {
+ if authorizePlan(w, planId, auth) == nil {
return
}
diff --git a/server/handlers/plans_crud.go b/server/handlers/plans_crud.go
index 112cfef2..ca61926f 100644
--- a/server/handlers/plans_crud.go
+++ b/server/handlers/plans_crud.go
@@ -22,19 +22,24 @@ func CreatePlanHandler(w http.ResponseWriter, r *http.Request) {
if auth == nil {
return
}
- currentUserId := auth.User.Id
+
+ if !auth.HasPermission("create_plan") {
+ log.Println("User does not have permission to create a plan")
+ http.Error(w, "User does not have permission to create a plan", http.StatusForbidden)
+ return
+ }
vars := mux.Vars(r)
projectId := vars["projectId"]
log.Println("projectId: ", projectId)
- if !authorizeProject(w, projectId, currentUserId, auth.OrgId) {
+ if !authorizeProject(w, projectId, auth) {
return
}
if os.Getenv("IS_CLOUD") != "" {
- user, err := db.GetUser(currentUserId)
+ user, err := db.GetUser(auth.User.Id)
if err != nil {
log.Printf("Error getting user: %v\n", err)
@@ -44,7 +49,7 @@ func CreatePlanHandler(w http.ResponseWriter, r *http.Request) {
if user.IsTrial {
if user.NumNonDraftPlans >= TrialMaxPlans {
- writeApiError(w, shared.ApiErr{
+ writeApiError(w, shared.ApiError{
Type: shared.ApiErrorTypeTrialPlansExceeded,
Status: http.StatusForbidden,
Msg: "User has reached max number of free trial plans",
@@ -80,7 +85,7 @@ func CreatePlanHandler(w http.ResponseWriter, r *http.Request) {
if name == "draft" {
// delete any existing draft plans
- err = db.DeleteDraftPlans(auth.OrgId, projectId, currentUserId)
+ err = db.DeleteDraftPlans(auth.OrgId, projectId, auth.User.Id)
if err != nil {
log.Printf("Error deleting draft plans: %v\n", err)
@@ -92,7 +97,7 @@ func CreatePlanHandler(w http.ResponseWriter, r *http.Request) {
originalName := name
for {
var count int
- err := db.Conn.Get(&count, "SELECT COUNT(*) FROM plans WHERE project_id = $1 AND owner_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.User.Id, name)
if err != nil {
log.Printf("Error checking if plan exists: %v\n", err)
@@ -109,7 +114,7 @@ func CreatePlanHandler(w http.ResponseWriter, r *http.Request) {
}
}
- plan, err := db.CreatePlan(auth.OrgId, projectId, currentUserId, name)
+ plan, err := db.CreatePlan(auth.OrgId, projectId, auth.User.Id, name)
if err != nil {
log.Printf("Error creating plan: %v\n", err)
@@ -142,14 +147,13 @@ func GetPlanHandler(w http.ResponseWriter, r *http.Request) {
if auth == nil {
return
}
- currentUserId := auth.User.Id
vars := mux.Vars(r)
planId := vars["planId"]
log.Println("planId: ", planId)
- plan := authorizePlan(w, planId, currentUserId, auth.OrgId)
+ plan := authorizePlan(w, planId, auth)
if plan == nil {
return
@@ -173,20 +177,19 @@ func DeletePlanHandler(w http.ResponseWriter, r *http.Request) {
if auth == nil {
return
}
- currentUserId := auth.User.Id
vars := mux.Vars(r)
planId := vars["planId"]
log.Println("planId: ", planId)
- plan := authorizePlan(w, planId, currentUserId, auth.OrgId)
+ plan := authorizePlanDelete(w, planId, auth)
if plan == nil {
return
}
- if plan.OwnerId != currentUserId {
+ if plan.OwnerId != auth.User.Id {
log.Println("Only the plan owner can delete a plan")
http.Error(w, "Only the plan owner can delete a plan", http.StatusForbidden)
return
@@ -231,18 +234,17 @@ func DeleteAllPlansHandler(w http.ResponseWriter, r *http.Request) {
if auth == nil {
return
}
- currentUserId := auth.User.Id
vars := mux.Vars(r)
projectId := vars["projectId"]
log.Println("projectId: ", projectId)
- if !authorizeProject(w, projectId, currentUserId, auth.OrgId) {
+ if !authorizeProject(w, projectId, auth) {
return
}
- err := db.DeleteOwnerPlans(auth.OrgId, projectId, currentUserId)
+ err := db.DeleteOwnerPlans(auth.OrgId, projectId, auth.User.Id)
if err != nil {
log.Printf("Error deleting plans: %v\n", err)
@@ -259,18 +261,17 @@ func ListPlansHandler(w http.ResponseWriter, r *http.Request) {
if auth == nil {
return
}
- currentUserId := auth.User.Id
vars := mux.Vars(r)
projectId := vars["projectId"]
log.Println("projectId: ", projectId)
- if !authorizeProject(w, projectId, currentUserId, auth.OrgId) {
+ if !authorizeProject(w, projectId, auth) {
return
}
- plans, err := db.ListOwnedPlans(projectId, currentUserId, false, "")
+ plans, err := db.ListOwnedPlans(projectId, auth.User.Id, false, "")
if err != nil {
log.Printf("Error listing plans: %v\n", err)
@@ -296,14 +297,13 @@ func ListArchivedPlansHandler(w http.ResponseWriter, r *http.Request) {
if auth == nil {
return
}
- currentUserId := auth.User.Id
vars := mux.Vars(r)
projectId := vars["projectId"]
log.Println("projectId: ", projectId)
- if !authorizeProject(w, projectId, currentUserId, auth.OrgId) {
+ if !authorizeProject(w, projectId, auth) {
return
}
@@ -333,14 +333,13 @@ func ListPlansRunningHandler(w http.ResponseWriter, r *http.Request) {
if auth == nil {
return
}
- currentUserId := auth.User.Id
vars := mux.Vars(r)
projectId := vars["projectId"]
log.Println("projectId: ", projectId)
- if !authorizeProject(w, projectId, currentUserId, auth.OrgId) {
+ if !authorizeProject(w, projectId, auth) {
return
}
diff --git a/server/handlers/plans_exec.go b/server/handlers/plans_exec.go
index 2fa41c86..02960a70 100644
--- a/server/handlers/plans_exec.go
+++ b/server/handlers/plans_exec.go
@@ -22,19 +22,24 @@ func TellPlanHandler(w http.ResponseWriter, r *http.Request) {
if auth == nil {
return
}
- currentUserId := auth.User.Id
vars := mux.Vars(r)
planId := vars["planId"]
log.Println("planId: ", planId)
- plan := authorizePlan(w, planId, currentUserId, auth.OrgId)
+ plan := authorizePlanUpdate(w, planId, auth)
if plan == nil {
return
}
+ if plan.OwnerId != auth.User.Id && !auth.HasPermission("update_any_plan") {
+ log.Println("User does not have permission to update plan")
+ http.Error(w, "User does not have permission to update plan", http.StatusForbidden)
+ return
+ }
+
body, err := io.ReadAll(r.Body)
if err != nil {
log.Printf("Error reading request body: %v\n", err)
@@ -54,7 +59,7 @@ func TellPlanHandler(w http.ResponseWriter, r *http.Request) {
}
if os.Getenv("IS_CLOUD") != "" {
- user, err := db.GetUser(currentUserId)
+ user, err := db.GetUser(auth.User.Id)
if err != nil {
log.Printf("Error getting user: %v\n", err)
@@ -64,7 +69,7 @@ func TellPlanHandler(w http.ResponseWriter, r *http.Request) {
if user.IsTrial {
if plan.TotalMessages >= TrialMaxMessages {
- writeApiError(w, shared.ApiErr{
+ writeApiError(w, shared.ApiError{
Type: shared.ApiErrorTypeTrialMessagesExceeded,
Status: http.StatusForbidden,
Msg: "Free trial message limit exceeded",
@@ -77,7 +82,7 @@ func TellPlanHandler(w http.ResponseWriter, r *http.Request) {
}
}
- err = model.Tell(plan, currentUserId, auth.OrgId, &requestBody)
+ err = model.Tell(plan, auth, &requestBody)
if err != nil {
log.Printf("Error telling plan: %v\n", err)
@@ -102,14 +107,13 @@ func BuildPlanHandler(w http.ResponseWriter, r *http.Request) {
if auth == nil {
return
}
- currentUserId := auth.User.Id
vars := mux.Vars(r)
planId := vars["planId"]
log.Println("planId: ", planId)
- if authorizePlan(w, planId, currentUserId, auth.OrgId) == nil {
+ if authorizePlan(w, planId, auth) == nil {
return
}
@@ -121,14 +125,13 @@ func ConnectPlanHandler(w http.ResponseWriter, r *http.Request) {
if auth == nil {
return
}
- currentUserId := auth.User.Id
vars := mux.Vars(r)
planId := vars["planId"]
log.Println("planId: ", planId)
- if authorizePlan(w, planId, currentUserId, auth.OrgId) == nil {
+ if authorizePlan(w, planId, auth) == nil {
return
}
@@ -140,14 +143,13 @@ func StopPlanHandler(w http.ResponseWriter, r *http.Request) {
if auth == nil {
return
}
- currentUserId := auth.User.Id
vars := mux.Vars(r)
planId := vars["planId"]
log.Println("planId: ", planId)
- if authorizePlan(w, planId, currentUserId, auth.OrgId) == nil {
+ if authorizePlan(w, planId, auth) == nil {
return
}
diff --git a/server/handlers/plans_versions.go b/server/handlers/plans_versions.go
index 8e36ad31..653a03bf 100644
--- a/server/handlers/plans_versions.go
+++ b/server/handlers/plans_versions.go
@@ -18,14 +18,13 @@ func ListLogsHandler(w http.ResponseWriter, r *http.Request) {
if auth == nil {
return
}
- currentUserId := auth.User.Id
vars := mux.Vars(r)
planId := vars["planId"]
log.Println("planId: ", planId)
- if authorizePlan(w, planId, currentUserId, auth.OrgId) == nil {
+ if authorizePlan(w, planId, auth) == nil {
return
}
@@ -62,14 +61,13 @@ func RewindPlanHandler(w http.ResponseWriter, r *http.Request) {
if auth == nil {
return
}
- currentUserId := auth.User.Id
vars := mux.Vars(r)
planId := vars["planId"]
log.Println("planId: ", planId)
- if authorizePlan(w, planId, currentUserId, auth.OrgId) == nil {
+ if authorizePlan(w, planId, auth) == nil {
return
}
diff --git a/server/handlers/projects.go b/server/handlers/projects.go
index bdb34594..2396f8b9 100644
--- a/server/handlers/projects.go
+++ b/server/handlers/projects.go
@@ -18,7 +18,6 @@ func CreateProjectHandler(w http.ResponseWriter, r *http.Request) {
if auth == nil {
return
}
- currentUserId := auth.User.Id
// read the request body
body, err := io.ReadAll(r.Body)
@@ -70,7 +69,7 @@ func CreateProjectHandler(w http.ResponseWriter, r *http.Request) {
return
}
- _, err = tx.Exec("INSERT INTO users_projects (user_id, org_id, project_id) VALUES ($1, $2, $3)", currentUserId, auth.OrgId, projectId)
+ _, err = tx.Exec("INSERT INTO users_projects (user_id, org_id, project_id) VALUES ($1, $2, $3)", auth, projectId)
if err != nil {
log.Printf("Error adding owner to project: %v\n", err)
@@ -109,9 +108,8 @@ func ListProjectsHandler(w http.ResponseWriter, r *http.Request) {
if auth == nil {
return
}
- currentUserId := auth.User.Id
- rows, err := db.Conn.Query("SELECT project.id, project.name FROM users_projects INNER JOIN project ON users_projects.project_id = project.id WHERE users_projects.user_id = $1 AND users_projects.org_id = $2", currentUserId, auth.OrgId)
+ rows, err := db.Conn.Query("SELECT project.id, project.name FROM users_projects INNER JOIN project ON users_projects.project_id = project.id WHERE users_projects.user_id = $1 AND users_projects.org_id = $2", auth)
if err != nil {
log.Printf("Error listing projects: %v\n", err)
@@ -148,14 +146,13 @@ func ProjectSetPlanHandler(w http.ResponseWriter, r *http.Request) {
if auth == nil {
return
}
- currentUserId := auth.User.Id
vars := mux.Vars(r)
projectId := vars["projectId"]
log.Println("projectId: ", projectId)
- if !authorizeProject(w, projectId, currentUserId, auth.OrgId) {
+ if !authorizeProject(w, projectId, auth) {
return
}
@@ -198,14 +195,13 @@ func RenameProjectHandler(w http.ResponseWriter, r *http.Request) {
if auth == nil {
return
}
- currentUserId := auth.User.Id
vars := mux.Vars(r)
projectId := vars["projectId"]
log.Println("projectId: ", projectId)
- if !authorizeProject(w, projectId, currentUserId, auth.OrgId) {
+ if !authorizeProjectRename(w, projectId, auth) {
return
}
diff --git a/server/handlers/sessions.go b/server/handlers/sessions.go
index 95d6be07..737f3f6b 100644
--- a/server/handlers/sessions.go
+++ b/server/handlers/sessions.go
@@ -98,14 +98,7 @@ func SignInHandler(w http.ResponseWriter, r *http.Request) {
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
- }
+ req.Email = strings.ToLower(req.Email)
user, err := db.GetUserByEmail(req.Email)
@@ -121,6 +114,20 @@ func SignInHandler(w http.ResponseWriter, r *http.Request) {
return
}
+ if user != nil && user.IsTrial {
+ log.Printf("Trial user can't sign in: %v\n", req.Email)
+ http.Error(w, "Trial user can't sign in", http.StatusForbidden)
+ 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 {
@@ -141,7 +148,7 @@ func SignInHandler(w http.ResponseWriter, r *http.Request) {
}()
// create auth token
- token, authTokenId, err := db.CreateAuthToken(user.Id, tx)
+ token, authTokenId, err := db.CreateAuthToken(user.Id, false, tx)
if err != nil {
log.Printf("Error creating auth token: %v\n", err)
diff --git a/server/handlers/users.go b/server/handlers/users.go
index 149db53f..f8205367 100644
--- a/server/handlers/users.go
+++ b/server/handlers/users.go
@@ -5,8 +5,10 @@ import (
"log"
"net/http"
"plandex-server/db"
+ "strings"
"github.com/gorilla/mux"
+ "github.com/plandex/plandex/shared"
)
func ListUsersHandler(w http.ResponseWriter, r *http.Request) {
@@ -17,8 +19,11 @@ func ListUsersHandler(w http.ResponseWriter, r *http.Request) {
}
if auth.User.IsTrial {
- log.Println("Trial user cannot list users")
- http.Error(w, "Trial user cannot list users", http.StatusForbidden)
+ writeApiError(w, shared.ApiError{
+ Type: shared.ApiErrorTypeTrialActionNotAllowed,
+ Status: http.StatusForbidden,
+ Msg: "Free trial user can't list users",
+ })
return
}
@@ -49,14 +54,32 @@ func DeleteOrgUserHandler(w http.ResponseWriter, r *http.Request) {
}
if auth.User.IsTrial {
- log.Println("Trial user cannot delete users")
- http.Error(w, "Trial user cannot delete users", http.StatusForbidden)
+ writeApiError(w, shared.ApiError{
+ Type: shared.ApiErrorTypeTrialActionNotAllowed,
+ Status: http.StatusForbidden,
+ Msg: "Free trial user can't delete users",
+ })
return
}
vars := mux.Vars(r)
userId := vars["userId"]
+ user, err := db.GetUser(userId)
+
+ if err != nil {
+ log.Printf("Error getting user: %v\n", err)
+ http.Error(w, "Error getting user: "+err.Error(), http.StatusInternalServerError)
+ return
+ }
+
+ // ensure current user can invite target user
+ if !auth.HasPermission(strings.Join([]string{"remove_user", user.OrgRoleId}, "|")) {
+ log.Printf("User does not have permission to invite user with role: %v\n", user.OrgRoleId)
+ http.Error(w, "User does not have permission to invite user with role: "+user.OrgRoleId, http.StatusForbidden)
+ return
+ }
+
// verify user is org member
isMember, err := db.ValidateOrgMembership(userId, auth.OrgId)
diff --git a/server/migrations/2023120500_init.up.sql b/server/migrations/2023120500_init.up.sql
index 38e7822b..b89aa949 100644
--- a/server/migrations/2023120500_init.up.sql
+++ b/server/migrations/2023120500_init.up.sql
@@ -70,10 +70,11 @@ 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,
+ is_trial BOOLEAN NOT NULL DEFAULT FALSE,
created_at TIMESTAMP NOT NULL DEFAULT NOW(),
deleted_at TIMESTAMP
);
-ALTER TABLE auth_tokens ADD UNIQUE (token_hash);
+CREATE UNIQUE INDEX auth_tokens_idx ON auth_tokens(token_hash);
CREATE TABLE IF NOT EXISTS email_verifications (
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
@@ -86,7 +87,7 @@ CREATE TABLE IF NOT EXISTS email_verifications (
);
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 UNIQUE INDEX email_verifications_idx ON email_verifications(pin_hash, email, created_at DESC);
CREATE TABLE IF NOT EXISTS projects (
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
@@ -154,4 +155,4 @@ CREATE TABLE IF NOT EXISTS plan_builds (
created_at TIMESTAMP NOT NULL DEFAULT NOW(),
updated_at TIMESTAMP NOT NULL DEFAULT NOW()
);
-CREATE TRIGGER update_plan_builds_modtime BEFORE UPDATE ON plan_builds FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();
+CREATE TRIGGER update_plan_builds_modtime BEFORE UPDATE ON plan_builds FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();
\ No newline at end of file
diff --git a/server/migrations/2024011700_rbac.down.sql b/server/migrations/2024011700_rbac.down.sql
new file mode 100644
index 00000000..4bcf2173
--- /dev/null
+++ b/server/migrations/2024011700_rbac.down.sql
@@ -0,0 +1,8 @@
+ALTER TABLE orgs_users DROP COLUMN org_role_id;
+ALTER TABLE invites DROP COLUMN org_role_id;
+
+DROP TABLE IF EXISTS org_roles_permissions;
+DROP TABLE IF EXISTS permissions;
+DROP TABLE IF EXISTS org_roles;
+
+
diff --git a/server/migrations/2024011700_rbac.up.sql b/server/migrations/2024011700_rbac.up.sql
new file mode 100644
index 00000000..a51f7a62
--- /dev/null
+++ b/server/migrations/2024011700_rbac.up.sql
@@ -0,0 +1,133 @@
+
+CREATE TABLE IF NOT EXISTS org_roles (
+ id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
+ org_id UUID REFERENCES orgs(id) ON DELETE CASCADE,
+ name VARCHAR(255) NOT NULL,
+ label VARCHAR(255) NOT NULL,
+ description TEXT NOT NULL,
+ created_at TIMESTAMP NOT NULL DEFAULT NOW(),
+ updated_at TIMESTAMP NOT NULL DEFAULT NOW()
+);
+CREATE TRIGGER update_org_roles_modtime BEFORE UPDATE ON org_roles FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();
+
+CREATE UNIQUE INDEX org_roles_org_idx ON org_roles(org_id, name);
+
+ALTER TABLE orgs_users ADD COLUMN org_role_id UUID NOT NULL REFERENCES org_roles(id) ON DELETE RESTRICT;
+CREATE INDEX orgs_users_org_role_idx ON orgs_users(org_id, org_role_id);
+
+ALTER TABLE invites ADD COLUMN org_role_id UUID NOT NULL REFERENCES org_roles(id) ON DELETE RESTRICT;
+CREATE INDEX invites_org_role_idx ON invites(org_id, org_role_id);
+
+CREATE TABLE IF NOT EXISTS permissions (
+ id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
+ name VARCHAR(255) NOT NULL,
+ description TEXT NOT NULL,
+ resource_id UUID,
+ created_at TIMESTAMP NOT NULL DEFAULT NOW()
+);
+
+CREATE TABLE IF NOT EXISTS org_roles_permissions (
+ id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
+ org_role_id UUID NOT NULL REFERENCES org_roles(id) ON DELETE CASCADE,
+ permission_id UUID NOT NULL REFERENCES permissions(id) ON DELETE CASCADE,
+ created_at TIMESTAMP NOT NULL DEFAULT NOW()
+);
+
+INSERT INTO org_roles (name, label, description) VALUES
+ ('owner', 'Owner', 'Can read and update any plan, invite other owners/admins/members, manage email domain auth, manage billing, read audit logs, delete the org'),
+ ('billing_admin', 'Billing Admin', 'Can manage billing'),
+ ('admin', 'Admin', 'Can read and update any plan, invite other admins/members'),
+ ('member', 'Member', 'Can read and update their own plans or plans shared with them');
+
+DO $$
+DECLARE
+ owner_org_role_id UUID;
+ billing_admin_org_role_id UUID;
+ admin_org_role_id UUID;
+ member_org_role_id UUID;
+BEGIN
+ SELECT id INTO owner_org_role_id FROM org_roles WHERE org_id IS NULL AND name = 'owner';
+ SELECT id INTO billing_admin_org_role_id FROM org_roles WHERE org_id IS NULL AND name = 'billing_admin';
+ SELECT id INTO admin_org_role_id FROM org_roles WHERE org_id IS NULL AND name = 'admin';
+ SELECT id INTO member_org_role_id FROM org_roles WHERE org_id IS NULL AND name = 'member';
+
+ INSERT INTO permissions (name, description, resource_id) VALUES
+ ('delete_org', 'Delete an org', NULL),
+ ('manage_email_domain_auth', 'Configure whether orgs_users from the org''s email domain are auto-admitted to org', NULL),
+ ('manage_billing', 'Manage an org''s billing', NULL),
+
+ ('invite_user', 'Invite owners to an org', owner_org_role_id),
+ ('invite_user', 'Invite admins to an org', admin_org_role_id),
+ ('invite_user', 'Invite billing admins to an org', billing_admin_org_role_id),
+ ('invite_user', 'Invite members to an org', member_org_role_id),
+
+ ('remove_user', 'Remove owners from an org', owner_org_role_id),
+ ('remove_user', 'Remove admins from an org', admin_org_role_id),
+ ('remove_user', 'Remove billing admins from an org', billing_admin_org_role_id),
+ ('remove_user', 'Remove members from an org', member_org_role_id),
+
+ ('set_user_role', 'Update an owner''s role in an org', owner_org_role_id),
+ ('set_user_role', 'Update an admin''s role in an org', admin_org_role_id),
+ ('set_user_role', 'Update a billing admin''s role in an org', billing_admin_org_role_id),
+ ('set_user_role', 'Update a member''s role in an org', member_org_role_id),
+
+ ('list_org_roles', 'List org roles', NULL),
+
+ ('create_project', 'Create a project', NULL),
+ ('rename_any_project', 'Rename a project', NULL),
+ ('delete_any_project', 'Delete a project', NULL),
+
+ ('create_plan', 'Create a plan', NULL),
+
+ ('manage_any_plan_shares', 'Unshare a plan any user shared', NULL),
+ ('rename_any_plan', 'Rename a plan', NULL),
+ ('delete_any_plan', 'Delete a plan', NULL),
+ ('update_any_plan', 'Update a plan', NULL),
+ ('archive_any_plan', 'Archive a plan', NULL);
+END $$;
+
+-- Insert all permissions for the 'org owner' role
+INSERT INTO org_roles_permissions (org_role_id, permission_id)
+SELECT
+ (SELECT id FROM org_roles WHERE name = 'owner') AS org_role_id,
+ p.id AS permission_id
+FROM
+ permissions p;
+
+-- Insert all permissions except specific ones and those exclusive to 'owner' or 'billing admin' for the 'org admin' role
+INSERT INTO org_roles_permissions (org_role_id, permission_id)
+SELECT
+ (SELECT id FROM org_roles WHERE name = 'admin') AS org_role_id,
+ p.id AS permission_id
+FROM
+ permissions p
+WHERE
+ p.name NOT IN ('delete_org', 'manage_email_domain_auth', 'manage_billing')
+ AND NOT EXISTS (
+ SELECT 1 FROM permissions p2
+ WHERE p2.resource_id IN (SELECT id FROM org_roles WHERE name IN ('owner', 'billing_admin'))
+ AND p2.id = p.id
+ );
+
+INSERT INTO org_roles_permissions (org_role_id, permission_id)
+SELECT
+ (SELECT id FROM org_roles WHERE name = 'billing_admin') AS org_role_id,
+ p.id AS permission_id
+FROM
+ permissions p
+WHERE
+ p.name IN (
+ 'manage_billing'
+ );
+
+INSERT INTO org_roles_permissions (org_role_id, permission_id)
+SELECT
+ (SELECT id FROM org_roles WHERE name = 'member') AS org_role_id,
+ p.id AS permission_id
+FROM
+ permissions p
+WHERE
+ p.name IN (
+ 'create_project',
+ 'create_plan'
+ );
diff --git a/server/model/plan/tell.go b/server/model/plan/tell.go
index d24ecdd2..85934faf 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(plan *db.Plan, currentUserId, currentOrgId string, req *shared.TellPlanRequest) error {
+func Tell(plan *db.Plan, auth *types.ServerAuth, req *shared.TellPlanRequest) error {
// goEnv := os.Getenv("GOENV") // Fetch the GO_ENV environment variable
// log.Println("GOENV: " + goEnv)
@@ -36,12 +36,15 @@ func Tell(plan *db.Plan, currentUserId, currentOrgId string, req *shared.TellPla
active = CreateActivePlan(planId, req.Prompt)
- go execTellPlan(plan, currentUserId, currentOrgId, req, active)
+ go execTellPlan(plan, auth, req, active)
return nil
}
-func execTellPlan(plan *db.Plan, currentUserId, currentOrgId string, req *shared.TellPlanRequest, active *types.ActivePlan) {
+func execTellPlan(plan *db.Plan, auth *types.ServerAuth, req *shared.TellPlanRequest, active *types.ActivePlan) {
+ currentUserId := auth.User.Id
+ currentOrgId := auth.OrgId
+
planId := plan.Id
err := db.SetPlanStatus(planId, shared.PlanStatusReplying, "")
if err != nil {
diff --git a/server/routes.go b/server/routes.go
index 8eecbbb0..ca553915 100644
--- a/server/routes.go
+++ b/server/routes.go
@@ -27,6 +27,7 @@ func InitRoutes() *mux.Router {
r.HandleFunc("/users", handlers.ListUsersHandler).Methods("GET")
r.HandleFunc("/orgs/users/{userId}", handlers.DeleteOrgUserHandler).Methods("DELETE")
+ r.HandleFunc("/orgs/roles", handlers.ListOrgRolesHandler).Methods("GET")
r.HandleFunc("/invites", handlers.InviteUserHandler).Methods("POST")
r.HandleFunc("/invites/pending", handlers.ListPendingInvitesHandler).Methods("GET")
diff --git a/server/types/auth.go b/server/types/auth.go
index 03772793..5b4dd530 100644
--- a/server/types/auth.go
+++ b/server/types/auth.go
@@ -3,7 +3,16 @@ package types
import "plandex-server/db"
type ServerAuth struct {
- AuthToken *db.AuthToken
- User *db.User
- OrgId string
+ AuthToken *db.AuthToken
+ User *db.User
+ OrgId string
+ Permissions map[string]bool
+}
+
+func (a *ServerAuth) HasPermission(permission string) bool {
+ if a.Permissions == nil {
+ return false
+ }
+
+ return a.Permissions[permission]
}
diff --git a/shared/auth.go b/shared/auth.go
index 2eddb129..83f5dad9 100644
--- a/shared/auth.go
+++ b/shared/auth.go
@@ -11,6 +11,7 @@ const (
ApiErrorTypeInvalidToken ApiErrorType = "invalid_token"
ApiErrorTypeTrialPlansExceeded ApiErrorType = "trial_plans_exceeded"
ApiErrorTypeTrialMessagesExceeded ApiErrorType = "trial_messages_exceeded"
+ ApiErrorTypeTrialActionNotAllowed ApiErrorType = "trial_action_not_allowed"
ApiErrorTypeOther ApiErrorType = "other"
)
diff --git a/shared/models.go b/shared/models.go
index c3ebbded..2f1b34a5 100644
--- a/shared/models.go
+++ b/shared/models.go
@@ -13,7 +13,8 @@ type User struct {
Name string `json:"name"`
Email string `json:"email"`
IsTrial bool `json:"isTrial"`
- NumNonDraftPlans int `db:"num_non_draft_plans"`
+ OrgRoleId string `json:"orgRoleId"`
+ NumNonDraftPlans int `json:"numNonDraftPlans"`
}
type Invite struct {
@@ -21,6 +22,7 @@ type Invite struct {
OrgId string `json:"orgId"`
Email string `json:"email"`
Name string `json:"name"`
+ OrgRoleId string `json:"orgRoleId"`
InviterId string `json:"inviterId"`
InviteeId string `json:"inviteeId"`
AcceptedAt *time.Time `json:"acceptedAt"`
@@ -171,3 +173,10 @@ type CurrentPlanState struct {
ContextsByPath map[string]*Context `json:"contextsByPath"`
PendingBuildDescriptions []*ConvoMessageDescription `json:"pendingBuildDescriptions"`
}
+
+type OrgRole struct {
+ Id string `json:"id"`
+ IsDefault bool `json:"isDefault"`
+ Label string `json:"label"`
+ Description string `json:"description"`
+}
diff --git a/shared/req_res.go b/shared/req_res.go
index 83437527..81298e3f 100644
--- a/shared/req_res.go
+++ b/shared/req_res.go
@@ -55,8 +55,9 @@ type CreateOrgResponse struct {
}
type InviteRequest struct {
- Email string `json:"email"`
- Name string `json:"name"`
+ Email string `json:"email"`
+ Name string `json:"name"`
+ OrgRoleId string `json:"orgRoleId"`
}
type CreateProjectRequest struct {