From 610deb50e3d4f9e3c151bfafe56716cb10ab562c Mon Sep 17 00:00:00 2001
From: bbedward
Date: Thu, 12 Nov 2026 01:34:17 +0000
Subject: [PATCH] api | web | docs: invite members to a single project
A project gets its own admin, editor and viewer role groups, created when
its first member is added. The team member and invitation endpoints take
an optional project_id, so the project Members tab reuses the team's UI.
A project member sees the team with that one project in it and nothing
else of the team. In the project they act by role, including through API
keys and MCP.
Volume metrics now authorize on the team, project or environment the
volume belongs to. They required a team role before, which refused
project members and keys limited to a project.
Deleting a project removes its role groups, its invitations and the
grants that named it.
---
apps/api/ent/client.go | 64 +++
apps/api/ent/group.go | 39 +-
apps/api/ent/group/group.go | 31 ++
apps/api/ent/group/where.go | 58 +++
apps/api/ent/group_create.go | 97 ++++
apps/api/ent/group_query.go | 80 +++-
apps/api/ent/group_update.go | 121 +++++
apps/api/ent/invitation.go | 39 +-
apps/api/ent/invitation/invitation.go | 31 ++
apps/api/ent/invitation/where.go | 58 +++
apps/api/ent/invitation_create.go | 97 ++++
apps/api/ent/invitation_query.go | 80 +++-
apps/api/ent/invitation_update.go | 121 +++++
.../20261112010707_project_members.sql | 21 +
apps/api/ent/migrate/migrations/atlas.sum | 3 +-
apps/api/ent/migrate/schema.go | 38 +-
apps/api/ent/mutation.go | 426 +++++++++++++++++-
apps/api/ent/project.go | 34 +-
apps/api/ent/project/project.go | 60 +++
apps/api/ent/project/where.go | 46 ++
apps/api/ent/project_create.go | 64 +++
apps/api/ent/project_query.go | 156 ++++++-
apps/api/ent/project_update.go | 326 ++++++++++++++
apps/api/ent/schema/group.go | 5 +-
apps/api/ent/schema/invitation.go | 8 +-
apps/api/ent/schema/project.go | 6 +
.../api/handlers/invitations/invitations.go | 4 +-
.../api/handlers/teams/invitations.go | 5 +-
.../internal/api/handlers/teams/members.go | 12 +-
apps/api/internal/api/handlers/teams/teams.go | 14 +-
apps/api/internal/models/group_response.go | 4 +-
.../internal/models/invitation_response.go | 5 +-
.../internal/models/team_member_response.go | 17 +-
.../bootstrap/bootstrap_repository_iface.go | 4 +-
.../repositories/bootstrap/create_user.go | 4 +-
.../repositories/bootstrap/superuser_group.go | 6 +-
.../repositories/project/mutations.go | 21 +
.../repositories/project/mutations_test.go | 20 +
.../internal/repositories/team/invitations.go | 24 +-
.../repositories/team/invitations_test.go | 34 +-
.../internal/repositories/team/mutations.go | 58 ++-
.../api/internal/repositories/team/queries.go | 50 +-
.../repositories/team/role_groups_test.go | 64 +++
.../team/team_repository_iface.go | 12 +-
apps/api/internal/services/group/managed.go | 13 +-
.../internal/services/metrics/metrics_test.go | 18 +
.../internal/services/metrics/read_volume.go | 32 +-
.../api/internal/services/team/invitations.go | 92 ++--
.../services/team/invitations_test.go | 44 ++
apps/api/internal/services/team/members.go | 171 +++++--
.../internal/services/team/members_test.go | 74 ++-
.../repository/team/team_repository_mock.go | 272 ++++++++++-
.../teams/members-and-permissions.mdx | 19 +-
apps/docs/content/api/index.mdx | 2 +-
.../team/settings/members/invitation-card.tsx | 6 +-
.../settings/members/invite-member-dialog.tsx | 13 +-
.../team/settings/members/member-card.tsx | 12 +-
.../settings/members/members-tab-content.tsx | 44 +-
.../members/team-members-provider.tsx | 43 +-
apps/web/src/lib/queries/teams.ts | 46 +-
apps/web/src/lib/server/client.gen.ts | 28 +-
.../$project_id/settings/members/index.tsx | 16 +-
apps/web/src/routes/invite/$token.tsx | 5 +-
63 files changed, 3148 insertions(+), 269 deletions(-)
create mode 100644 apps/api/ent/migrate/migrations/20261112010707_project_members.sql
diff --git a/apps/api/ent/client.go b/apps/api/ent/client.go
index c23f480b7..0a2bbb433 100644
--- a/apps/api/ent/client.go
+++ b/apps/api/ent/client.go
@@ -1572,6 +1572,22 @@ func (c *GroupClient) QueryTeam(_m *Group) *TeamQuery {
return query
}
+// QueryProject queries the project edge of a Group.
+func (c *GroupClient) QueryProject(_m *Group) *ProjectQuery {
+ query := (&ProjectClient{config: c.config}).Query()
+ query.path = func(context.Context) (fromV *sql.Selector, _ error) {
+ id := _m.ID
+ step := sqlgraph.NewStep(
+ sqlgraph.From(group.Table, group.FieldID, id),
+ sqlgraph.To(project.Table, project.FieldID),
+ sqlgraph.Edge(sqlgraph.M2O, true, group.ProjectTable, group.ProjectColumn),
+ )
+ fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step)
+ return fromV, nil
+ }
+ return query
+}
+
// Hooks returns the client hooks.
func (c *GroupClient) Hooks() []Hook {
return c.hooks.Group
@@ -1721,6 +1737,22 @@ func (c *InvitationClient) QueryTeam(_m *Invitation) *TeamQuery {
return query
}
+// QueryProject queries the project edge of a Invitation.
+func (c *InvitationClient) QueryProject(_m *Invitation) *ProjectQuery {
+ query := (&ProjectClient{config: c.config}).Query()
+ query.path = func(context.Context) (fromV *sql.Selector, _ error) {
+ id := _m.ID
+ step := sqlgraph.NewStep(
+ sqlgraph.From(invitation.Table, invitation.FieldID, id),
+ sqlgraph.To(project.Table, project.FieldID),
+ sqlgraph.Edge(sqlgraph.M2O, true, invitation.ProjectTable, invitation.ProjectColumn),
+ )
+ fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step)
+ return fromV, nil
+ }
+ return query
+}
+
// QueryInviter queries the inviter edge of a Invitation.
func (c *InvitationClient) QueryInviter(_m *Invitation) *UserQuery {
query := (&UserClient{config: c.config}).Query()
@@ -3259,6 +3291,38 @@ func (c *ProjectClient) QueryProjectWebhooks(_m *Project) *WebhookQuery {
return query
}
+// QueryRoleGroups queries the role_groups edge of a Project.
+func (c *ProjectClient) QueryRoleGroups(_m *Project) *GroupQuery {
+ query := (&GroupClient{config: c.config}).Query()
+ query.path = func(context.Context) (fromV *sql.Selector, _ error) {
+ id := _m.ID
+ step := sqlgraph.NewStep(
+ sqlgraph.From(project.Table, project.FieldID, id),
+ sqlgraph.To(group.Table, group.FieldID),
+ sqlgraph.Edge(sqlgraph.O2M, false, project.RoleGroupsTable, project.RoleGroupsColumn),
+ )
+ fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step)
+ return fromV, nil
+ }
+ return query
+}
+
+// QueryInvitations queries the invitations edge of a Project.
+func (c *ProjectClient) QueryInvitations(_m *Project) *InvitationQuery {
+ query := (&InvitationClient{config: c.config}).Query()
+ query.path = func(context.Context) (fromV *sql.Selector, _ error) {
+ id := _m.ID
+ step := sqlgraph.NewStep(
+ sqlgraph.From(project.Table, project.FieldID, id),
+ sqlgraph.To(invitation.Table, invitation.FieldID),
+ sqlgraph.Edge(sqlgraph.O2M, false, project.InvitationsTable, project.InvitationsColumn),
+ )
+ fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step)
+ return fromV, nil
+ }
+ return query
+}
+
// Hooks returns the client hooks.
func (c *ProjectClient) Hooks() []Hook {
return c.hooks.Project
diff --git a/apps/api/ent/group.go b/apps/api/ent/group.go
index 061616c68..f94cbdd90 100644
--- a/apps/api/ent/group.go
+++ b/apps/api/ent/group.go
@@ -11,6 +11,7 @@ import (
"entgo.io/ent/dialect/sql"
"github.com/google/uuid"
"github.com/unbindapp/unbind-api/ent/group"
+ "github.com/unbindapp/unbind-api/ent/project"
"github.com/unbindapp/unbind-api/ent/schema"
"github.com/unbindapp/unbind-api/ent/team"
)
@@ -33,7 +34,9 @@ type Group struct {
K8sRoleName *string `json:"k8s_role_name,omitempty"`
// Set on a role group owned by a team
TeamID *uuid.UUID `json:"team_id,omitempty"`
- // The one role a team role group grants on its team
+ // Set on a role group owned by a project
+ ProjectID *uuid.UUID `json:"project_id,omitempty"`
+ // The one role a role group grants on its team or project
Role *schema.PermittedAction `json:"role,omitempty"`
// Edges holds the relations/edges for other nodes in the graph.
// The values are being populated by the GroupQuery when eager-loading is set.
@@ -49,9 +52,11 @@ type GroupEdges struct {
Permissions []*Permission `json:"permissions,omitempty"`
// Team holds the value of the team edge.
Team *Team `json:"team,omitempty"`
+ // Project holds the value of the project edge.
+ Project *Project `json:"project,omitempty"`
// loadedTypes holds the information for reporting if a
// type was loaded (or requested) in eager-loading or not.
- loadedTypes [3]bool
+ loadedTypes [4]bool
}
// UsersOrErr returns the Users value or an error if the edge
@@ -83,12 +88,23 @@ func (e GroupEdges) TeamOrErr() (*Team, error) {
return nil, &NotLoadedError{edge: "team"}
}
+// ProjectOrErr returns the Project value or an error if the edge
+// was not loaded in eager-loading, or loaded but was not found.
+func (e GroupEdges) ProjectOrErr() (*Project, error) {
+ if e.Project != nil {
+ return e.Project, nil
+ } else if e.loadedTypes[3] {
+ return nil, &NotFoundError{label: project.Label}
+ }
+ return nil, &NotLoadedError{edge: "project"}
+}
+
// scanValues returns the types for scanning values from sql.Rows.
func (*Group) scanValues(columns []string) ([]any, error) {
values := make([]any, len(columns))
for i := range columns {
switch columns[i] {
- case group.FieldTeamID:
+ case group.FieldTeamID, group.FieldProjectID:
values[i] = &sql.NullScanner{S: new(uuid.UUID)}
case group.FieldName, group.FieldDescription, group.FieldK8sRoleName, group.FieldRole:
values[i] = new(sql.NullString)
@@ -155,6 +171,13 @@ func (_m *Group) assignValues(columns []string, values []any) error {
_m.TeamID = new(uuid.UUID)
*_m.TeamID = *value.S.(*uuid.UUID)
}
+ case group.FieldProjectID:
+ if value, ok := values[i].(*sql.NullScanner); !ok {
+ return fmt.Errorf("unexpected type %T for field project_id", values[i])
+ } else if value.Valid {
+ _m.ProjectID = new(uuid.UUID)
+ *_m.ProjectID = *value.S.(*uuid.UUID)
+ }
case group.FieldRole:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field role", values[i])
@@ -190,6 +213,11 @@ func (_m *Group) QueryTeam() *TeamQuery {
return NewGroupClient(_m.config).QueryTeam(_m)
}
+// QueryProject queries the "project" edge of the Group entity.
+func (_m *Group) QueryProject() *ProjectQuery {
+ return NewGroupClient(_m.config).QueryProject(_m)
+}
+
// Update returns a builder for updating this Group.
// Note that you need to call Group.Unwrap() before calling this method if this Group
// was returned from a transaction, and the transaction was committed or rolled back.
@@ -235,6 +263,11 @@ func (_m *Group) String() string {
builder.WriteString(fmt.Sprintf("%v", *v))
}
builder.WriteString(", ")
+ if v := _m.ProjectID; v != nil {
+ builder.WriteString("project_id=")
+ builder.WriteString(fmt.Sprintf("%v", *v))
+ }
+ builder.WriteString(", ")
if v := _m.Role; v != nil {
builder.WriteString("role=")
builder.WriteString(fmt.Sprintf("%v", *v))
diff --git a/apps/api/ent/group/group.go b/apps/api/ent/group/group.go
index 8a2de268f..408cb049d 100644
--- a/apps/api/ent/group/group.go
+++ b/apps/api/ent/group/group.go
@@ -29,6 +29,8 @@ const (
FieldK8sRoleName = "k8s_role_name"
// FieldTeamID holds the string denoting the team_id field in the database.
FieldTeamID = "team_id"
+ // FieldProjectID holds the string denoting the project_id field in the database.
+ FieldProjectID = "project_id"
// FieldRole holds the string denoting the role field in the database.
FieldRole = "role"
// EdgeUsers holds the string denoting the users edge name in mutations.
@@ -37,6 +39,8 @@ const (
EdgePermissions = "permissions"
// EdgeTeam holds the string denoting the team edge name in mutations.
EdgeTeam = "team"
+ // EdgeProject holds the string denoting the project edge name in mutations.
+ EdgeProject = "project"
// Table holds the table name of the group in the database.
Table = "groups"
// UsersTable is the table that holds the users relation/edge. The primary key declared below.
@@ -56,6 +60,13 @@ const (
TeamInverseTable = "teams"
// TeamColumn is the table column denoting the team relation/edge.
TeamColumn = "team_id"
+ // ProjectTable is the table that holds the project relation/edge.
+ ProjectTable = "groups"
+ // ProjectInverseTable is the table name for the Project entity.
+ // It exists in this package in order to avoid circular dependency with the "project" package.
+ ProjectInverseTable = "projects"
+ // ProjectColumn is the table column denoting the project relation/edge.
+ ProjectColumn = "project_id"
)
// Columns holds all SQL columns for group fields.
@@ -67,6 +78,7 @@ var Columns = []string{
FieldDescription,
FieldK8sRoleName,
FieldTeamID,
+ FieldProjectID,
FieldRole,
}
@@ -150,6 +162,11 @@ func ByTeamID(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldTeamID, opts...).ToFunc()
}
+// ByProjectID orders the results by the project_id field.
+func ByProjectID(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldProjectID, opts...).ToFunc()
+}
+
// ByRole orders the results by the role field.
func ByRole(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldRole, opts...).ToFunc()
@@ -189,6 +206,13 @@ func ByTeamField(field string, opts ...sql.OrderTermOption) OrderOption {
sqlgraph.OrderByNeighborTerms(s, newTeamStep(), sql.OrderByField(field, opts...))
}
}
+
+// ByProjectField orders the results by project field.
+func ByProjectField(field string, opts ...sql.OrderTermOption) OrderOption {
+ return func(s *sql.Selector) {
+ sqlgraph.OrderByNeighborTerms(s, newProjectStep(), sql.OrderByField(field, opts...))
+ }
+}
func newUsersStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
@@ -210,3 +234,10 @@ func newTeamStep() *sqlgraph.Step {
sqlgraph.Edge(sqlgraph.M2O, true, TeamTable, TeamColumn),
)
}
+func newProjectStep() *sqlgraph.Step {
+ return sqlgraph.NewStep(
+ sqlgraph.From(Table, FieldID),
+ sqlgraph.To(ProjectInverseTable, FieldID),
+ sqlgraph.Edge(sqlgraph.M2O, true, ProjectTable, ProjectColumn),
+ )
+}
diff --git a/apps/api/ent/group/where.go b/apps/api/ent/group/where.go
index ecda6f7e3..8a329f356 100644
--- a/apps/api/ent/group/where.go
+++ b/apps/api/ent/group/where.go
@@ -87,6 +87,11 @@ func TeamID(v uuid.UUID) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldTeamID, v))
}
+// ProjectID applies equality check predicate on the "project_id" field. It's identical to ProjectIDEQ.
+func ProjectID(v uuid.UUID) predicate.Group {
+ return predicate.Group(sql.FieldEQ(FieldProjectID, v))
+}
+
// CreatedAtEQ applies the EQ predicate on the "created_at" field.
func CreatedAtEQ(v time.Time) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldCreatedAt, v))
@@ -412,6 +417,36 @@ func TeamIDNotNil() predicate.Group {
return predicate.Group(sql.FieldNotNull(FieldTeamID))
}
+// ProjectIDEQ applies the EQ predicate on the "project_id" field.
+func ProjectIDEQ(v uuid.UUID) predicate.Group {
+ return predicate.Group(sql.FieldEQ(FieldProjectID, v))
+}
+
+// ProjectIDNEQ applies the NEQ predicate on the "project_id" field.
+func ProjectIDNEQ(v uuid.UUID) predicate.Group {
+ return predicate.Group(sql.FieldNEQ(FieldProjectID, v))
+}
+
+// ProjectIDIn applies the In predicate on the "project_id" field.
+func ProjectIDIn(vs ...uuid.UUID) predicate.Group {
+ return predicate.Group(sql.FieldIn(FieldProjectID, vs...))
+}
+
+// ProjectIDNotIn applies the NotIn predicate on the "project_id" field.
+func ProjectIDNotIn(vs ...uuid.UUID) predicate.Group {
+ return predicate.Group(sql.FieldNotIn(FieldProjectID, vs...))
+}
+
+// ProjectIDIsNil applies the IsNil predicate on the "project_id" field.
+func ProjectIDIsNil() predicate.Group {
+ return predicate.Group(sql.FieldIsNull(FieldProjectID))
+}
+
+// ProjectIDNotNil applies the NotNil predicate on the "project_id" field.
+func ProjectIDNotNil() predicate.Group {
+ return predicate.Group(sql.FieldNotNull(FieldProjectID))
+}
+
// RoleEQ applies the EQ predicate on the "role" field.
func RoleEQ(v schema.PermittedAction) predicate.Group {
vc := v
@@ -521,6 +556,29 @@ func HasTeamWith(preds ...predicate.Team) predicate.Group {
})
}
+// HasProject applies the HasEdge predicate on the "project" edge.
+func HasProject() predicate.Group {
+ return predicate.Group(func(s *sql.Selector) {
+ step := sqlgraph.NewStep(
+ sqlgraph.From(Table, FieldID),
+ sqlgraph.Edge(sqlgraph.M2O, true, ProjectTable, ProjectColumn),
+ )
+ sqlgraph.HasNeighbors(s, step)
+ })
+}
+
+// HasProjectWith applies the HasEdge predicate on the "project" edge with a given conditions (other predicates).
+func HasProjectWith(preds ...predicate.Project) predicate.Group {
+ return predicate.Group(func(s *sql.Selector) {
+ step := newProjectStep()
+ sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
+ for _, p := range preds {
+ p(s)
+ }
+ })
+ })
+}
+
// And groups predicates with the AND operator between them.
func And(predicates ...predicate.Group) predicate.Group {
return predicate.Group(sql.AndPredicates(predicates...))
diff --git a/apps/api/ent/group_create.go b/apps/api/ent/group_create.go
index eead3b646..b2d2ea6e9 100644
--- a/apps/api/ent/group_create.go
+++ b/apps/api/ent/group_create.go
@@ -15,6 +15,7 @@ import (
"github.com/google/uuid"
"github.com/unbindapp/unbind-api/ent/group"
"github.com/unbindapp/unbind-api/ent/permission"
+ "github.com/unbindapp/unbind-api/ent/project"
"github.com/unbindapp/unbind-api/ent/schema"
"github.com/unbindapp/unbind-api/ent/team"
"github.com/unbindapp/unbind-api/ent/user"
@@ -104,6 +105,20 @@ func (_c *GroupCreate) SetNillableTeamID(v *uuid.UUID) *GroupCreate {
return _c
}
+// SetProjectID sets the "project_id" field.
+func (_c *GroupCreate) SetProjectID(v uuid.UUID) *GroupCreate {
+ _c.mutation.SetProjectID(v)
+ return _c
+}
+
+// SetNillableProjectID sets the "project_id" field if the given value is not nil.
+func (_c *GroupCreate) SetNillableProjectID(v *uuid.UUID) *GroupCreate {
+ if v != nil {
+ _c.SetProjectID(*v)
+ }
+ return _c
+}
+
// SetRole sets the "role" field.
func (_c *GroupCreate) SetRole(v schema.PermittedAction) *GroupCreate {
_c.mutation.SetRole(v)
@@ -167,6 +182,11 @@ func (_c *GroupCreate) SetTeam(v *Team) *GroupCreate {
return _c.SetTeamID(v.ID)
}
+// SetProject sets the "project" edge to the Project entity.
+func (_c *GroupCreate) SetProject(v *Project) *GroupCreate {
+ return _c.SetProjectID(v.ID)
+}
+
// Mutation returns the GroupMutation object of the builder.
func (_c *GroupCreate) Mutation() *GroupMutation {
return _c.mutation
@@ -346,6 +366,23 @@ func (_c *GroupCreate) createSpec() (*Group, *sqlgraph.CreateSpec) {
_node.TeamID = &nodes[0]
_spec.Edges = append(_spec.Edges, edge)
}
+ if nodes := _c.mutation.ProjectIDs(); len(nodes) > 0 {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.M2O,
+ Inverse: true,
+ Table: group.ProjectTable,
+ Columns: []string{group.ProjectColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(project.FieldID, field.TypeUUID),
+ },
+ }
+ for _, k := range nodes {
+ edge.Target.Nodes = append(edge.Target.Nodes, k)
+ }
+ _node.ProjectID = &nodes[0]
+ _spec.Edges = append(_spec.Edges, edge)
+ }
return _node, _spec
}
@@ -476,6 +513,24 @@ func (u *GroupUpsert) ClearTeamID() *GroupUpsert {
return u
}
+// SetProjectID sets the "project_id" field.
+func (u *GroupUpsert) SetProjectID(v uuid.UUID) *GroupUpsert {
+ u.Set(group.FieldProjectID, v)
+ return u
+}
+
+// UpdateProjectID sets the "project_id" field to the value that was provided on create.
+func (u *GroupUpsert) UpdateProjectID() *GroupUpsert {
+ u.SetExcluded(group.FieldProjectID)
+ return u
+}
+
+// ClearProjectID clears the value of the "project_id" field.
+func (u *GroupUpsert) ClearProjectID() *GroupUpsert {
+ u.SetNull(group.FieldProjectID)
+ return u
+}
+
// SetRole sets the "role" field.
func (u *GroupUpsert) SetRole(v schema.PermittedAction) *GroupUpsert {
u.Set(group.FieldRole, v)
@@ -636,6 +691,27 @@ func (u *GroupUpsertOne) ClearTeamID() *GroupUpsertOne {
})
}
+// SetProjectID sets the "project_id" field.
+func (u *GroupUpsertOne) SetProjectID(v uuid.UUID) *GroupUpsertOne {
+ return u.Update(func(s *GroupUpsert) {
+ s.SetProjectID(v)
+ })
+}
+
+// UpdateProjectID sets the "project_id" field to the value that was provided on create.
+func (u *GroupUpsertOne) UpdateProjectID() *GroupUpsertOne {
+ return u.Update(func(s *GroupUpsert) {
+ s.UpdateProjectID()
+ })
+}
+
+// ClearProjectID clears the value of the "project_id" field.
+func (u *GroupUpsertOne) ClearProjectID() *GroupUpsertOne {
+ return u.Update(func(s *GroupUpsert) {
+ s.ClearProjectID()
+ })
+}
+
// SetRole sets the "role" field.
func (u *GroupUpsertOne) SetRole(v schema.PermittedAction) *GroupUpsertOne {
return u.Update(func(s *GroupUpsert) {
@@ -966,6 +1042,27 @@ func (u *GroupUpsertBulk) ClearTeamID() *GroupUpsertBulk {
})
}
+// SetProjectID sets the "project_id" field.
+func (u *GroupUpsertBulk) SetProjectID(v uuid.UUID) *GroupUpsertBulk {
+ return u.Update(func(s *GroupUpsert) {
+ s.SetProjectID(v)
+ })
+}
+
+// UpdateProjectID sets the "project_id" field to the value that was provided on create.
+func (u *GroupUpsertBulk) UpdateProjectID() *GroupUpsertBulk {
+ return u.Update(func(s *GroupUpsert) {
+ s.UpdateProjectID()
+ })
+}
+
+// ClearProjectID clears the value of the "project_id" field.
+func (u *GroupUpsertBulk) ClearProjectID() *GroupUpsertBulk {
+ return u.Update(func(s *GroupUpsert) {
+ s.ClearProjectID()
+ })
+}
+
// SetRole sets the "role" field.
func (u *GroupUpsertBulk) SetRole(v schema.PermittedAction) *GroupUpsertBulk {
return u.Update(func(s *GroupUpsert) {
diff --git a/apps/api/ent/group_query.go b/apps/api/ent/group_query.go
index 655cb1ca7..8714f6c07 100644
--- a/apps/api/ent/group_query.go
+++ b/apps/api/ent/group_query.go
@@ -16,6 +16,7 @@ import (
"github.com/unbindapp/unbind-api/ent/group"
"github.com/unbindapp/unbind-api/ent/permission"
"github.com/unbindapp/unbind-api/ent/predicate"
+ "github.com/unbindapp/unbind-api/ent/project"
"github.com/unbindapp/unbind-api/ent/team"
"github.com/unbindapp/unbind-api/ent/user"
)
@@ -30,6 +31,7 @@ type GroupQuery struct {
withUsers *UserQuery
withPermissions *PermissionQuery
withTeam *TeamQuery
+ withProject *ProjectQuery
modifiers []func(*sql.Selector)
// intermediate query (i.e. traversal path).
sql *sql.Selector
@@ -133,6 +135,28 @@ func (_q *GroupQuery) QueryTeam() *TeamQuery {
return query
}
+// QueryProject chains the current query on the "project" edge.
+func (_q *GroupQuery) QueryProject() *ProjectQuery {
+ query := (&ProjectClient{config: _q.config}).Query()
+ query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
+ if err := _q.prepareQuery(ctx); err != nil {
+ return nil, err
+ }
+ selector := _q.sqlQuery(ctx)
+ if err := selector.Err(); err != nil {
+ return nil, err
+ }
+ step := sqlgraph.NewStep(
+ sqlgraph.From(group.Table, group.FieldID, selector),
+ sqlgraph.To(project.Table, project.FieldID),
+ sqlgraph.Edge(sqlgraph.M2O, true, group.ProjectTable, group.ProjectColumn),
+ )
+ fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step)
+ return fromU, nil
+ }
+ return query
+}
+
// First returns the first Group entity from the query.
// Returns a *NotFoundError when no Group was found.
func (_q *GroupQuery) First(ctx context.Context) (*Group, error) {
@@ -328,6 +352,7 @@ func (_q *GroupQuery) Clone() *GroupQuery {
withUsers: _q.withUsers.Clone(),
withPermissions: _q.withPermissions.Clone(),
withTeam: _q.withTeam.Clone(),
+ withProject: _q.withProject.Clone(),
// clone intermediate query.
sql: _q.sql.Clone(),
path: _q.path,
@@ -368,6 +393,17 @@ func (_q *GroupQuery) WithTeam(opts ...func(*TeamQuery)) *GroupQuery {
return _q
}
+// WithProject tells the query-builder to eager-load the nodes that are connected to
+// the "project" edge. The optional arguments are used to configure the query builder of the edge.
+func (_q *GroupQuery) WithProject(opts ...func(*ProjectQuery)) *GroupQuery {
+ query := (&ProjectClient{config: _q.config}).Query()
+ for _, opt := range opts {
+ opt(query)
+ }
+ _q.withProject = query
+ return _q
+}
+
// GroupBy is used to group vertices by one or more fields/columns.
// It is often used with aggregate functions, like: count, max, mean, min, sum.
//
@@ -446,10 +482,11 @@ func (_q *GroupQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Group,
var (
nodes = []*Group{}
_spec = _q.querySpec()
- loadedTypes = [3]bool{
+ loadedTypes = [4]bool{
_q.withUsers != nil,
_q.withPermissions != nil,
_q.withTeam != nil,
+ _q.withProject != nil,
}
)
_spec.ScanValues = func(columns []string) ([]any, error) {
@@ -493,6 +530,12 @@ func (_q *GroupQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Group,
return nil, err
}
}
+ if query := _q.withProject; query != nil {
+ if err := _q.loadProject(ctx, query, nodes, nil,
+ func(n *Group, e *Project) { n.Edges.Project = e }); err != nil {
+ return nil, err
+ }
+ }
return nodes, nil
}
@@ -650,6 +693,38 @@ func (_q *GroupQuery) loadTeam(ctx context.Context, query *TeamQuery, nodes []*G
}
return nil
}
+func (_q *GroupQuery) loadProject(ctx context.Context, query *ProjectQuery, nodes []*Group, init func(*Group), assign func(*Group, *Project)) error {
+ ids := make([]uuid.UUID, 0, len(nodes))
+ nodeids := make(map[uuid.UUID][]*Group)
+ for i := range nodes {
+ if nodes[i].ProjectID == nil {
+ continue
+ }
+ fk := *nodes[i].ProjectID
+ if _, ok := nodeids[fk]; !ok {
+ ids = append(ids, fk)
+ }
+ nodeids[fk] = append(nodeids[fk], nodes[i])
+ }
+ if len(ids) == 0 {
+ return nil
+ }
+ query.Where(project.IDIn(ids...))
+ neighbors, err := query.All(ctx)
+ if err != nil {
+ return err
+ }
+ for _, n := range neighbors {
+ nodes, ok := nodeids[n.ID]
+ if !ok {
+ return fmt.Errorf(`unexpected foreign-key "project_id" returned %v`, n.ID)
+ }
+ for i := range nodes {
+ assign(nodes[i], n)
+ }
+ }
+ return nil
+}
func (_q *GroupQuery) sqlCount(ctx context.Context) (int, error) {
_spec := _q.querySpec()
@@ -682,6 +757,9 @@ func (_q *GroupQuery) querySpec() *sqlgraph.QuerySpec {
if _q.withTeam != nil {
_spec.Node.AddColumnOnce(group.FieldTeamID)
}
+ if _q.withProject != nil {
+ _spec.Node.AddColumnOnce(group.FieldProjectID)
+ }
}
if ps := _q.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
diff --git a/apps/api/ent/group_update.go b/apps/api/ent/group_update.go
index d84e113e2..7213f7be1 100644
--- a/apps/api/ent/group_update.go
+++ b/apps/api/ent/group_update.go
@@ -15,6 +15,7 @@ import (
"github.com/unbindapp/unbind-api/ent/group"
"github.com/unbindapp/unbind-api/ent/permission"
"github.com/unbindapp/unbind-api/ent/predicate"
+ "github.com/unbindapp/unbind-api/ent/project"
"github.com/unbindapp/unbind-api/ent/schema"
"github.com/unbindapp/unbind-api/ent/team"
"github.com/unbindapp/unbind-api/ent/user"
@@ -114,6 +115,26 @@ func (_u *GroupUpdate) ClearTeamID() *GroupUpdate {
return _u
}
+// SetProjectID sets the "project_id" field.
+func (_u *GroupUpdate) SetProjectID(v uuid.UUID) *GroupUpdate {
+ _u.mutation.SetProjectID(v)
+ return _u
+}
+
+// SetNillableProjectID sets the "project_id" field if the given value is not nil.
+func (_u *GroupUpdate) SetNillableProjectID(v *uuid.UUID) *GroupUpdate {
+ if v != nil {
+ _u.SetProjectID(*v)
+ }
+ return _u
+}
+
+// ClearProjectID clears the value of the "project_id" field.
+func (_u *GroupUpdate) ClearProjectID() *GroupUpdate {
+ _u.mutation.ClearProjectID()
+ return _u
+}
+
// SetRole sets the "role" field.
func (_u *GroupUpdate) SetRole(v schema.PermittedAction) *GroupUpdate {
_u.mutation.SetRole(v)
@@ -169,6 +190,11 @@ func (_u *GroupUpdate) SetTeam(v *Team) *GroupUpdate {
return _u.SetTeamID(v.ID)
}
+// SetProject sets the "project" edge to the Project entity.
+func (_u *GroupUpdate) SetProject(v *Project) *GroupUpdate {
+ return _u.SetProjectID(v.ID)
+}
+
// Mutation returns the GroupMutation object of the builder.
func (_u *GroupUpdate) Mutation() *GroupMutation {
return _u.mutation
@@ -222,6 +248,12 @@ func (_u *GroupUpdate) ClearTeam() *GroupUpdate {
return _u
}
+// ClearProject clears the "project" edge to the Project entity.
+func (_u *GroupUpdate) ClearProject() *GroupUpdate {
+ _u.mutation.ClearProject()
+ return _u
+}
+
// Save executes the query and returns the number of nodes affected by the update operation.
func (_u *GroupUpdate) Save(ctx context.Context) (int, error) {
_u.defaults()
@@ -434,6 +466,35 @@ func (_u *GroupUpdate) sqlSave(ctx context.Context) (_node int, err error) {
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
+ if _u.mutation.ProjectCleared() {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.M2O,
+ Inverse: true,
+ Table: group.ProjectTable,
+ Columns: []string{group.ProjectColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(project.FieldID, field.TypeUUID),
+ },
+ }
+ _spec.Edges.Clear = append(_spec.Edges.Clear, edge)
+ }
+ if nodes := _u.mutation.ProjectIDs(); len(nodes) > 0 {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.M2O,
+ Inverse: true,
+ Table: group.ProjectTable,
+ Columns: []string{group.ProjectColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(project.FieldID, field.TypeUUID),
+ },
+ }
+ for _, k := range nodes {
+ edge.Target.Nodes = append(edge.Target.Nodes, k)
+ }
+ _spec.Edges.Add = append(_spec.Edges.Add, edge)
+ }
_spec.AddModifiers(_u.modifiers...)
if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
@@ -536,6 +597,26 @@ func (_u *GroupUpdateOne) ClearTeamID() *GroupUpdateOne {
return _u
}
+// SetProjectID sets the "project_id" field.
+func (_u *GroupUpdateOne) SetProjectID(v uuid.UUID) *GroupUpdateOne {
+ _u.mutation.SetProjectID(v)
+ return _u
+}
+
+// SetNillableProjectID sets the "project_id" field if the given value is not nil.
+func (_u *GroupUpdateOne) SetNillableProjectID(v *uuid.UUID) *GroupUpdateOne {
+ if v != nil {
+ _u.SetProjectID(*v)
+ }
+ return _u
+}
+
+// ClearProjectID clears the value of the "project_id" field.
+func (_u *GroupUpdateOne) ClearProjectID() *GroupUpdateOne {
+ _u.mutation.ClearProjectID()
+ return _u
+}
+
// SetRole sets the "role" field.
func (_u *GroupUpdateOne) SetRole(v schema.PermittedAction) *GroupUpdateOne {
_u.mutation.SetRole(v)
@@ -591,6 +672,11 @@ func (_u *GroupUpdateOne) SetTeam(v *Team) *GroupUpdateOne {
return _u.SetTeamID(v.ID)
}
+// SetProject sets the "project" edge to the Project entity.
+func (_u *GroupUpdateOne) SetProject(v *Project) *GroupUpdateOne {
+ return _u.SetProjectID(v.ID)
+}
+
// Mutation returns the GroupMutation object of the builder.
func (_u *GroupUpdateOne) Mutation() *GroupMutation {
return _u.mutation
@@ -644,6 +730,12 @@ func (_u *GroupUpdateOne) ClearTeam() *GroupUpdateOne {
return _u
}
+// ClearProject clears the "project" edge to the Project entity.
+func (_u *GroupUpdateOne) ClearProject() *GroupUpdateOne {
+ _u.mutation.ClearProject()
+ return _u
+}
+
// Where appends a list predicates to the GroupUpdate builder.
func (_u *GroupUpdateOne) Where(ps ...predicate.Group) *GroupUpdateOne {
_u.mutation.Where(ps...)
@@ -886,6 +978,35 @@ func (_u *GroupUpdateOne) sqlSave(ctx context.Context) (_node *Group, err error)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
+ if _u.mutation.ProjectCleared() {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.M2O,
+ Inverse: true,
+ Table: group.ProjectTable,
+ Columns: []string{group.ProjectColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(project.FieldID, field.TypeUUID),
+ },
+ }
+ _spec.Edges.Clear = append(_spec.Edges.Clear, edge)
+ }
+ if nodes := _u.mutation.ProjectIDs(); len(nodes) > 0 {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.M2O,
+ Inverse: true,
+ Table: group.ProjectTable,
+ Columns: []string{group.ProjectColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(project.FieldID, field.TypeUUID),
+ },
+ }
+ for _, k := range nodes {
+ edge.Target.Nodes = append(edge.Target.Nodes, k)
+ }
+ _spec.Edges.Add = append(_spec.Edges.Add, edge)
+ }
_spec.AddModifiers(_u.modifiers...)
_node = &Group{config: _u.config}
_spec.Assign = _node.assignValues
diff --git a/apps/api/ent/invitation.go b/apps/api/ent/invitation.go
index 83b7f60c4..13260717c 100644
--- a/apps/api/ent/invitation.go
+++ b/apps/api/ent/invitation.go
@@ -11,6 +11,7 @@ import (
"entgo.io/ent/dialect/sql"
"github.com/google/uuid"
"github.com/unbindapp/unbind-api/ent/invitation"
+ "github.com/unbindapp/unbind-api/ent/project"
"github.com/unbindapp/unbind-api/ent/schema"
"github.com/unbindapp/unbind-api/ent/team"
"github.com/unbindapp/unbind-api/ent/user"
@@ -38,6 +39,8 @@ type Invitation struct {
AcceptedAt *time.Time `json:"accepted_at,omitempty"`
// TeamID holds the value of the "team_id" field.
TeamID uuid.UUID `json:"team_id,omitempty"`
+ // ProjectID holds the value of the "project_id" field.
+ ProjectID *uuid.UUID `json:"project_id,omitempty"`
// InvitedBy holds the value of the "invited_by" field.
InvitedBy *uuid.UUID `json:"invited_by,omitempty"`
// Edges holds the relations/edges for other nodes in the graph.
@@ -50,11 +53,13 @@ type Invitation struct {
type InvitationEdges struct {
// Team holds the value of the team edge.
Team *Team `json:"team,omitempty"`
+ // Project holds the value of the project edge.
+ Project *Project `json:"project,omitempty"`
// Inviter holds the value of the inviter edge.
Inviter *User `json:"inviter,omitempty"`
// loadedTypes holds the information for reporting if a
// type was loaded (or requested) in eager-loading or not.
- loadedTypes [2]bool
+ loadedTypes [3]bool
}
// TeamOrErr returns the Team value or an error if the edge
@@ -68,12 +73,23 @@ func (e InvitationEdges) TeamOrErr() (*Team, error) {
return nil, &NotLoadedError{edge: "team"}
}
+// ProjectOrErr returns the Project value or an error if the edge
+// was not loaded in eager-loading, or loaded but was not found.
+func (e InvitationEdges) ProjectOrErr() (*Project, error) {
+ if e.Project != nil {
+ return e.Project, nil
+ } else if e.loadedTypes[1] {
+ return nil, &NotFoundError{label: project.Label}
+ }
+ return nil, &NotLoadedError{edge: "project"}
+}
+
// InviterOrErr returns the Inviter value or an error if the edge
// was not loaded in eager-loading, or loaded but was not found.
func (e InvitationEdges) InviterOrErr() (*User, error) {
if e.Inviter != nil {
return e.Inviter, nil
- } else if e.loadedTypes[1] {
+ } else if e.loadedTypes[2] {
return nil, &NotFoundError{label: user.Label}
}
return nil, &NotLoadedError{edge: "inviter"}
@@ -84,7 +100,7 @@ func (*Invitation) scanValues(columns []string) ([]any, error) {
values := make([]any, len(columns))
for i := range columns {
switch columns[i] {
- case invitation.FieldInvitedBy:
+ case invitation.FieldProjectID, invitation.FieldInvitedBy:
values[i] = &sql.NullScanner{S: new(uuid.UUID)}
case invitation.FieldEmail, invitation.FieldTokenHash, invitation.FieldRole:
values[i] = new(sql.NullString)
@@ -162,6 +178,13 @@ func (_m *Invitation) assignValues(columns []string, values []any) error {
} else if value != nil {
_m.TeamID = *value
}
+ case invitation.FieldProjectID:
+ if value, ok := values[i].(*sql.NullScanner); !ok {
+ return fmt.Errorf("unexpected type %T for field project_id", values[i])
+ } else if value.Valid {
+ _m.ProjectID = new(uuid.UUID)
+ *_m.ProjectID = *value.S.(*uuid.UUID)
+ }
case invitation.FieldInvitedBy:
if value, ok := values[i].(*sql.NullScanner); !ok {
return fmt.Errorf("unexpected type %T for field invited_by", values[i])
@@ -187,6 +210,11 @@ func (_m *Invitation) QueryTeam() *TeamQuery {
return NewInvitationClient(_m.config).QueryTeam(_m)
}
+// QueryProject queries the "project" edge of the Invitation entity.
+func (_m *Invitation) QueryProject() *ProjectQuery {
+ return NewInvitationClient(_m.config).QueryProject(_m)
+}
+
// QueryInviter queries the "inviter" edge of the Invitation entity.
func (_m *Invitation) QueryInviter() *UserQuery {
return NewInvitationClient(_m.config).QueryInviter(_m)
@@ -240,6 +268,11 @@ func (_m *Invitation) String() string {
builder.WriteString("team_id=")
builder.WriteString(fmt.Sprintf("%v", _m.TeamID))
builder.WriteString(", ")
+ if v := _m.ProjectID; v != nil {
+ builder.WriteString("project_id=")
+ builder.WriteString(fmt.Sprintf("%v", *v))
+ }
+ builder.WriteString(", ")
if v := _m.InvitedBy; v != nil {
builder.WriteString("invited_by=")
builder.WriteString(fmt.Sprintf("%v", *v))
diff --git a/apps/api/ent/invitation/invitation.go b/apps/api/ent/invitation/invitation.go
index 27c2ed3b3..daf691068 100644
--- a/apps/api/ent/invitation/invitation.go
+++ b/apps/api/ent/invitation/invitation.go
@@ -33,10 +33,14 @@ const (
FieldAcceptedAt = "accepted_at"
// FieldTeamID holds the string denoting the team_id field in the database.
FieldTeamID = "team_id"
+ // FieldProjectID holds the string denoting the project_id field in the database.
+ FieldProjectID = "project_id"
// FieldInvitedBy holds the string denoting the invited_by field in the database.
FieldInvitedBy = "invited_by"
// EdgeTeam holds the string denoting the team edge name in mutations.
EdgeTeam = "team"
+ // EdgeProject holds the string denoting the project edge name in mutations.
+ EdgeProject = "project"
// EdgeInviter holds the string denoting the inviter edge name in mutations.
EdgeInviter = "inviter"
// Table holds the table name of the invitation in the database.
@@ -48,6 +52,13 @@ const (
TeamInverseTable = "teams"
// TeamColumn is the table column denoting the team relation/edge.
TeamColumn = "team_id"
+ // ProjectTable is the table that holds the project relation/edge.
+ ProjectTable = "invitations"
+ // ProjectInverseTable is the table name for the Project entity.
+ // It exists in this package in order to avoid circular dependency with the "project" package.
+ ProjectInverseTable = "projects"
+ // ProjectColumn is the table column denoting the project relation/edge.
+ ProjectColumn = "project_id"
// InviterTable is the table that holds the inviter relation/edge.
InviterTable = "invitations"
// InviterInverseTable is the table name for the User entity.
@@ -68,6 +79,7 @@ var Columns = []string{
FieldExpiresAt,
FieldAcceptedAt,
FieldTeamID,
+ FieldProjectID,
FieldInvitedBy,
}
@@ -152,6 +164,11 @@ func ByTeamID(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldTeamID, opts...).ToFunc()
}
+// ByProjectID orders the results by the project_id field.
+func ByProjectID(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldProjectID, opts...).ToFunc()
+}
+
// ByInvitedBy orders the results by the invited_by field.
func ByInvitedBy(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldInvitedBy, opts...).ToFunc()
@@ -164,6 +181,13 @@ func ByTeamField(field string, opts ...sql.OrderTermOption) OrderOption {
}
}
+// ByProjectField orders the results by project field.
+func ByProjectField(field string, opts ...sql.OrderTermOption) OrderOption {
+ return func(s *sql.Selector) {
+ sqlgraph.OrderByNeighborTerms(s, newProjectStep(), sql.OrderByField(field, opts...))
+ }
+}
+
// ByInviterField orders the results by inviter field.
func ByInviterField(field string, opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
@@ -177,6 +201,13 @@ func newTeamStep() *sqlgraph.Step {
sqlgraph.Edge(sqlgraph.M2O, true, TeamTable, TeamColumn),
)
}
+func newProjectStep() *sqlgraph.Step {
+ return sqlgraph.NewStep(
+ sqlgraph.From(Table, FieldID),
+ sqlgraph.To(ProjectInverseTable, FieldID),
+ sqlgraph.Edge(sqlgraph.M2O, true, ProjectTable, ProjectColumn),
+ )
+}
func newInviterStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
diff --git a/apps/api/ent/invitation/where.go b/apps/api/ent/invitation/where.go
index 43de3f7b9..aa508b8d6 100644
--- a/apps/api/ent/invitation/where.go
+++ b/apps/api/ent/invitation/where.go
@@ -92,6 +92,11 @@ func TeamID(v uuid.UUID) predicate.Invitation {
return predicate.Invitation(sql.FieldEQ(FieldTeamID, v))
}
+// ProjectID applies equality check predicate on the "project_id" field. It's identical to ProjectIDEQ.
+func ProjectID(v uuid.UUID) predicate.Invitation {
+ return predicate.Invitation(sql.FieldEQ(FieldProjectID, v))
+}
+
// InvitedBy applies equality check predicate on the "invited_by" field. It's identical to InvitedByEQ.
func InvitedBy(v uuid.UUID) predicate.Invitation {
return predicate.Invitation(sql.FieldEQ(FieldInvitedBy, v))
@@ -447,6 +452,36 @@ func TeamIDNotIn(vs ...uuid.UUID) predicate.Invitation {
return predicate.Invitation(sql.FieldNotIn(FieldTeamID, vs...))
}
+// ProjectIDEQ applies the EQ predicate on the "project_id" field.
+func ProjectIDEQ(v uuid.UUID) predicate.Invitation {
+ return predicate.Invitation(sql.FieldEQ(FieldProjectID, v))
+}
+
+// ProjectIDNEQ applies the NEQ predicate on the "project_id" field.
+func ProjectIDNEQ(v uuid.UUID) predicate.Invitation {
+ return predicate.Invitation(sql.FieldNEQ(FieldProjectID, v))
+}
+
+// ProjectIDIn applies the In predicate on the "project_id" field.
+func ProjectIDIn(vs ...uuid.UUID) predicate.Invitation {
+ return predicate.Invitation(sql.FieldIn(FieldProjectID, vs...))
+}
+
+// ProjectIDNotIn applies the NotIn predicate on the "project_id" field.
+func ProjectIDNotIn(vs ...uuid.UUID) predicate.Invitation {
+ return predicate.Invitation(sql.FieldNotIn(FieldProjectID, vs...))
+}
+
+// ProjectIDIsNil applies the IsNil predicate on the "project_id" field.
+func ProjectIDIsNil() predicate.Invitation {
+ return predicate.Invitation(sql.FieldIsNull(FieldProjectID))
+}
+
+// ProjectIDNotNil applies the NotNil predicate on the "project_id" field.
+func ProjectIDNotNil() predicate.Invitation {
+ return predicate.Invitation(sql.FieldNotNull(FieldProjectID))
+}
+
// InvitedByEQ applies the EQ predicate on the "invited_by" field.
func InvitedByEQ(v uuid.UUID) predicate.Invitation {
return predicate.Invitation(sql.FieldEQ(FieldInvitedBy, v))
@@ -500,6 +535,29 @@ func HasTeamWith(preds ...predicate.Team) predicate.Invitation {
})
}
+// HasProject applies the HasEdge predicate on the "project" edge.
+func HasProject() predicate.Invitation {
+ return predicate.Invitation(func(s *sql.Selector) {
+ step := sqlgraph.NewStep(
+ sqlgraph.From(Table, FieldID),
+ sqlgraph.Edge(sqlgraph.M2O, true, ProjectTable, ProjectColumn),
+ )
+ sqlgraph.HasNeighbors(s, step)
+ })
+}
+
+// HasProjectWith applies the HasEdge predicate on the "project" edge with a given conditions (other predicates).
+func HasProjectWith(preds ...predicate.Project) predicate.Invitation {
+ return predicate.Invitation(func(s *sql.Selector) {
+ step := newProjectStep()
+ sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
+ for _, p := range preds {
+ p(s)
+ }
+ })
+ })
+}
+
// HasInviter applies the HasEdge predicate on the "inviter" edge.
func HasInviter() predicate.Invitation {
return predicate.Invitation(func(s *sql.Selector) {
diff --git a/apps/api/ent/invitation_create.go b/apps/api/ent/invitation_create.go
index 648fa298b..faf471c08 100644
--- a/apps/api/ent/invitation_create.go
+++ b/apps/api/ent/invitation_create.go
@@ -14,6 +14,7 @@ import (
"entgo.io/ent/schema/field"
"github.com/google/uuid"
"github.com/unbindapp/unbind-api/ent/invitation"
+ "github.com/unbindapp/unbind-api/ent/project"
"github.com/unbindapp/unbind-api/ent/schema"
"github.com/unbindapp/unbind-api/ent/team"
"github.com/unbindapp/unbind-api/ent/user"
@@ -99,6 +100,20 @@ func (_c *InvitationCreate) SetTeamID(v uuid.UUID) *InvitationCreate {
return _c
}
+// SetProjectID sets the "project_id" field.
+func (_c *InvitationCreate) SetProjectID(v uuid.UUID) *InvitationCreate {
+ _c.mutation.SetProjectID(v)
+ return _c
+}
+
+// SetNillableProjectID sets the "project_id" field if the given value is not nil.
+func (_c *InvitationCreate) SetNillableProjectID(v *uuid.UUID) *InvitationCreate {
+ if v != nil {
+ _c.SetProjectID(*v)
+ }
+ return _c
+}
+
// SetInvitedBy sets the "invited_by" field.
func (_c *InvitationCreate) SetInvitedBy(v uuid.UUID) *InvitationCreate {
_c.mutation.SetInvitedBy(v)
@@ -132,6 +147,11 @@ func (_c *InvitationCreate) SetTeam(v *Team) *InvitationCreate {
return _c.SetTeamID(v.ID)
}
+// SetProject sets the "project" edge to the Project entity.
+func (_c *InvitationCreate) SetProject(v *Project) *InvitationCreate {
+ return _c.SetProjectID(v.ID)
+}
+
// SetInviterID sets the "inviter" edge to the User entity by ID.
func (_c *InvitationCreate) SetInviterID(id uuid.UUID) *InvitationCreate {
_c.mutation.SetInviterID(id)
@@ -317,6 +337,23 @@ func (_c *InvitationCreate) createSpec() (*Invitation, *sqlgraph.CreateSpec) {
_node.TeamID = nodes[0]
_spec.Edges = append(_spec.Edges, edge)
}
+ if nodes := _c.mutation.ProjectIDs(); len(nodes) > 0 {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.M2O,
+ Inverse: true,
+ Table: invitation.ProjectTable,
+ Columns: []string{invitation.ProjectColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(project.FieldID, field.TypeUUID),
+ },
+ }
+ for _, k := range nodes {
+ edge.Target.Nodes = append(edge.Target.Nodes, k)
+ }
+ _node.ProjectID = &nodes[0]
+ _spec.Edges = append(_spec.Edges, edge)
+ }
if nodes := _c.mutation.InviterIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
@@ -476,6 +513,24 @@ func (u *InvitationUpsert) UpdateTeamID() *InvitationUpsert {
return u
}
+// SetProjectID sets the "project_id" field.
+func (u *InvitationUpsert) SetProjectID(v uuid.UUID) *InvitationUpsert {
+ u.Set(invitation.FieldProjectID, v)
+ return u
+}
+
+// UpdateProjectID sets the "project_id" field to the value that was provided on create.
+func (u *InvitationUpsert) UpdateProjectID() *InvitationUpsert {
+ u.SetExcluded(invitation.FieldProjectID)
+ return u
+}
+
+// ClearProjectID clears the value of the "project_id" field.
+func (u *InvitationUpsert) ClearProjectID() *InvitationUpsert {
+ u.SetNull(invitation.FieldProjectID)
+ return u
+}
+
// SetInvitedBy sets the "invited_by" field.
func (u *InvitationUpsert) SetInvitedBy(v uuid.UUID) *InvitationUpsert {
u.Set(invitation.FieldInvitedBy, v)
@@ -650,6 +705,27 @@ func (u *InvitationUpsertOne) UpdateTeamID() *InvitationUpsertOne {
})
}
+// SetProjectID sets the "project_id" field.
+func (u *InvitationUpsertOne) SetProjectID(v uuid.UUID) *InvitationUpsertOne {
+ return u.Update(func(s *InvitationUpsert) {
+ s.SetProjectID(v)
+ })
+}
+
+// UpdateProjectID sets the "project_id" field to the value that was provided on create.
+func (u *InvitationUpsertOne) UpdateProjectID() *InvitationUpsertOne {
+ return u.Update(func(s *InvitationUpsert) {
+ s.UpdateProjectID()
+ })
+}
+
+// ClearProjectID clears the value of the "project_id" field.
+func (u *InvitationUpsertOne) ClearProjectID() *InvitationUpsertOne {
+ return u.Update(func(s *InvitationUpsert) {
+ s.ClearProjectID()
+ })
+}
+
// SetInvitedBy sets the "invited_by" field.
func (u *InvitationUpsertOne) SetInvitedBy(v uuid.UUID) *InvitationUpsertOne {
return u.Update(func(s *InvitationUpsert) {
@@ -994,6 +1070,27 @@ func (u *InvitationUpsertBulk) UpdateTeamID() *InvitationUpsertBulk {
})
}
+// SetProjectID sets the "project_id" field.
+func (u *InvitationUpsertBulk) SetProjectID(v uuid.UUID) *InvitationUpsertBulk {
+ return u.Update(func(s *InvitationUpsert) {
+ s.SetProjectID(v)
+ })
+}
+
+// UpdateProjectID sets the "project_id" field to the value that was provided on create.
+func (u *InvitationUpsertBulk) UpdateProjectID() *InvitationUpsertBulk {
+ return u.Update(func(s *InvitationUpsert) {
+ s.UpdateProjectID()
+ })
+}
+
+// ClearProjectID clears the value of the "project_id" field.
+func (u *InvitationUpsertBulk) ClearProjectID() *InvitationUpsertBulk {
+ return u.Update(func(s *InvitationUpsert) {
+ s.ClearProjectID()
+ })
+}
+
// SetInvitedBy sets the "invited_by" field.
func (u *InvitationUpsertBulk) SetInvitedBy(v uuid.UUID) *InvitationUpsertBulk {
return u.Update(func(s *InvitationUpsert) {
diff --git a/apps/api/ent/invitation_query.go b/apps/api/ent/invitation_query.go
index b5e762e89..81039537a 100644
--- a/apps/api/ent/invitation_query.go
+++ b/apps/api/ent/invitation_query.go
@@ -14,6 +14,7 @@ import (
"github.com/google/uuid"
"github.com/unbindapp/unbind-api/ent/invitation"
"github.com/unbindapp/unbind-api/ent/predicate"
+ "github.com/unbindapp/unbind-api/ent/project"
"github.com/unbindapp/unbind-api/ent/team"
"github.com/unbindapp/unbind-api/ent/user"
)
@@ -26,6 +27,7 @@ type InvitationQuery struct {
inters []Interceptor
predicates []predicate.Invitation
withTeam *TeamQuery
+ withProject *ProjectQuery
withInviter *UserQuery
modifiers []func(*sql.Selector)
// intermediate query (i.e. traversal path).
@@ -86,6 +88,28 @@ func (_q *InvitationQuery) QueryTeam() *TeamQuery {
return query
}
+// QueryProject chains the current query on the "project" edge.
+func (_q *InvitationQuery) QueryProject() *ProjectQuery {
+ query := (&ProjectClient{config: _q.config}).Query()
+ query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
+ if err := _q.prepareQuery(ctx); err != nil {
+ return nil, err
+ }
+ selector := _q.sqlQuery(ctx)
+ if err := selector.Err(); err != nil {
+ return nil, err
+ }
+ step := sqlgraph.NewStep(
+ sqlgraph.From(invitation.Table, invitation.FieldID, selector),
+ sqlgraph.To(project.Table, project.FieldID),
+ sqlgraph.Edge(sqlgraph.M2O, true, invitation.ProjectTable, invitation.ProjectColumn),
+ )
+ fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step)
+ return fromU, nil
+ }
+ return query
+}
+
// QueryInviter chains the current query on the "inviter" edge.
func (_q *InvitationQuery) QueryInviter() *UserQuery {
query := (&UserClient{config: _q.config}).Query()
@@ -301,6 +325,7 @@ func (_q *InvitationQuery) Clone() *InvitationQuery {
inters: append([]Interceptor{}, _q.inters...),
predicates: append([]predicate.Invitation{}, _q.predicates...),
withTeam: _q.withTeam.Clone(),
+ withProject: _q.withProject.Clone(),
withInviter: _q.withInviter.Clone(),
// clone intermediate query.
sql: _q.sql.Clone(),
@@ -320,6 +345,17 @@ func (_q *InvitationQuery) WithTeam(opts ...func(*TeamQuery)) *InvitationQuery {
return _q
}
+// WithProject tells the query-builder to eager-load the nodes that are connected to
+// the "project" edge. The optional arguments are used to configure the query builder of the edge.
+func (_q *InvitationQuery) WithProject(opts ...func(*ProjectQuery)) *InvitationQuery {
+ query := (&ProjectClient{config: _q.config}).Query()
+ for _, opt := range opts {
+ opt(query)
+ }
+ _q.withProject = query
+ return _q
+}
+
// WithInviter tells the query-builder to eager-load the nodes that are connected to
// the "inviter" edge. The optional arguments are used to configure the query builder of the edge.
func (_q *InvitationQuery) WithInviter(opts ...func(*UserQuery)) *InvitationQuery {
@@ -409,8 +445,9 @@ func (_q *InvitationQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*I
var (
nodes = []*Invitation{}
_spec = _q.querySpec()
- loadedTypes = [2]bool{
+ loadedTypes = [3]bool{
_q.withTeam != nil,
+ _q.withProject != nil,
_q.withInviter != nil,
}
)
@@ -441,6 +478,12 @@ func (_q *InvitationQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*I
return nil, err
}
}
+ if query := _q.withProject; query != nil {
+ if err := _q.loadProject(ctx, query, nodes, nil,
+ func(n *Invitation, e *Project) { n.Edges.Project = e }); err != nil {
+ return nil, err
+ }
+ }
if query := _q.withInviter; query != nil {
if err := _q.loadInviter(ctx, query, nodes, nil,
func(n *Invitation, e *User) { n.Edges.Inviter = e }); err != nil {
@@ -479,6 +522,38 @@ func (_q *InvitationQuery) loadTeam(ctx context.Context, query *TeamQuery, nodes
}
return nil
}
+func (_q *InvitationQuery) loadProject(ctx context.Context, query *ProjectQuery, nodes []*Invitation, init func(*Invitation), assign func(*Invitation, *Project)) error {
+ ids := make([]uuid.UUID, 0, len(nodes))
+ nodeids := make(map[uuid.UUID][]*Invitation)
+ for i := range nodes {
+ if nodes[i].ProjectID == nil {
+ continue
+ }
+ fk := *nodes[i].ProjectID
+ if _, ok := nodeids[fk]; !ok {
+ ids = append(ids, fk)
+ }
+ nodeids[fk] = append(nodeids[fk], nodes[i])
+ }
+ if len(ids) == 0 {
+ return nil
+ }
+ query.Where(project.IDIn(ids...))
+ neighbors, err := query.All(ctx)
+ if err != nil {
+ return err
+ }
+ for _, n := range neighbors {
+ nodes, ok := nodeids[n.ID]
+ if !ok {
+ return fmt.Errorf(`unexpected foreign-key "project_id" returned %v`, n.ID)
+ }
+ for i := range nodes {
+ assign(nodes[i], n)
+ }
+ }
+ return nil
+}
func (_q *InvitationQuery) loadInviter(ctx context.Context, query *UserQuery, nodes []*Invitation, init func(*Invitation), assign func(*Invitation, *User)) error {
ids := make([]uuid.UUID, 0, len(nodes))
nodeids := make(map[uuid.UUID][]*Invitation)
@@ -543,6 +618,9 @@ func (_q *InvitationQuery) querySpec() *sqlgraph.QuerySpec {
if _q.withTeam != nil {
_spec.Node.AddColumnOnce(invitation.FieldTeamID)
}
+ if _q.withProject != nil {
+ _spec.Node.AddColumnOnce(invitation.FieldProjectID)
+ }
if _q.withInviter != nil {
_spec.Node.AddColumnOnce(invitation.FieldInvitedBy)
}
diff --git a/apps/api/ent/invitation_update.go b/apps/api/ent/invitation_update.go
index 9875e4ea0..a954e9018 100644
--- a/apps/api/ent/invitation_update.go
+++ b/apps/api/ent/invitation_update.go
@@ -14,6 +14,7 @@ import (
"github.com/google/uuid"
"github.com/unbindapp/unbind-api/ent/invitation"
"github.com/unbindapp/unbind-api/ent/predicate"
+ "github.com/unbindapp/unbind-api/ent/project"
"github.com/unbindapp/unbind-api/ent/schema"
"github.com/unbindapp/unbind-api/ent/team"
"github.com/unbindapp/unbind-api/ent/user"
@@ -129,6 +130,26 @@ func (_u *InvitationUpdate) SetNillableTeamID(v *uuid.UUID) *InvitationUpdate {
return _u
}
+// SetProjectID sets the "project_id" field.
+func (_u *InvitationUpdate) SetProjectID(v uuid.UUID) *InvitationUpdate {
+ _u.mutation.SetProjectID(v)
+ return _u
+}
+
+// SetNillableProjectID sets the "project_id" field if the given value is not nil.
+func (_u *InvitationUpdate) SetNillableProjectID(v *uuid.UUID) *InvitationUpdate {
+ if v != nil {
+ _u.SetProjectID(*v)
+ }
+ return _u
+}
+
+// ClearProjectID clears the value of the "project_id" field.
+func (_u *InvitationUpdate) ClearProjectID() *InvitationUpdate {
+ _u.mutation.ClearProjectID()
+ return _u
+}
+
// SetInvitedBy sets the "invited_by" field.
func (_u *InvitationUpdate) SetInvitedBy(v uuid.UUID) *InvitationUpdate {
_u.mutation.SetInvitedBy(v)
@@ -154,6 +175,11 @@ func (_u *InvitationUpdate) SetTeam(v *Team) *InvitationUpdate {
return _u.SetTeamID(v.ID)
}
+// SetProject sets the "project" edge to the Project entity.
+func (_u *InvitationUpdate) SetProject(v *Project) *InvitationUpdate {
+ return _u.SetProjectID(v.ID)
+}
+
// SetInviterID sets the "inviter" edge to the User entity by ID.
func (_u *InvitationUpdate) SetInviterID(id uuid.UUID) *InvitationUpdate {
_u.mutation.SetInviterID(id)
@@ -184,6 +210,12 @@ func (_u *InvitationUpdate) ClearTeam() *InvitationUpdate {
return _u
}
+// ClearProject clears the "project" edge to the Project entity.
+func (_u *InvitationUpdate) ClearProject() *InvitationUpdate {
+ _u.mutation.ClearProject()
+ return _u
+}
+
// ClearInviter clears the "inviter" edge to the User entity.
func (_u *InvitationUpdate) ClearInviter() *InvitationUpdate {
_u.mutation.ClearInviter()
@@ -312,6 +344,35 @@ func (_u *InvitationUpdate) sqlSave(ctx context.Context) (_node int, err error)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
+ if _u.mutation.ProjectCleared() {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.M2O,
+ Inverse: true,
+ Table: invitation.ProjectTable,
+ Columns: []string{invitation.ProjectColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(project.FieldID, field.TypeUUID),
+ },
+ }
+ _spec.Edges.Clear = append(_spec.Edges.Clear, edge)
+ }
+ if nodes := _u.mutation.ProjectIDs(); len(nodes) > 0 {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.M2O,
+ Inverse: true,
+ Table: invitation.ProjectTable,
+ Columns: []string{invitation.ProjectColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(project.FieldID, field.TypeUUID),
+ },
+ }
+ for _, k := range nodes {
+ edge.Target.Nodes = append(edge.Target.Nodes, k)
+ }
+ _spec.Edges.Add = append(_spec.Edges.Add, edge)
+ }
if _u.mutation.InviterCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
@@ -459,6 +520,26 @@ func (_u *InvitationUpdateOne) SetNillableTeamID(v *uuid.UUID) *InvitationUpdate
return _u
}
+// SetProjectID sets the "project_id" field.
+func (_u *InvitationUpdateOne) SetProjectID(v uuid.UUID) *InvitationUpdateOne {
+ _u.mutation.SetProjectID(v)
+ return _u
+}
+
+// SetNillableProjectID sets the "project_id" field if the given value is not nil.
+func (_u *InvitationUpdateOne) SetNillableProjectID(v *uuid.UUID) *InvitationUpdateOne {
+ if v != nil {
+ _u.SetProjectID(*v)
+ }
+ return _u
+}
+
+// ClearProjectID clears the value of the "project_id" field.
+func (_u *InvitationUpdateOne) ClearProjectID() *InvitationUpdateOne {
+ _u.mutation.ClearProjectID()
+ return _u
+}
+
// SetInvitedBy sets the "invited_by" field.
func (_u *InvitationUpdateOne) SetInvitedBy(v uuid.UUID) *InvitationUpdateOne {
_u.mutation.SetInvitedBy(v)
@@ -484,6 +565,11 @@ func (_u *InvitationUpdateOne) SetTeam(v *Team) *InvitationUpdateOne {
return _u.SetTeamID(v.ID)
}
+// SetProject sets the "project" edge to the Project entity.
+func (_u *InvitationUpdateOne) SetProject(v *Project) *InvitationUpdateOne {
+ return _u.SetProjectID(v.ID)
+}
+
// SetInviterID sets the "inviter" edge to the User entity by ID.
func (_u *InvitationUpdateOne) SetInviterID(id uuid.UUID) *InvitationUpdateOne {
_u.mutation.SetInviterID(id)
@@ -514,6 +600,12 @@ func (_u *InvitationUpdateOne) ClearTeam() *InvitationUpdateOne {
return _u
}
+// ClearProject clears the "project" edge to the Project entity.
+func (_u *InvitationUpdateOne) ClearProject() *InvitationUpdateOne {
+ _u.mutation.ClearProject()
+ return _u
+}
+
// ClearInviter clears the "inviter" edge to the User entity.
func (_u *InvitationUpdateOne) ClearInviter() *InvitationUpdateOne {
_u.mutation.ClearInviter()
@@ -672,6 +764,35 @@ func (_u *InvitationUpdateOne) sqlSave(ctx context.Context) (_node *Invitation,
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
+ if _u.mutation.ProjectCleared() {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.M2O,
+ Inverse: true,
+ Table: invitation.ProjectTable,
+ Columns: []string{invitation.ProjectColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(project.FieldID, field.TypeUUID),
+ },
+ }
+ _spec.Edges.Clear = append(_spec.Edges.Clear, edge)
+ }
+ if nodes := _u.mutation.ProjectIDs(); len(nodes) > 0 {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.M2O,
+ Inverse: true,
+ Table: invitation.ProjectTable,
+ Columns: []string{invitation.ProjectColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(project.FieldID, field.TypeUUID),
+ },
+ }
+ for _, k := range nodes {
+ edge.Target.Nodes = append(edge.Target.Nodes, k)
+ }
+ _spec.Edges.Add = append(_spec.Edges.Add, edge)
+ }
if _u.mutation.InviterCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
diff --git a/apps/api/ent/migrate/migrations/20261112010707_project_members.sql b/apps/api/ent/migrate/migrations/20261112010707_project_members.sql
new file mode 100644
index 000000000..0c0f1aef5
--- /dev/null
+++ b/apps/api/ent/migrate/migrations/20261112010707_project_members.sql
@@ -0,0 +1,21 @@
+-- +goose Up
+-- modify "groups" table
+ALTER TABLE "groups" ADD COLUMN "project_id" uuid NULL, ADD
+CONSTRAINT "groups_projects_role_groups" FOREIGN KEY ("project_id") REFERENCES "projects" ("id") ON UPDATE NO ACTION ON DELETE CASCADE;
+-- create index "group_project_id_role" to table: "groups"
+CREATE UNIQUE INDEX "group_project_id_role" ON "groups" ("project_id", "role");
+-- modify "invitations" table
+ALTER TABLE "invitations" ADD COLUMN "project_id" uuid NULL, ADD
+CONSTRAINT "invitations_projects_invitations" FOREIGN KEY ("project_id") REFERENCES "projects" ("id") ON UPDATE NO ACTION ON DELETE CASCADE;
+-- create index "invitation_project_id" to table: "invitations"
+CREATE INDEX "invitation_project_id" ON "invitations" ("project_id");
+
+-- +goose Down
+-- reverse: create index "invitation_project_id" to table: "invitations"
+DROP INDEX "invitation_project_id";
+-- reverse: modify "invitations" table
+ALTER TABLE "invitations" DROP CONSTRAINT "invitations_projects_invitations", DROP COLUMN "project_id";
+-- reverse: create index "group_project_id_role" to table: "groups"
+DROP INDEX "group_project_id_role";
+-- reverse: modify "groups" table
+ALTER TABLE "groups" DROP CONSTRAINT "groups_projects_role_groups", DROP COLUMN "project_id";
diff --git a/apps/api/ent/migrate/migrations/atlas.sum b/apps/api/ent/migrate/migrations/atlas.sum
index 260235108..9da7c985f 100644
--- a/apps/api/ent/migrate/migrations/atlas.sum
+++ b/apps/api/ent/migrate/migrations/atlas.sum
@@ -1,4 +1,4 @@
-h1:88VzW9ZeM7lzJqTeQHU/guLgBxH0RumkS9nGuIjLrO8=
+h1:/QqXYC+9aJAFpCLHal37DdzuuX8oHGgs5NmhinoP86s=
20250519010757_initial_migration.sql h1:94lMwKemoNX/ichD+2Vzb7GmOHXVj4qVTfeBInQAe0g=
20250519163449_add_init_containers.sql h1:7bt+zCbtmlYr1QDztgka0R5wUxdjD7XYUkrhL9GYYIQ=
20250521202532_non_nillable_kubernetes_secret.sql h1:eDpMWyeBXh5cG4poavaUMeYs5QXddFBBIyYlxc+nq64=
@@ -48,3 +48,4 @@ h1:88VzW9ZeM7lzJqTeQHU/guLgBxH0RumkS9nGuIjLrO8=
20261017090000_github_app_teams.sql h1:j9IBUD7IDXXorzPAkPqIFuTZ12I9EvrlW3LbXxHUaAY=
20261017152745_network_exceptions.sql h1:8DxllTMyEDZbGzocCwxCkbIyOK7dpxAYdxX07zcqNiQ=
20261017170311_positions.sql h1:Av2PRLP5ffvK4zE9hDQSkGZH62pqqBafNDUZcd9t96U=
+20261112010707_project_members.sql h1:nw4TNm4h+y1TaPXV0pD8vKf3VQDXC0vOW8/CehHVZaw=
diff --git a/apps/api/ent/migrate/schema.go b/apps/api/ent/migrate/schema.go
index 2883fdada..5e832594c 100644
--- a/apps/api/ent/migrate/schema.go
+++ b/apps/api/ent/migrate/schema.go
@@ -224,6 +224,7 @@ var (
{Name: "description", Type: field.TypeString, Nullable: true},
{Name: "k8s_role_name", Type: field.TypeString, Nullable: true},
{Name: "role", Type: field.TypeEnum, Nullable: true, Enums: []string{"admin", "editor", "viewer"}},
+ {Name: "project_id", Type: field.TypeUUID, Nullable: true},
{Name: "team_id", Type: field.TypeUUID, Nullable: true},
}
// GroupsTable holds the schema information for the "groups" table.
@@ -233,8 +234,14 @@ var (
PrimaryKey: []*schema.Column{GroupsColumns[0]},
ForeignKeys: []*schema.ForeignKey{
{
- Symbol: "groups_teams_role_groups",
+ Symbol: "groups_projects_role_groups",
Columns: []*schema.Column{GroupsColumns[7]},
+ RefColumns: []*schema.Column{ProjectsColumns[0]},
+ OnDelete: schema.Cascade,
+ },
+ {
+ Symbol: "groups_teams_role_groups",
+ Columns: []*schema.Column{GroupsColumns[8]},
RefColumns: []*schema.Column{TeamsColumns[0]},
OnDelete: schema.Cascade,
},
@@ -243,6 +250,11 @@ var (
{
Name: "group_team_id_role",
Unique: true,
+ Columns: []*schema.Column{GroupsColumns[8], GroupsColumns[6]},
+ },
+ {
+ Name: "group_project_id_role",
+ Unique: true,
Columns: []*schema.Column{GroupsColumns[7], GroupsColumns[6]},
},
},
@@ -257,6 +269,7 @@ var (
{Name: "role", Type: field.TypeEnum, Enums: []string{"admin", "editor", "viewer"}},
{Name: "expires_at", Type: field.TypeTime},
{Name: "accepted_at", Type: field.TypeTime, Nullable: true},
+ {Name: "project_id", Type: field.TypeUUID, Nullable: true},
{Name: "team_id", Type: field.TypeUUID},
{Name: "invited_by", Type: field.TypeUUID, Nullable: true},
}
@@ -267,14 +280,20 @@ var (
PrimaryKey: []*schema.Column{InvitationsColumns[0]},
ForeignKeys: []*schema.ForeignKey{
{
- Symbol: "invitations_teams_invitations",
+ Symbol: "invitations_projects_invitations",
Columns: []*schema.Column{InvitationsColumns[8]},
+ RefColumns: []*schema.Column{ProjectsColumns[0]},
+ OnDelete: schema.Cascade,
+ },
+ {
+ Symbol: "invitations_teams_invitations",
+ Columns: []*schema.Column{InvitationsColumns[9]},
RefColumns: []*schema.Column{TeamsColumns[0]},
OnDelete: schema.Cascade,
},
{
Symbol: "invitations_users_sent_invitations",
- Columns: []*schema.Column{InvitationsColumns[9]},
+ Columns: []*schema.Column{InvitationsColumns[10]},
RefColumns: []*schema.Column{UsersColumns[0]},
OnDelete: schema.SetNull,
},
@@ -283,6 +302,11 @@ var (
{
Name: "invitation_team_id",
Unique: false,
+ Columns: []*schema.Column{InvitationsColumns[9]},
+ },
+ {
+ Name: "invitation_project_id",
+ Unique: false,
Columns: []*schema.Column{InvitationsColumns[8]},
},
},
@@ -1121,12 +1145,14 @@ func init() {
GithubInstallationsTable.Annotation = &entsql.Annotation{
Table: "github_installations",
}
- GroupsTable.ForeignKeys[0].RefTable = TeamsTable
+ GroupsTable.ForeignKeys[0].RefTable = ProjectsTable
+ GroupsTable.ForeignKeys[1].RefTable = TeamsTable
GroupsTable.Annotation = &entsql.Annotation{
Table: "groups",
}
- InvitationsTable.ForeignKeys[0].RefTable = TeamsTable
- InvitationsTable.ForeignKeys[1].RefTable = UsersTable
+ InvitationsTable.ForeignKeys[0].RefTable = ProjectsTable
+ InvitationsTable.ForeignKeys[1].RefTable = TeamsTable
+ InvitationsTable.ForeignKeys[2].RefTable = UsersTable
InvitationsTable.Annotation = &entsql.Annotation{
Table: "invitations",
}
diff --git a/apps/api/ent/mutation.go b/apps/api/ent/mutation.go
index 6ff340b92..98cca2666 100644
--- a/apps/api/ent/mutation.go
+++ b/apps/api/ent/mutation.go
@@ -6948,6 +6948,8 @@ type GroupMutation struct {
clearedpermissions bool
team *uuid.UUID
clearedteam bool
+ project *uuid.UUID
+ clearedproject bool
done bool
oldValue func(context.Context) (*Group, error)
predicates []predicate.Group
@@ -7312,6 +7314,55 @@ func (m *GroupMutation) ResetTeamID() {
delete(m.clearedFields, group.FieldTeamID)
}
+// SetProjectID sets the "project_id" field.
+func (m *GroupMutation) SetProjectID(u uuid.UUID) {
+ m.project = &u
+}
+
+// ProjectID returns the value of the "project_id" field in the mutation.
+func (m *GroupMutation) ProjectID() (r uuid.UUID, exists bool) {
+ v := m.project
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// OldProjectID returns the old "project_id" field's value of the Group entity.
+// If the Group object wasn't provided to the builder, the object is fetched from the database.
+// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
+func (m *GroupMutation) OldProjectID(ctx context.Context) (v *uuid.UUID, err error) {
+ if !m.op.Is(OpUpdateOne) {
+ return v, errors.New("OldProjectID is only allowed on UpdateOne operations")
+ }
+ if m.id == nil || m.oldValue == nil {
+ return v, errors.New("OldProjectID requires an ID field in the mutation")
+ }
+ oldValue, err := m.oldValue(ctx)
+ if err != nil {
+ return v, fmt.Errorf("querying old value for OldProjectID: %w", err)
+ }
+ return oldValue.ProjectID, nil
+}
+
+// ClearProjectID clears the value of the "project_id" field.
+func (m *GroupMutation) ClearProjectID() {
+ m.project = nil
+ m.clearedFields[group.FieldProjectID] = struct{}{}
+}
+
+// ProjectIDCleared returns if the "project_id" field was cleared in this mutation.
+func (m *GroupMutation) ProjectIDCleared() bool {
+ _, ok := m.clearedFields[group.FieldProjectID]
+ return ok
+}
+
+// ResetProjectID resets all changes to the "project_id" field.
+func (m *GroupMutation) ResetProjectID() {
+ m.project = nil
+ delete(m.clearedFields, group.FieldProjectID)
+}
+
// SetRole sets the "role" field.
func (m *GroupMutation) SetRole(sa schema.PermittedAction) {
m.role = &sa
@@ -7496,6 +7547,33 @@ func (m *GroupMutation) ResetTeam() {
m.clearedteam = false
}
+// ClearProject clears the "project" edge to the Project entity.
+func (m *GroupMutation) ClearProject() {
+ m.clearedproject = true
+ m.clearedFields[group.FieldProjectID] = struct{}{}
+}
+
+// ProjectCleared reports if the "project" edge to the Project entity was cleared.
+func (m *GroupMutation) ProjectCleared() bool {
+ return m.ProjectIDCleared() || m.clearedproject
+}
+
+// ProjectIDs returns the "project" edge IDs in the mutation.
+// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use
+// ProjectID instead. It exists only for internal usage by the builders.
+func (m *GroupMutation) ProjectIDs() (ids []uuid.UUID) {
+ if id := m.project; id != nil {
+ ids = append(ids, *id)
+ }
+ return
+}
+
+// ResetProject resets all changes to the "project" edge.
+func (m *GroupMutation) ResetProject() {
+ m.project = nil
+ m.clearedproject = false
+}
+
// Where appends a list predicates to the GroupMutation builder.
func (m *GroupMutation) Where(ps ...predicate.Group) {
m.predicates = append(m.predicates, ps...)
@@ -7530,7 +7608,7 @@ func (m *GroupMutation) Type() string {
// order to get all numeric fields that were incremented/decremented, call
// AddedFields().
func (m *GroupMutation) Fields() []string {
- fields := make([]string, 0, 7)
+ fields := make([]string, 0, 8)
if m.created_at != nil {
fields = append(fields, group.FieldCreatedAt)
}
@@ -7549,6 +7627,9 @@ func (m *GroupMutation) Fields() []string {
if m.team != nil {
fields = append(fields, group.FieldTeamID)
}
+ if m.project != nil {
+ fields = append(fields, group.FieldProjectID)
+ }
if m.role != nil {
fields = append(fields, group.FieldRole)
}
@@ -7572,6 +7653,8 @@ func (m *GroupMutation) Field(name string) (ent.Value, bool) {
return m.K8sRoleName()
case group.FieldTeamID:
return m.TeamID()
+ case group.FieldProjectID:
+ return m.ProjectID()
case group.FieldRole:
return m.Role()
}
@@ -7595,6 +7678,8 @@ func (m *GroupMutation) OldField(ctx context.Context, name string) (ent.Value, e
return m.OldK8sRoleName(ctx)
case group.FieldTeamID:
return m.OldTeamID(ctx)
+ case group.FieldProjectID:
+ return m.OldProjectID(ctx)
case group.FieldRole:
return m.OldRole(ctx)
}
@@ -7648,6 +7733,13 @@ func (m *GroupMutation) SetField(name string, value ent.Value) error {
}
m.SetTeamID(v)
return nil
+ case group.FieldProjectID:
+ v, ok := value.(uuid.UUID)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetProjectID(v)
+ return nil
case group.FieldRole:
v, ok := value.(schema.PermittedAction)
if !ok {
@@ -7694,6 +7786,9 @@ func (m *GroupMutation) ClearedFields() []string {
if m.FieldCleared(group.FieldTeamID) {
fields = append(fields, group.FieldTeamID)
}
+ if m.FieldCleared(group.FieldProjectID) {
+ fields = append(fields, group.FieldProjectID)
+ }
if m.FieldCleared(group.FieldRole) {
fields = append(fields, group.FieldRole)
}
@@ -7720,6 +7815,9 @@ func (m *GroupMutation) ClearField(name string) error {
case group.FieldTeamID:
m.ClearTeamID()
return nil
+ case group.FieldProjectID:
+ m.ClearProjectID()
+ return nil
case group.FieldRole:
m.ClearRole()
return nil
@@ -7749,6 +7847,9 @@ func (m *GroupMutation) ResetField(name string) error {
case group.FieldTeamID:
m.ResetTeamID()
return nil
+ case group.FieldProjectID:
+ m.ResetProjectID()
+ return nil
case group.FieldRole:
m.ResetRole()
return nil
@@ -7758,7 +7859,7 @@ func (m *GroupMutation) ResetField(name string) error {
// AddedEdges returns all edge names that were set/added in this mutation.
func (m *GroupMutation) AddedEdges() []string {
- edges := make([]string, 0, 3)
+ edges := make([]string, 0, 4)
if m.users != nil {
edges = append(edges, group.EdgeUsers)
}
@@ -7768,6 +7869,9 @@ func (m *GroupMutation) AddedEdges() []string {
if m.team != nil {
edges = append(edges, group.EdgeTeam)
}
+ if m.project != nil {
+ edges = append(edges, group.EdgeProject)
+ }
return edges
}
@@ -7791,13 +7895,17 @@ func (m *GroupMutation) AddedIDs(name string) []ent.Value {
if id := m.team; id != nil {
return []ent.Value{*id}
}
+ case group.EdgeProject:
+ if id := m.project; id != nil {
+ return []ent.Value{*id}
+ }
}
return nil
}
// RemovedEdges returns all edge names that were removed in this mutation.
func (m *GroupMutation) RemovedEdges() []string {
- edges := make([]string, 0, 3)
+ edges := make([]string, 0, 4)
if m.removedusers != nil {
edges = append(edges, group.EdgeUsers)
}
@@ -7829,7 +7937,7 @@ func (m *GroupMutation) RemovedIDs(name string) []ent.Value {
// ClearedEdges returns all edge names that were cleared in this mutation.
func (m *GroupMutation) ClearedEdges() []string {
- edges := make([]string, 0, 3)
+ edges := make([]string, 0, 4)
if m.clearedusers {
edges = append(edges, group.EdgeUsers)
}
@@ -7839,6 +7947,9 @@ func (m *GroupMutation) ClearedEdges() []string {
if m.clearedteam {
edges = append(edges, group.EdgeTeam)
}
+ if m.clearedproject {
+ edges = append(edges, group.EdgeProject)
+ }
return edges
}
@@ -7852,6 +7963,8 @@ func (m *GroupMutation) EdgeCleared(name string) bool {
return m.clearedpermissions
case group.EdgeTeam:
return m.clearedteam
+ case group.EdgeProject:
+ return m.clearedproject
}
return false
}
@@ -7863,6 +7976,9 @@ func (m *GroupMutation) ClearEdge(name string) error {
case group.EdgeTeam:
m.ClearTeam()
return nil
+ case group.EdgeProject:
+ m.ClearProject()
+ return nil
}
return fmt.Errorf("unknown Group unique edge %s", name)
}
@@ -7880,6 +7996,9 @@ func (m *GroupMutation) ResetEdge(name string) error {
case group.EdgeTeam:
m.ResetTeam()
return nil
+ case group.EdgeProject:
+ m.ResetProject()
+ return nil
}
return fmt.Errorf("unknown Group edge %s", name)
}
@@ -7900,6 +8019,8 @@ type InvitationMutation struct {
clearedFields map[string]struct{}
team *uuid.UUID
clearedteam bool
+ project *uuid.UUID
+ clearedproject bool
inviter *uuid.UUID
clearedinviter bool
done bool
@@ -8312,6 +8433,55 @@ func (m *InvitationMutation) ResetTeamID() {
m.team = nil
}
+// SetProjectID sets the "project_id" field.
+func (m *InvitationMutation) SetProjectID(u uuid.UUID) {
+ m.project = &u
+}
+
+// ProjectID returns the value of the "project_id" field in the mutation.
+func (m *InvitationMutation) ProjectID() (r uuid.UUID, exists bool) {
+ v := m.project
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// OldProjectID returns the old "project_id" field's value of the Invitation entity.
+// If the Invitation object wasn't provided to the builder, the object is fetched from the database.
+// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
+func (m *InvitationMutation) OldProjectID(ctx context.Context) (v *uuid.UUID, err error) {
+ if !m.op.Is(OpUpdateOne) {
+ return v, errors.New("OldProjectID is only allowed on UpdateOne operations")
+ }
+ if m.id == nil || m.oldValue == nil {
+ return v, errors.New("OldProjectID requires an ID field in the mutation")
+ }
+ oldValue, err := m.oldValue(ctx)
+ if err != nil {
+ return v, fmt.Errorf("querying old value for OldProjectID: %w", err)
+ }
+ return oldValue.ProjectID, nil
+}
+
+// ClearProjectID clears the value of the "project_id" field.
+func (m *InvitationMutation) ClearProjectID() {
+ m.project = nil
+ m.clearedFields[invitation.FieldProjectID] = struct{}{}
+}
+
+// ProjectIDCleared returns if the "project_id" field was cleared in this mutation.
+func (m *InvitationMutation) ProjectIDCleared() bool {
+ _, ok := m.clearedFields[invitation.FieldProjectID]
+ return ok
+}
+
+// ResetProjectID resets all changes to the "project_id" field.
+func (m *InvitationMutation) ResetProjectID() {
+ m.project = nil
+ delete(m.clearedFields, invitation.FieldProjectID)
+}
+
// SetInvitedBy sets the "invited_by" field.
func (m *InvitationMutation) SetInvitedBy(u uuid.UUID) {
m.inviter = &u
@@ -8388,6 +8558,33 @@ func (m *InvitationMutation) ResetTeam() {
m.clearedteam = false
}
+// ClearProject clears the "project" edge to the Project entity.
+func (m *InvitationMutation) ClearProject() {
+ m.clearedproject = true
+ m.clearedFields[invitation.FieldProjectID] = struct{}{}
+}
+
+// ProjectCleared reports if the "project" edge to the Project entity was cleared.
+func (m *InvitationMutation) ProjectCleared() bool {
+ return m.ProjectIDCleared() || m.clearedproject
+}
+
+// ProjectIDs returns the "project" edge IDs in the mutation.
+// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use
+// ProjectID instead. It exists only for internal usage by the builders.
+func (m *InvitationMutation) ProjectIDs() (ids []uuid.UUID) {
+ if id := m.project; id != nil {
+ ids = append(ids, *id)
+ }
+ return
+}
+
+// ResetProject resets all changes to the "project" edge.
+func (m *InvitationMutation) ResetProject() {
+ m.project = nil
+ m.clearedproject = false
+}
+
// SetInviterID sets the "inviter" edge to the User entity by id.
func (m *InvitationMutation) SetInviterID(id uuid.UUID) {
m.inviter = &id
@@ -8462,7 +8659,7 @@ func (m *InvitationMutation) Type() string {
// order to get all numeric fields that were incremented/decremented, call
// AddedFields().
func (m *InvitationMutation) Fields() []string {
- fields := make([]string, 0, 9)
+ fields := make([]string, 0, 10)
if m.created_at != nil {
fields = append(fields, invitation.FieldCreatedAt)
}
@@ -8487,6 +8684,9 @@ func (m *InvitationMutation) Fields() []string {
if m.team != nil {
fields = append(fields, invitation.FieldTeamID)
}
+ if m.project != nil {
+ fields = append(fields, invitation.FieldProjectID)
+ }
if m.inviter != nil {
fields = append(fields, invitation.FieldInvitedBy)
}
@@ -8514,6 +8714,8 @@ func (m *InvitationMutation) Field(name string) (ent.Value, bool) {
return m.AcceptedAt()
case invitation.FieldTeamID:
return m.TeamID()
+ case invitation.FieldProjectID:
+ return m.ProjectID()
case invitation.FieldInvitedBy:
return m.InvitedBy()
}
@@ -8541,6 +8743,8 @@ func (m *InvitationMutation) OldField(ctx context.Context, name string) (ent.Val
return m.OldAcceptedAt(ctx)
case invitation.FieldTeamID:
return m.OldTeamID(ctx)
+ case invitation.FieldProjectID:
+ return m.OldProjectID(ctx)
case invitation.FieldInvitedBy:
return m.OldInvitedBy(ctx)
}
@@ -8608,6 +8812,13 @@ func (m *InvitationMutation) SetField(name string, value ent.Value) error {
}
m.SetTeamID(v)
return nil
+ case invitation.FieldProjectID:
+ v, ok := value.(uuid.UUID)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetProjectID(v)
+ return nil
case invitation.FieldInvitedBy:
v, ok := value.(uuid.UUID)
if !ok {
@@ -8648,6 +8859,9 @@ func (m *InvitationMutation) ClearedFields() []string {
if m.FieldCleared(invitation.FieldAcceptedAt) {
fields = append(fields, invitation.FieldAcceptedAt)
}
+ if m.FieldCleared(invitation.FieldProjectID) {
+ fields = append(fields, invitation.FieldProjectID)
+ }
if m.FieldCleared(invitation.FieldInvitedBy) {
fields = append(fields, invitation.FieldInvitedBy)
}
@@ -8668,6 +8882,9 @@ func (m *InvitationMutation) ClearField(name string) error {
case invitation.FieldAcceptedAt:
m.ClearAcceptedAt()
return nil
+ case invitation.FieldProjectID:
+ m.ClearProjectID()
+ return nil
case invitation.FieldInvitedBy:
m.ClearInvitedBy()
return nil
@@ -8703,6 +8920,9 @@ func (m *InvitationMutation) ResetField(name string) error {
case invitation.FieldTeamID:
m.ResetTeamID()
return nil
+ case invitation.FieldProjectID:
+ m.ResetProjectID()
+ return nil
case invitation.FieldInvitedBy:
m.ResetInvitedBy()
return nil
@@ -8712,10 +8932,13 @@ func (m *InvitationMutation) ResetField(name string) error {
// AddedEdges returns all edge names that were set/added in this mutation.
func (m *InvitationMutation) AddedEdges() []string {
- edges := make([]string, 0, 2)
+ edges := make([]string, 0, 3)
if m.team != nil {
edges = append(edges, invitation.EdgeTeam)
}
+ if m.project != nil {
+ edges = append(edges, invitation.EdgeProject)
+ }
if m.inviter != nil {
edges = append(edges, invitation.EdgeInviter)
}
@@ -8730,6 +8953,10 @@ func (m *InvitationMutation) AddedIDs(name string) []ent.Value {
if id := m.team; id != nil {
return []ent.Value{*id}
}
+ case invitation.EdgeProject:
+ if id := m.project; id != nil {
+ return []ent.Value{*id}
+ }
case invitation.EdgeInviter:
if id := m.inviter; id != nil {
return []ent.Value{*id}
@@ -8740,7 +8967,7 @@ func (m *InvitationMutation) AddedIDs(name string) []ent.Value {
// RemovedEdges returns all edge names that were removed in this mutation.
func (m *InvitationMutation) RemovedEdges() []string {
- edges := make([]string, 0, 2)
+ edges := make([]string, 0, 3)
return edges
}
@@ -8752,10 +8979,13 @@ func (m *InvitationMutation) RemovedIDs(name string) []ent.Value {
// ClearedEdges returns all edge names that were cleared in this mutation.
func (m *InvitationMutation) ClearedEdges() []string {
- edges := make([]string, 0, 2)
+ edges := make([]string, 0, 3)
if m.clearedteam {
edges = append(edges, invitation.EdgeTeam)
}
+ if m.clearedproject {
+ edges = append(edges, invitation.EdgeProject)
+ }
if m.clearedinviter {
edges = append(edges, invitation.EdgeInviter)
}
@@ -8768,6 +8998,8 @@ func (m *InvitationMutation) EdgeCleared(name string) bool {
switch name {
case invitation.EdgeTeam:
return m.clearedteam
+ case invitation.EdgeProject:
+ return m.clearedproject
case invitation.EdgeInviter:
return m.clearedinviter
}
@@ -8781,6 +9013,9 @@ func (m *InvitationMutation) ClearEdge(name string) error {
case invitation.EdgeTeam:
m.ClearTeam()
return nil
+ case invitation.EdgeProject:
+ m.ClearProject()
+ return nil
case invitation.EdgeInviter:
m.ClearInviter()
return nil
@@ -8795,6 +9030,9 @@ func (m *InvitationMutation) ResetEdge(name string) error {
case invitation.EdgeTeam:
m.ResetTeam()
return nil
+ case invitation.EdgeProject:
+ m.ResetProject()
+ return nil
case invitation.EdgeInviter:
m.ResetInviter()
return nil
@@ -16215,6 +16453,12 @@ type ProjectMutation struct {
project_webhooks map[uuid.UUID]struct{}
removedproject_webhooks map[uuid.UUID]struct{}
clearedproject_webhooks bool
+ role_groups map[uuid.UUID]struct{}
+ removedrole_groups map[uuid.UUID]struct{}
+ clearedrole_groups bool
+ invitations map[uuid.UUID]struct{}
+ removedinvitations map[uuid.UUID]struct{}
+ clearedinvitations bool
done bool
oldValue func(context.Context) (*Project, error)
predicates []predicate.Project
@@ -16957,6 +17201,114 @@ func (m *ProjectMutation) ResetProjectWebhooks() {
m.removedproject_webhooks = nil
}
+// AddRoleGroupIDs adds the "role_groups" edge to the Group entity by ids.
+func (m *ProjectMutation) AddRoleGroupIDs(ids ...uuid.UUID) {
+ if m.role_groups == nil {
+ m.role_groups = make(map[uuid.UUID]struct{})
+ }
+ for i := range ids {
+ m.role_groups[ids[i]] = struct{}{}
+ }
+}
+
+// ClearRoleGroups clears the "role_groups" edge to the Group entity.
+func (m *ProjectMutation) ClearRoleGroups() {
+ m.clearedrole_groups = true
+}
+
+// RoleGroupsCleared reports if the "role_groups" edge to the Group entity was cleared.
+func (m *ProjectMutation) RoleGroupsCleared() bool {
+ return m.clearedrole_groups
+}
+
+// RemoveRoleGroupIDs removes the "role_groups" edge to the Group entity by IDs.
+func (m *ProjectMutation) RemoveRoleGroupIDs(ids ...uuid.UUID) {
+ if m.removedrole_groups == nil {
+ m.removedrole_groups = make(map[uuid.UUID]struct{})
+ }
+ for i := range ids {
+ delete(m.role_groups, ids[i])
+ m.removedrole_groups[ids[i]] = struct{}{}
+ }
+}
+
+// RemovedRoleGroups returns the removed IDs of the "role_groups" edge to the Group entity.
+func (m *ProjectMutation) RemovedRoleGroupsIDs() (ids []uuid.UUID) {
+ for id := range m.removedrole_groups {
+ ids = append(ids, id)
+ }
+ return
+}
+
+// RoleGroupsIDs returns the "role_groups" edge IDs in the mutation.
+func (m *ProjectMutation) RoleGroupsIDs() (ids []uuid.UUID) {
+ for id := range m.role_groups {
+ ids = append(ids, id)
+ }
+ return
+}
+
+// ResetRoleGroups resets all changes to the "role_groups" edge.
+func (m *ProjectMutation) ResetRoleGroups() {
+ m.role_groups = nil
+ m.clearedrole_groups = false
+ m.removedrole_groups = nil
+}
+
+// AddInvitationIDs adds the "invitations" edge to the Invitation entity by ids.
+func (m *ProjectMutation) AddInvitationIDs(ids ...uuid.UUID) {
+ if m.invitations == nil {
+ m.invitations = make(map[uuid.UUID]struct{})
+ }
+ for i := range ids {
+ m.invitations[ids[i]] = struct{}{}
+ }
+}
+
+// ClearInvitations clears the "invitations" edge to the Invitation entity.
+func (m *ProjectMutation) ClearInvitations() {
+ m.clearedinvitations = true
+}
+
+// InvitationsCleared reports if the "invitations" edge to the Invitation entity was cleared.
+func (m *ProjectMutation) InvitationsCleared() bool {
+ return m.clearedinvitations
+}
+
+// RemoveInvitationIDs removes the "invitations" edge to the Invitation entity by IDs.
+func (m *ProjectMutation) RemoveInvitationIDs(ids ...uuid.UUID) {
+ if m.removedinvitations == nil {
+ m.removedinvitations = make(map[uuid.UUID]struct{})
+ }
+ for i := range ids {
+ delete(m.invitations, ids[i])
+ m.removedinvitations[ids[i]] = struct{}{}
+ }
+}
+
+// RemovedInvitations returns the removed IDs of the "invitations" edge to the Invitation entity.
+func (m *ProjectMutation) RemovedInvitationsIDs() (ids []uuid.UUID) {
+ for id := range m.removedinvitations {
+ ids = append(ids, id)
+ }
+ return
+}
+
+// InvitationsIDs returns the "invitations" edge IDs in the mutation.
+func (m *ProjectMutation) InvitationsIDs() (ids []uuid.UUID) {
+ for id := range m.invitations {
+ ids = append(ids, id)
+ }
+ return
+}
+
+// ResetInvitations resets all changes to the "invitations" edge.
+func (m *ProjectMutation) ResetInvitations() {
+ m.invitations = nil
+ m.clearedinvitations = false
+ m.removedinvitations = nil
+}
+
// Where appends a list predicates to the ProjectMutation builder.
func (m *ProjectMutation) Where(ps ...predicate.Project) {
m.predicates = append(m.predicates, ps...)
@@ -17296,7 +17648,7 @@ func (m *ProjectMutation) ResetField(name string) error {
// AddedEdges returns all edge names that were set/added in this mutation.
func (m *ProjectMutation) AddedEdges() []string {
- edges := make([]string, 0, 4)
+ edges := make([]string, 0, 6)
if m.team != nil {
edges = append(edges, project.EdgeTeam)
}
@@ -17309,6 +17661,12 @@ func (m *ProjectMutation) AddedEdges() []string {
if m.project_webhooks != nil {
edges = append(edges, project.EdgeProjectWebhooks)
}
+ if m.role_groups != nil {
+ edges = append(edges, project.EdgeRoleGroups)
+ }
+ if m.invitations != nil {
+ edges = append(edges, project.EdgeInvitations)
+ }
return edges
}
@@ -17336,19 +17694,37 @@ func (m *ProjectMutation) AddedIDs(name string) []ent.Value {
ids = append(ids, id)
}
return ids
+ case project.EdgeRoleGroups:
+ ids := make([]ent.Value, 0, len(m.role_groups))
+ for id := range m.role_groups {
+ ids = append(ids, id)
+ }
+ return ids
+ case project.EdgeInvitations:
+ ids := make([]ent.Value, 0, len(m.invitations))
+ for id := range m.invitations {
+ ids = append(ids, id)
+ }
+ return ids
}
return nil
}
// RemovedEdges returns all edge names that were removed in this mutation.
func (m *ProjectMutation) RemovedEdges() []string {
- edges := make([]string, 0, 4)
+ edges := make([]string, 0, 6)
if m.removedenvironments != nil {
edges = append(edges, project.EdgeEnvironments)
}
if m.removedproject_webhooks != nil {
edges = append(edges, project.EdgeProjectWebhooks)
}
+ if m.removedrole_groups != nil {
+ edges = append(edges, project.EdgeRoleGroups)
+ }
+ if m.removedinvitations != nil {
+ edges = append(edges, project.EdgeInvitations)
+ }
return edges
}
@@ -17368,13 +17744,25 @@ func (m *ProjectMutation) RemovedIDs(name string) []ent.Value {
ids = append(ids, id)
}
return ids
+ case project.EdgeRoleGroups:
+ ids := make([]ent.Value, 0, len(m.removedrole_groups))
+ for id := range m.removedrole_groups {
+ ids = append(ids, id)
+ }
+ return ids
+ case project.EdgeInvitations:
+ ids := make([]ent.Value, 0, len(m.removedinvitations))
+ for id := range m.removedinvitations {
+ ids = append(ids, id)
+ }
+ return ids
}
return nil
}
// ClearedEdges returns all edge names that were cleared in this mutation.
func (m *ProjectMutation) ClearedEdges() []string {
- edges := make([]string, 0, 4)
+ edges := make([]string, 0, 6)
if m.clearedteam {
edges = append(edges, project.EdgeTeam)
}
@@ -17387,6 +17775,12 @@ func (m *ProjectMutation) ClearedEdges() []string {
if m.clearedproject_webhooks {
edges = append(edges, project.EdgeProjectWebhooks)
}
+ if m.clearedrole_groups {
+ edges = append(edges, project.EdgeRoleGroups)
+ }
+ if m.clearedinvitations {
+ edges = append(edges, project.EdgeInvitations)
+ }
return edges
}
@@ -17402,6 +17796,10 @@ func (m *ProjectMutation) EdgeCleared(name string) bool {
return m.cleareddefault_environment
case project.EdgeProjectWebhooks:
return m.clearedproject_webhooks
+ case project.EdgeRoleGroups:
+ return m.clearedrole_groups
+ case project.EdgeInvitations:
+ return m.clearedinvitations
}
return false
}
@@ -17436,6 +17834,12 @@ func (m *ProjectMutation) ResetEdge(name string) error {
case project.EdgeProjectWebhooks:
m.ResetProjectWebhooks()
return nil
+ case project.EdgeRoleGroups:
+ m.ResetRoleGroups()
+ return nil
+ case project.EdgeInvitations:
+ m.ResetInvitations()
+ return nil
}
return fmt.Errorf("unknown Project edge %s", name)
}
diff --git a/apps/api/ent/project.go b/apps/api/ent/project.go
index 3465aa7da..8ec70d425 100644
--- a/apps/api/ent/project.go
+++ b/apps/api/ent/project.go
@@ -60,9 +60,13 @@ type ProjectEdges struct {
DefaultEnvironment *Environment `json:"default_environment,omitempty"`
// ProjectWebhooks holds the value of the project_webhooks edge.
ProjectWebhooks []*Webhook `json:"project_webhooks,omitempty"`
+ // RoleGroups holds the value of the role_groups edge.
+ RoleGroups []*Group `json:"role_groups,omitempty"`
+ // Invitations holds the value of the invitations edge.
+ Invitations []*Invitation `json:"invitations,omitempty"`
// loadedTypes holds the information for reporting if a
// type was loaded (or requested) in eager-loading or not.
- loadedTypes [4]bool
+ loadedTypes [6]bool
}
// TeamOrErr returns the Team value or an error if the edge
@@ -105,6 +109,24 @@ func (e ProjectEdges) ProjectWebhooksOrErr() ([]*Webhook, error) {
return nil, &NotLoadedError{edge: "project_webhooks"}
}
+// RoleGroupsOrErr returns the RoleGroups value or an error if the edge
+// was not loaded in eager-loading.
+func (e ProjectEdges) RoleGroupsOrErr() ([]*Group, error) {
+ if e.loadedTypes[4] {
+ return e.RoleGroups, nil
+ }
+ return nil, &NotLoadedError{edge: "role_groups"}
+}
+
+// InvitationsOrErr returns the Invitations value or an error if the edge
+// was not loaded in eager-loading.
+func (e ProjectEdges) InvitationsOrErr() ([]*Invitation, error) {
+ if e.loadedTypes[5] {
+ return e.Invitations, nil
+ }
+ return nil, &NotLoadedError{edge: "invitations"}
+}
+
// scanValues returns the types for scanning values from sql.Rows.
func (*Project) scanValues(columns []string) ([]any, error) {
values := make([]any, len(columns))
@@ -246,6 +268,16 @@ func (_m *Project) QueryProjectWebhooks() *WebhookQuery {
return NewProjectClient(_m.config).QueryProjectWebhooks(_m)
}
+// QueryRoleGroups queries the "role_groups" edge of the Project entity.
+func (_m *Project) QueryRoleGroups() *GroupQuery {
+ return NewProjectClient(_m.config).QueryRoleGroups(_m)
+}
+
+// QueryInvitations queries the "invitations" edge of the Project entity.
+func (_m *Project) QueryInvitations() *InvitationQuery {
+ return NewProjectClient(_m.config).QueryInvitations(_m)
+}
+
// Update returns a builder for updating this Project.
// Note that you need to call Project.Unwrap() before calling this method if this Project
// was returned from a transaction, and the transaction was committed or rolled back.
diff --git a/apps/api/ent/project/project.go b/apps/api/ent/project/project.go
index 5df3654c0..34024492b 100644
--- a/apps/api/ent/project/project.go
+++ b/apps/api/ent/project/project.go
@@ -45,6 +45,10 @@ const (
EdgeDefaultEnvironment = "default_environment"
// EdgeProjectWebhooks holds the string denoting the project_webhooks edge name in mutations.
EdgeProjectWebhooks = "project_webhooks"
+ // EdgeRoleGroups holds the string denoting the role_groups edge name in mutations.
+ EdgeRoleGroups = "role_groups"
+ // EdgeInvitations holds the string denoting the invitations edge name in mutations.
+ EdgeInvitations = "invitations"
// Table holds the table name of the project in the database.
Table = "projects"
// TeamTable is the table that holds the team relation/edge.
@@ -75,6 +79,20 @@ const (
ProjectWebhooksInverseTable = "webhooks"
// ProjectWebhooksColumn is the table column denoting the project_webhooks relation/edge.
ProjectWebhooksColumn = "project_id"
+ // RoleGroupsTable is the table that holds the role_groups relation/edge.
+ RoleGroupsTable = "groups"
+ // RoleGroupsInverseTable is the table name for the Group entity.
+ // It exists in this package in order to avoid circular dependency with the "group" package.
+ RoleGroupsInverseTable = "groups"
+ // RoleGroupsColumn is the table column denoting the role_groups relation/edge.
+ RoleGroupsColumn = "project_id"
+ // InvitationsTable is the table that holds the invitations relation/edge.
+ InvitationsTable = "invitations"
+ // InvitationsInverseTable is the table name for the Invitation entity.
+ // It exists in this package in order to avoid circular dependency with the "invitation" package.
+ InvitationsInverseTable = "invitations"
+ // InvitationsColumn is the table column denoting the invitations relation/edge.
+ InvitationsColumn = "project_id"
)
// Columns holds all SQL columns for project fields.
@@ -219,6 +237,34 @@ func ByProjectWebhooks(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption {
sqlgraph.OrderByNeighborTerms(s, newProjectWebhooksStep(), append([]sql.OrderTerm{term}, terms...)...)
}
}
+
+// ByRoleGroupsCount orders the results by role_groups count.
+func ByRoleGroupsCount(opts ...sql.OrderTermOption) OrderOption {
+ return func(s *sql.Selector) {
+ sqlgraph.OrderByNeighborsCount(s, newRoleGroupsStep(), opts...)
+ }
+}
+
+// ByRoleGroups orders the results by role_groups terms.
+func ByRoleGroups(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption {
+ return func(s *sql.Selector) {
+ sqlgraph.OrderByNeighborTerms(s, newRoleGroupsStep(), append([]sql.OrderTerm{term}, terms...)...)
+ }
+}
+
+// ByInvitationsCount orders the results by invitations count.
+func ByInvitationsCount(opts ...sql.OrderTermOption) OrderOption {
+ return func(s *sql.Selector) {
+ sqlgraph.OrderByNeighborsCount(s, newInvitationsStep(), opts...)
+ }
+}
+
+// ByInvitations orders the results by invitations terms.
+func ByInvitations(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption {
+ return func(s *sql.Selector) {
+ sqlgraph.OrderByNeighborTerms(s, newInvitationsStep(), append([]sql.OrderTerm{term}, terms...)...)
+ }
+}
func newTeamStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
@@ -247,3 +293,17 @@ func newProjectWebhooksStep() *sqlgraph.Step {
sqlgraph.Edge(sqlgraph.O2M, false, ProjectWebhooksTable, ProjectWebhooksColumn),
)
}
+func newRoleGroupsStep() *sqlgraph.Step {
+ return sqlgraph.NewStep(
+ sqlgraph.From(Table, FieldID),
+ sqlgraph.To(RoleGroupsInverseTable, FieldID),
+ sqlgraph.Edge(sqlgraph.O2M, false, RoleGroupsTable, RoleGroupsColumn),
+ )
+}
+func newInvitationsStep() *sqlgraph.Step {
+ return sqlgraph.NewStep(
+ sqlgraph.From(Table, FieldID),
+ sqlgraph.To(InvitationsInverseTable, FieldID),
+ sqlgraph.Edge(sqlgraph.O2M, false, InvitationsTable, InvitationsColumn),
+ )
+}
diff --git a/apps/api/ent/project/where.go b/apps/api/ent/project/where.go
index f93f4676d..c522bc725 100644
--- a/apps/api/ent/project/where.go
+++ b/apps/api/ent/project/where.go
@@ -713,6 +713,52 @@ func HasProjectWebhooksWith(preds ...predicate.Webhook) predicate.Project {
})
}
+// HasRoleGroups applies the HasEdge predicate on the "role_groups" edge.
+func HasRoleGroups() predicate.Project {
+ return predicate.Project(func(s *sql.Selector) {
+ step := sqlgraph.NewStep(
+ sqlgraph.From(Table, FieldID),
+ sqlgraph.Edge(sqlgraph.O2M, false, RoleGroupsTable, RoleGroupsColumn),
+ )
+ sqlgraph.HasNeighbors(s, step)
+ })
+}
+
+// HasRoleGroupsWith applies the HasEdge predicate on the "role_groups" edge with a given conditions (other predicates).
+func HasRoleGroupsWith(preds ...predicate.Group) predicate.Project {
+ return predicate.Project(func(s *sql.Selector) {
+ step := newRoleGroupsStep()
+ sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
+ for _, p := range preds {
+ p(s)
+ }
+ })
+ })
+}
+
+// HasInvitations applies the HasEdge predicate on the "invitations" edge.
+func HasInvitations() predicate.Project {
+ return predicate.Project(func(s *sql.Selector) {
+ step := sqlgraph.NewStep(
+ sqlgraph.From(Table, FieldID),
+ sqlgraph.Edge(sqlgraph.O2M, false, InvitationsTable, InvitationsColumn),
+ )
+ sqlgraph.HasNeighbors(s, step)
+ })
+}
+
+// HasInvitationsWith applies the HasEdge predicate on the "invitations" edge with a given conditions (other predicates).
+func HasInvitationsWith(preds ...predicate.Invitation) predicate.Project {
+ return predicate.Project(func(s *sql.Selector) {
+ step := newInvitationsStep()
+ sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
+ for _, p := range preds {
+ p(s)
+ }
+ })
+ })
+}
+
// And groups predicates with the AND operator between them.
func And(predicates ...predicate.Project) predicate.Project {
return predicate.Project(sql.AndPredicates(predicates...))
diff --git a/apps/api/ent/project_create.go b/apps/api/ent/project_create.go
index 513652cd9..d759be532 100644
--- a/apps/api/ent/project_create.go
+++ b/apps/api/ent/project_create.go
@@ -14,6 +14,8 @@ import (
"entgo.io/ent/schema/field"
"github.com/google/uuid"
"github.com/unbindapp/unbind-api/ent/environment"
+ "github.com/unbindapp/unbind-api/ent/group"
+ "github.com/unbindapp/unbind-api/ent/invitation"
"github.com/unbindapp/unbind-api/ent/project"
"github.com/unbindapp/unbind-api/ent/team"
"github.com/unbindapp/unbind-api/ent/webhook"
@@ -195,6 +197,36 @@ func (_c *ProjectCreate) AddProjectWebhooks(v ...*Webhook) *ProjectCreate {
return _c.AddProjectWebhookIDs(ids...)
}
+// AddRoleGroupIDs adds the "role_groups" edge to the Group entity by IDs.
+func (_c *ProjectCreate) AddRoleGroupIDs(ids ...uuid.UUID) *ProjectCreate {
+ _c.mutation.AddRoleGroupIDs(ids...)
+ return _c
+}
+
+// AddRoleGroups adds the "role_groups" edges to the Group entity.
+func (_c *ProjectCreate) AddRoleGroups(v ...*Group) *ProjectCreate {
+ ids := make([]uuid.UUID, len(v))
+ for i := range v {
+ ids[i] = v[i].ID
+ }
+ return _c.AddRoleGroupIDs(ids...)
+}
+
+// AddInvitationIDs adds the "invitations" edge to the Invitation entity by IDs.
+func (_c *ProjectCreate) AddInvitationIDs(ids ...uuid.UUID) *ProjectCreate {
+ _c.mutation.AddInvitationIDs(ids...)
+ return _c
+}
+
+// AddInvitations adds the "invitations" edges to the Invitation entity.
+func (_c *ProjectCreate) AddInvitations(v ...*Invitation) *ProjectCreate {
+ ids := make([]uuid.UUID, len(v))
+ for i := range v {
+ ids[i] = v[i].ID
+ }
+ return _c.AddInvitationIDs(ids...)
+}
+
// Mutation returns the ProjectMutation object of the builder.
func (_c *ProjectCreate) Mutation() *ProjectMutation {
return _c.mutation
@@ -424,6 +456,38 @@ func (_c *ProjectCreate) createSpec() (*Project, *sqlgraph.CreateSpec) {
}
_spec.Edges = append(_spec.Edges, edge)
}
+ if nodes := _c.mutation.RoleGroupsIDs(); len(nodes) > 0 {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.O2M,
+ Inverse: false,
+ Table: project.RoleGroupsTable,
+ Columns: []string{project.RoleGroupsColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(group.FieldID, field.TypeUUID),
+ },
+ }
+ for _, k := range nodes {
+ edge.Target.Nodes = append(edge.Target.Nodes, k)
+ }
+ _spec.Edges = append(_spec.Edges, edge)
+ }
+ if nodes := _c.mutation.InvitationsIDs(); len(nodes) > 0 {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.O2M,
+ Inverse: false,
+ Table: project.InvitationsTable,
+ Columns: []string{project.InvitationsColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(invitation.FieldID, field.TypeUUID),
+ },
+ }
+ for _, k := range nodes {
+ edge.Target.Nodes = append(edge.Target.Nodes, k)
+ }
+ _spec.Edges = append(_spec.Edges, edge)
+ }
return _node, _spec
}
diff --git a/apps/api/ent/project_query.go b/apps/api/ent/project_query.go
index f840ba0ef..7f0b6d323 100644
--- a/apps/api/ent/project_query.go
+++ b/apps/api/ent/project_query.go
@@ -14,6 +14,8 @@ import (
"entgo.io/ent/schema/field"
"github.com/google/uuid"
"github.com/unbindapp/unbind-api/ent/environment"
+ "github.com/unbindapp/unbind-api/ent/group"
+ "github.com/unbindapp/unbind-api/ent/invitation"
"github.com/unbindapp/unbind-api/ent/predicate"
"github.com/unbindapp/unbind-api/ent/project"
"github.com/unbindapp/unbind-api/ent/team"
@@ -31,6 +33,8 @@ type ProjectQuery struct {
withEnvironments *EnvironmentQuery
withDefaultEnvironment *EnvironmentQuery
withProjectWebhooks *WebhookQuery
+ withRoleGroups *GroupQuery
+ withInvitations *InvitationQuery
modifiers []func(*sql.Selector)
// intermediate query (i.e. traversal path).
sql *sql.Selector
@@ -156,6 +160,50 @@ func (_q *ProjectQuery) QueryProjectWebhooks() *WebhookQuery {
return query
}
+// QueryRoleGroups chains the current query on the "role_groups" edge.
+func (_q *ProjectQuery) QueryRoleGroups() *GroupQuery {
+ query := (&GroupClient{config: _q.config}).Query()
+ query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
+ if err := _q.prepareQuery(ctx); err != nil {
+ return nil, err
+ }
+ selector := _q.sqlQuery(ctx)
+ if err := selector.Err(); err != nil {
+ return nil, err
+ }
+ step := sqlgraph.NewStep(
+ sqlgraph.From(project.Table, project.FieldID, selector),
+ sqlgraph.To(group.Table, group.FieldID),
+ sqlgraph.Edge(sqlgraph.O2M, false, project.RoleGroupsTable, project.RoleGroupsColumn),
+ )
+ fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step)
+ return fromU, nil
+ }
+ return query
+}
+
+// QueryInvitations chains the current query on the "invitations" edge.
+func (_q *ProjectQuery) QueryInvitations() *InvitationQuery {
+ query := (&InvitationClient{config: _q.config}).Query()
+ query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
+ if err := _q.prepareQuery(ctx); err != nil {
+ return nil, err
+ }
+ selector := _q.sqlQuery(ctx)
+ if err := selector.Err(); err != nil {
+ return nil, err
+ }
+ step := sqlgraph.NewStep(
+ sqlgraph.From(project.Table, project.FieldID, selector),
+ sqlgraph.To(invitation.Table, invitation.FieldID),
+ sqlgraph.Edge(sqlgraph.O2M, false, project.InvitationsTable, project.InvitationsColumn),
+ )
+ fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step)
+ return fromU, nil
+ }
+ return query
+}
+
// First returns the first Project entity from the query.
// Returns a *NotFoundError when no Project was found.
func (_q *ProjectQuery) First(ctx context.Context) (*Project, error) {
@@ -352,6 +400,8 @@ func (_q *ProjectQuery) Clone() *ProjectQuery {
withEnvironments: _q.withEnvironments.Clone(),
withDefaultEnvironment: _q.withDefaultEnvironment.Clone(),
withProjectWebhooks: _q.withProjectWebhooks.Clone(),
+ withRoleGroups: _q.withRoleGroups.Clone(),
+ withInvitations: _q.withInvitations.Clone(),
// clone intermediate query.
sql: _q.sql.Clone(),
path: _q.path,
@@ -403,6 +453,28 @@ func (_q *ProjectQuery) WithProjectWebhooks(opts ...func(*WebhookQuery)) *Projec
return _q
}
+// WithRoleGroups tells the query-builder to eager-load the nodes that are connected to
+// the "role_groups" edge. The optional arguments are used to configure the query builder of the edge.
+func (_q *ProjectQuery) WithRoleGroups(opts ...func(*GroupQuery)) *ProjectQuery {
+ query := (&GroupClient{config: _q.config}).Query()
+ for _, opt := range opts {
+ opt(query)
+ }
+ _q.withRoleGroups = query
+ return _q
+}
+
+// WithInvitations tells the query-builder to eager-load the nodes that are connected to
+// the "invitations" edge. The optional arguments are used to configure the query builder of the edge.
+func (_q *ProjectQuery) WithInvitations(opts ...func(*InvitationQuery)) *ProjectQuery {
+ query := (&InvitationClient{config: _q.config}).Query()
+ for _, opt := range opts {
+ opt(query)
+ }
+ _q.withInvitations = query
+ return _q
+}
+
// GroupBy is used to group vertices by one or more fields/columns.
// It is often used with aggregate functions, like: count, max, mean, min, sum.
//
@@ -481,11 +553,13 @@ func (_q *ProjectQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Proj
var (
nodes = []*Project{}
_spec = _q.querySpec()
- loadedTypes = [4]bool{
+ loadedTypes = [6]bool{
_q.withTeam != nil,
_q.withEnvironments != nil,
_q.withDefaultEnvironment != nil,
_q.withProjectWebhooks != nil,
+ _q.withRoleGroups != nil,
+ _q.withInvitations != nil,
}
)
_spec.ScanValues = func(columns []string) ([]any, error) {
@@ -535,6 +609,20 @@ func (_q *ProjectQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Proj
return nil, err
}
}
+ if query := _q.withRoleGroups; query != nil {
+ if err := _q.loadRoleGroups(ctx, query, nodes,
+ func(n *Project) { n.Edges.RoleGroups = []*Group{} },
+ func(n *Project, e *Group) { n.Edges.RoleGroups = append(n.Edges.RoleGroups, e) }); err != nil {
+ return nil, err
+ }
+ }
+ if query := _q.withInvitations; query != nil {
+ if err := _q.loadInvitations(ctx, query, nodes,
+ func(n *Project) { n.Edges.Invitations = []*Invitation{} },
+ func(n *Project, e *Invitation) { n.Edges.Invitations = append(n.Edges.Invitations, e) }); err != nil {
+ return nil, err
+ }
+ }
return nodes, nil
}
@@ -662,6 +750,72 @@ func (_q *ProjectQuery) loadProjectWebhooks(ctx context.Context, query *WebhookQ
}
return nil
}
+func (_q *ProjectQuery) loadRoleGroups(ctx context.Context, query *GroupQuery, nodes []*Project, init func(*Project), assign func(*Project, *Group)) error {
+ fks := make([]driver.Value, 0, len(nodes))
+ nodeids := make(map[uuid.UUID]*Project)
+ for i := range nodes {
+ fks = append(fks, nodes[i].ID)
+ nodeids[nodes[i].ID] = nodes[i]
+ if init != nil {
+ init(nodes[i])
+ }
+ }
+ if len(query.ctx.Fields) > 0 {
+ query.ctx.AppendFieldOnce(group.FieldProjectID)
+ }
+ query.Where(predicate.Group(func(s *sql.Selector) {
+ s.Where(sql.InValues(s.C(project.RoleGroupsColumn), fks...))
+ }))
+ neighbors, err := query.All(ctx)
+ if err != nil {
+ return err
+ }
+ for _, n := range neighbors {
+ fk := n.ProjectID
+ if fk == nil {
+ return fmt.Errorf(`foreign-key "project_id" is nil for node %v`, n.ID)
+ }
+ node, ok := nodeids[*fk]
+ if !ok {
+ return fmt.Errorf(`unexpected referenced foreign-key "project_id" returned %v for node %v`, *fk, n.ID)
+ }
+ assign(node, n)
+ }
+ return nil
+}
+func (_q *ProjectQuery) loadInvitations(ctx context.Context, query *InvitationQuery, nodes []*Project, init func(*Project), assign func(*Project, *Invitation)) error {
+ fks := make([]driver.Value, 0, len(nodes))
+ nodeids := make(map[uuid.UUID]*Project)
+ for i := range nodes {
+ fks = append(fks, nodes[i].ID)
+ nodeids[nodes[i].ID] = nodes[i]
+ if init != nil {
+ init(nodes[i])
+ }
+ }
+ if len(query.ctx.Fields) > 0 {
+ query.ctx.AppendFieldOnce(invitation.FieldProjectID)
+ }
+ query.Where(predicate.Invitation(func(s *sql.Selector) {
+ s.Where(sql.InValues(s.C(project.InvitationsColumn), fks...))
+ }))
+ neighbors, err := query.All(ctx)
+ if err != nil {
+ return err
+ }
+ for _, n := range neighbors {
+ fk := n.ProjectID
+ if fk == nil {
+ return fmt.Errorf(`foreign-key "project_id" is nil for node %v`, n.ID)
+ }
+ node, ok := nodeids[*fk]
+ if !ok {
+ return fmt.Errorf(`unexpected referenced foreign-key "project_id" returned %v for node %v`, *fk, n.ID)
+ }
+ assign(node, n)
+ }
+ return nil
+}
func (_q *ProjectQuery) sqlCount(ctx context.Context) (int, error) {
_spec := _q.querySpec()
diff --git a/apps/api/ent/project_update.go b/apps/api/ent/project_update.go
index bd6b3e6c3..89a43a546 100644
--- a/apps/api/ent/project_update.go
+++ b/apps/api/ent/project_update.go
@@ -14,6 +14,8 @@ import (
"entgo.io/ent/schema/field"
"github.com/google/uuid"
"github.com/unbindapp/unbind-api/ent/environment"
+ "github.com/unbindapp/unbind-api/ent/group"
+ "github.com/unbindapp/unbind-api/ent/invitation"
"github.com/unbindapp/unbind-api/ent/predicate"
"github.com/unbindapp/unbind-api/ent/project"
"github.com/unbindapp/unbind-api/ent/team"
@@ -229,6 +231,36 @@ func (_u *ProjectUpdate) AddProjectWebhooks(v ...*Webhook) *ProjectUpdate {
return _u.AddProjectWebhookIDs(ids...)
}
+// AddRoleGroupIDs adds the "role_groups" edge to the Group entity by IDs.
+func (_u *ProjectUpdate) AddRoleGroupIDs(ids ...uuid.UUID) *ProjectUpdate {
+ _u.mutation.AddRoleGroupIDs(ids...)
+ return _u
+}
+
+// AddRoleGroups adds the "role_groups" edges to the Group entity.
+func (_u *ProjectUpdate) AddRoleGroups(v ...*Group) *ProjectUpdate {
+ ids := make([]uuid.UUID, len(v))
+ for i := range v {
+ ids[i] = v[i].ID
+ }
+ return _u.AddRoleGroupIDs(ids...)
+}
+
+// AddInvitationIDs adds the "invitations" edge to the Invitation entity by IDs.
+func (_u *ProjectUpdate) AddInvitationIDs(ids ...uuid.UUID) *ProjectUpdate {
+ _u.mutation.AddInvitationIDs(ids...)
+ return _u
+}
+
+// AddInvitations adds the "invitations" edges to the Invitation entity.
+func (_u *ProjectUpdate) AddInvitations(v ...*Invitation) *ProjectUpdate {
+ ids := make([]uuid.UUID, len(v))
+ for i := range v {
+ ids[i] = v[i].ID
+ }
+ return _u.AddInvitationIDs(ids...)
+}
+
// Mutation returns the ProjectMutation object of the builder.
func (_u *ProjectUpdate) Mutation() *ProjectMutation {
return _u.mutation
@@ -288,6 +320,48 @@ func (_u *ProjectUpdate) RemoveProjectWebhooks(v ...*Webhook) *ProjectUpdate {
return _u.RemoveProjectWebhookIDs(ids...)
}
+// ClearRoleGroups clears all "role_groups" edges to the Group entity.
+func (_u *ProjectUpdate) ClearRoleGroups() *ProjectUpdate {
+ _u.mutation.ClearRoleGroups()
+ return _u
+}
+
+// RemoveRoleGroupIDs removes the "role_groups" edge to Group entities by IDs.
+func (_u *ProjectUpdate) RemoveRoleGroupIDs(ids ...uuid.UUID) *ProjectUpdate {
+ _u.mutation.RemoveRoleGroupIDs(ids...)
+ return _u
+}
+
+// RemoveRoleGroups removes "role_groups" edges to Group entities.
+func (_u *ProjectUpdate) RemoveRoleGroups(v ...*Group) *ProjectUpdate {
+ ids := make([]uuid.UUID, len(v))
+ for i := range v {
+ ids[i] = v[i].ID
+ }
+ return _u.RemoveRoleGroupIDs(ids...)
+}
+
+// ClearInvitations clears all "invitations" edges to the Invitation entity.
+func (_u *ProjectUpdate) ClearInvitations() *ProjectUpdate {
+ _u.mutation.ClearInvitations()
+ return _u
+}
+
+// RemoveInvitationIDs removes the "invitations" edge to Invitation entities by IDs.
+func (_u *ProjectUpdate) RemoveInvitationIDs(ids ...uuid.UUID) *ProjectUpdate {
+ _u.mutation.RemoveInvitationIDs(ids...)
+ return _u
+}
+
+// RemoveInvitations removes "invitations" edges to Invitation entities.
+func (_u *ProjectUpdate) RemoveInvitations(v ...*Invitation) *ProjectUpdate {
+ ids := make([]uuid.UUID, len(v))
+ for i := range v {
+ ids[i] = v[i].ID
+ }
+ return _u.RemoveInvitationIDs(ids...)
+}
+
// Save executes the query and returns the number of nodes affected by the update operation.
func (_u *ProjectUpdate) Save(ctx context.Context) (int, error) {
_u.defaults()
@@ -541,6 +615,96 @@ func (_u *ProjectUpdate) sqlSave(ctx context.Context) (_node int, err error) {
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
+ if _u.mutation.RoleGroupsCleared() {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.O2M,
+ Inverse: false,
+ Table: project.RoleGroupsTable,
+ Columns: []string{project.RoleGroupsColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(group.FieldID, field.TypeUUID),
+ },
+ }
+ _spec.Edges.Clear = append(_spec.Edges.Clear, edge)
+ }
+ if nodes := _u.mutation.RemovedRoleGroupsIDs(); len(nodes) > 0 && !_u.mutation.RoleGroupsCleared() {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.O2M,
+ Inverse: false,
+ Table: project.RoleGroupsTable,
+ Columns: []string{project.RoleGroupsColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(group.FieldID, field.TypeUUID),
+ },
+ }
+ for _, k := range nodes {
+ edge.Target.Nodes = append(edge.Target.Nodes, k)
+ }
+ _spec.Edges.Clear = append(_spec.Edges.Clear, edge)
+ }
+ if nodes := _u.mutation.RoleGroupsIDs(); len(nodes) > 0 {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.O2M,
+ Inverse: false,
+ Table: project.RoleGroupsTable,
+ Columns: []string{project.RoleGroupsColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(group.FieldID, field.TypeUUID),
+ },
+ }
+ for _, k := range nodes {
+ edge.Target.Nodes = append(edge.Target.Nodes, k)
+ }
+ _spec.Edges.Add = append(_spec.Edges.Add, edge)
+ }
+ if _u.mutation.InvitationsCleared() {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.O2M,
+ Inverse: false,
+ Table: project.InvitationsTable,
+ Columns: []string{project.InvitationsColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(invitation.FieldID, field.TypeUUID),
+ },
+ }
+ _spec.Edges.Clear = append(_spec.Edges.Clear, edge)
+ }
+ if nodes := _u.mutation.RemovedInvitationsIDs(); len(nodes) > 0 && !_u.mutation.InvitationsCleared() {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.O2M,
+ Inverse: false,
+ Table: project.InvitationsTable,
+ Columns: []string{project.InvitationsColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(invitation.FieldID, field.TypeUUID),
+ },
+ }
+ for _, k := range nodes {
+ edge.Target.Nodes = append(edge.Target.Nodes, k)
+ }
+ _spec.Edges.Clear = append(_spec.Edges.Clear, edge)
+ }
+ if nodes := _u.mutation.InvitationsIDs(); len(nodes) > 0 {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.O2M,
+ Inverse: false,
+ Table: project.InvitationsTable,
+ Columns: []string{project.InvitationsColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(invitation.FieldID, field.TypeUUID),
+ },
+ }
+ for _, k := range nodes {
+ edge.Target.Nodes = append(edge.Target.Nodes, k)
+ }
+ _spec.Edges.Add = append(_spec.Edges.Add, edge)
+ }
_spec.AddModifiers(_u.modifiers...)
if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
@@ -758,6 +922,36 @@ func (_u *ProjectUpdateOne) AddProjectWebhooks(v ...*Webhook) *ProjectUpdateOne
return _u.AddProjectWebhookIDs(ids...)
}
+// AddRoleGroupIDs adds the "role_groups" edge to the Group entity by IDs.
+func (_u *ProjectUpdateOne) AddRoleGroupIDs(ids ...uuid.UUID) *ProjectUpdateOne {
+ _u.mutation.AddRoleGroupIDs(ids...)
+ return _u
+}
+
+// AddRoleGroups adds the "role_groups" edges to the Group entity.
+func (_u *ProjectUpdateOne) AddRoleGroups(v ...*Group) *ProjectUpdateOne {
+ ids := make([]uuid.UUID, len(v))
+ for i := range v {
+ ids[i] = v[i].ID
+ }
+ return _u.AddRoleGroupIDs(ids...)
+}
+
+// AddInvitationIDs adds the "invitations" edge to the Invitation entity by IDs.
+func (_u *ProjectUpdateOne) AddInvitationIDs(ids ...uuid.UUID) *ProjectUpdateOne {
+ _u.mutation.AddInvitationIDs(ids...)
+ return _u
+}
+
+// AddInvitations adds the "invitations" edges to the Invitation entity.
+func (_u *ProjectUpdateOne) AddInvitations(v ...*Invitation) *ProjectUpdateOne {
+ ids := make([]uuid.UUID, len(v))
+ for i := range v {
+ ids[i] = v[i].ID
+ }
+ return _u.AddInvitationIDs(ids...)
+}
+
// Mutation returns the ProjectMutation object of the builder.
func (_u *ProjectUpdateOne) Mutation() *ProjectMutation {
return _u.mutation
@@ -817,6 +1011,48 @@ func (_u *ProjectUpdateOne) RemoveProjectWebhooks(v ...*Webhook) *ProjectUpdateO
return _u.RemoveProjectWebhookIDs(ids...)
}
+// ClearRoleGroups clears all "role_groups" edges to the Group entity.
+func (_u *ProjectUpdateOne) ClearRoleGroups() *ProjectUpdateOne {
+ _u.mutation.ClearRoleGroups()
+ return _u
+}
+
+// RemoveRoleGroupIDs removes the "role_groups" edge to Group entities by IDs.
+func (_u *ProjectUpdateOne) RemoveRoleGroupIDs(ids ...uuid.UUID) *ProjectUpdateOne {
+ _u.mutation.RemoveRoleGroupIDs(ids...)
+ return _u
+}
+
+// RemoveRoleGroups removes "role_groups" edges to Group entities.
+func (_u *ProjectUpdateOne) RemoveRoleGroups(v ...*Group) *ProjectUpdateOne {
+ ids := make([]uuid.UUID, len(v))
+ for i := range v {
+ ids[i] = v[i].ID
+ }
+ return _u.RemoveRoleGroupIDs(ids...)
+}
+
+// ClearInvitations clears all "invitations" edges to the Invitation entity.
+func (_u *ProjectUpdateOne) ClearInvitations() *ProjectUpdateOne {
+ _u.mutation.ClearInvitations()
+ return _u
+}
+
+// RemoveInvitationIDs removes the "invitations" edge to Invitation entities by IDs.
+func (_u *ProjectUpdateOne) RemoveInvitationIDs(ids ...uuid.UUID) *ProjectUpdateOne {
+ _u.mutation.RemoveInvitationIDs(ids...)
+ return _u
+}
+
+// RemoveInvitations removes "invitations" edges to Invitation entities.
+func (_u *ProjectUpdateOne) RemoveInvitations(v ...*Invitation) *ProjectUpdateOne {
+ ids := make([]uuid.UUID, len(v))
+ for i := range v {
+ ids[i] = v[i].ID
+ }
+ return _u.RemoveInvitationIDs(ids...)
+}
+
// Where appends a list predicates to the ProjectUpdate builder.
func (_u *ProjectUpdateOne) Where(ps ...predicate.Project) *ProjectUpdateOne {
_u.mutation.Where(ps...)
@@ -1100,6 +1336,96 @@ func (_u *ProjectUpdateOne) sqlSave(ctx context.Context) (_node *Project, err er
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
+ if _u.mutation.RoleGroupsCleared() {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.O2M,
+ Inverse: false,
+ Table: project.RoleGroupsTable,
+ Columns: []string{project.RoleGroupsColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(group.FieldID, field.TypeUUID),
+ },
+ }
+ _spec.Edges.Clear = append(_spec.Edges.Clear, edge)
+ }
+ if nodes := _u.mutation.RemovedRoleGroupsIDs(); len(nodes) > 0 && !_u.mutation.RoleGroupsCleared() {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.O2M,
+ Inverse: false,
+ Table: project.RoleGroupsTable,
+ Columns: []string{project.RoleGroupsColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(group.FieldID, field.TypeUUID),
+ },
+ }
+ for _, k := range nodes {
+ edge.Target.Nodes = append(edge.Target.Nodes, k)
+ }
+ _spec.Edges.Clear = append(_spec.Edges.Clear, edge)
+ }
+ if nodes := _u.mutation.RoleGroupsIDs(); len(nodes) > 0 {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.O2M,
+ Inverse: false,
+ Table: project.RoleGroupsTable,
+ Columns: []string{project.RoleGroupsColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(group.FieldID, field.TypeUUID),
+ },
+ }
+ for _, k := range nodes {
+ edge.Target.Nodes = append(edge.Target.Nodes, k)
+ }
+ _spec.Edges.Add = append(_spec.Edges.Add, edge)
+ }
+ if _u.mutation.InvitationsCleared() {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.O2M,
+ Inverse: false,
+ Table: project.InvitationsTable,
+ Columns: []string{project.InvitationsColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(invitation.FieldID, field.TypeUUID),
+ },
+ }
+ _spec.Edges.Clear = append(_spec.Edges.Clear, edge)
+ }
+ if nodes := _u.mutation.RemovedInvitationsIDs(); len(nodes) > 0 && !_u.mutation.InvitationsCleared() {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.O2M,
+ Inverse: false,
+ Table: project.InvitationsTable,
+ Columns: []string{project.InvitationsColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(invitation.FieldID, field.TypeUUID),
+ },
+ }
+ for _, k := range nodes {
+ edge.Target.Nodes = append(edge.Target.Nodes, k)
+ }
+ _spec.Edges.Clear = append(_spec.Edges.Clear, edge)
+ }
+ if nodes := _u.mutation.InvitationsIDs(); len(nodes) > 0 {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.O2M,
+ Inverse: false,
+ Table: project.InvitationsTable,
+ Columns: []string{project.InvitationsColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(invitation.FieldID, field.TypeUUID),
+ },
+ }
+ for _, k := range nodes {
+ edge.Target.Nodes = append(edge.Target.Nodes, k)
+ }
+ _spec.Edges.Add = append(_spec.Edges.Add, edge)
+ }
_spec.AddModifiers(_u.modifiers...)
_node = &Project{config: _u.config}
_spec.Assign = _node.assignValues
diff --git a/apps/api/ent/schema/group.go b/apps/api/ent/schema/group.go
index c92799f3f..e6a34d4dc 100644
--- a/apps/api/ent/schema/group.go
+++ b/apps/api/ent/schema/group.go
@@ -31,7 +31,8 @@ func (Group) Fields() []ent.Field {
field.String("description").Optional(),
field.String("k8s_role_name").Optional().Nillable().Comment("Reference to the Kubernetes Role name"),
field.UUID("team_id", uuid.UUID{}).Optional().Nillable().Comment("Set on a role group owned by a team"),
- field.Enum("role").GoType(PermittedAction("")).Optional().Nillable().Comment("The one role a team role group grants on its team"),
+ field.UUID("project_id", uuid.UUID{}).Optional().Nillable().Comment("Set on a role group owned by a project"),
+ field.Enum("role").GoType(PermittedAction("")).Optional().Nillable().Comment("The one role a role group grants on its team or project"),
}
}
@@ -41,6 +42,7 @@ func (Group) Edges() []ent.Edge {
edge.From("users", User.Type).Ref("groups"),
edge.To("permissions", Permission.Type),
edge.From("team", Team.Type).Ref("role_groups").Field("team_id").Unique(),
+ edge.From("project", Project.Type).Ref("role_groups").Field("project_id").Unique(),
}
}
@@ -48,6 +50,7 @@ func (Group) Edges() []ent.Edge {
func (Group) Indexes() []ent.Index {
return []ent.Index{
index.Fields("team_id", "role").Unique(),
+ index.Fields("project_id", "role").Unique(),
}
}
diff --git a/apps/api/ent/schema/invitation.go b/apps/api/ent/schema/invitation.go
index 6e6ffdf69..be1996bf2 100644
--- a/apps/api/ent/schema/invitation.go
+++ b/apps/api/ent/schema/invitation.go
@@ -11,8 +11,9 @@ import (
"github.com/unbindapp/unbind-api/ent/schema/mixin"
)
-// Invitation is a pending offer of a role on a team to an email address. The
-// token is only ever stored hashed; the link holding it goes to the invitee.
+// Invitation is a pending offer of a role to an email address, on a team or on
+// one of its projects when project_id is set. The token is only ever stored
+// hashed; the link holding it goes to the invitee.
type Invitation struct {
ent.Schema
}
@@ -32,6 +33,7 @@ func (Invitation) Fields() []ent.Field {
field.Time("expires_at"),
field.Time("accepted_at").Optional().Nillable(),
field.UUID("team_id", uuid.UUID{}),
+ field.UUID("project_id", uuid.UUID{}).Optional().Nillable(),
field.UUID("invited_by", uuid.UUID{}).Optional().Nillable(),
}
}
@@ -39,6 +41,7 @@ func (Invitation) Fields() []ent.Field {
func (Invitation) Edges() []ent.Edge {
return []ent.Edge{
edge.From("team", Team.Type).Ref("invitations").Field("team_id").Unique().Required(),
+ edge.From("project", Project.Type).Ref("invitations").Field("project_id").Unique(),
edge.From("inviter", User.Type).Ref("sent_invitations").Field("invited_by").Unique(),
}
}
@@ -46,6 +49,7 @@ func (Invitation) Edges() []ent.Edge {
func (Invitation) Indexes() []ent.Index {
return []ent.Index{
index.Fields("team_id"),
+ index.Fields("project_id"),
}
}
diff --git a/apps/api/ent/schema/project.go b/apps/api/ent/schema/project.go
index 338aae9fa..e6116cf78 100644
--- a/apps/api/ent/schema/project.go
+++ b/apps/api/ent/schema/project.go
@@ -57,6 +57,12 @@ func (Project) Edges() []ent.Edge {
edge.To("project_webhooks", Webhook.Type).Annotations(
entsql.Annotation{OnDelete: entsql.Cascade},
),
+ edge.To("role_groups", Group.Type).Annotations(
+ entsql.Annotation{OnDelete: entsql.Cascade},
+ ),
+ edge.To("invitations", Invitation.Type).Annotations(
+ entsql.Annotation{OnDelete: entsql.Cascade},
+ ),
}
}
diff --git a/apps/api/internal/api/handlers/invitations/invitations.go b/apps/api/internal/api/handlers/invitations/invitations.go
index ba5fe1ee8..34c42b1f2 100644
--- a/apps/api/internal/api/handlers/invitations/invitations.go
+++ b/apps/api/internal/api/handlers/invitations/invitations.go
@@ -1,4 +1,4 @@
-// Package invitations_handler serves the public side of team invitations: the
+// Package invitations_handler serves the public side of invitations: the
// invitee holds a token and nothing else, so these routes take no session.
package invitations_handler
@@ -31,7 +31,7 @@ func RegisterHandlers(server *server.Server, grp *huma.Group) {
oapi.Register(grp, oapi.Create, huma.Operation{
OperationID: "accept-invitation",
Summary: "Accept Invitation",
- Description: "Accept an invitation. Creates the account when the invited email has none, then adds it to the team.",
+ Description: "Accept an invitation. Creates the account when the invited email has none, then adds it to the team or project it was invited to.",
Path: "/accept",
Method: http.MethodPost,
}, handlers.AcceptInvitation, oapi.Public)
diff --git a/apps/api/internal/api/handlers/teams/invitations.go b/apps/api/internal/api/handlers/teams/invitations.go
index f072bb27c..b7417cbfd 100644
--- a/apps/api/internal/api/handlers/teams/invitations.go
+++ b/apps/api/internal/api/handlers/teams/invitations.go
@@ -39,7 +39,8 @@ func (self *HandlerGroup) InviteTeamMember(ctx context.Context, input *InviteTea
type ListTeamInvitationsInput struct {
server.BaseAuthInput
- TeamID uuid.UUID `query:"team_id" format:"uuid" required:"true"`
+ TeamID uuid.UUID `query:"team_id" format:"uuid" required:"true"`
+ ProjectID uuid.UUID `query:"project_id" format:"uuid" required:"false" doc:"If present, list the invitations to this project of the team"`
}
type ListTeamInvitationsResponse struct {
@@ -54,7 +55,7 @@ func (self *HandlerGroup) ListTeamInvitations(ctx context.Context, input *ListTe
return nil, err
}
- invitations, err := self.srv.TeamService.ListInvitations(ctx, user.ID, input.TeamID)
+ invitations, err := self.srv.TeamService.ListInvitations(ctx, user.ID, input.TeamID, optionalID(input.ProjectID))
if err != nil {
return nil, oapi.MapError(err)
}
diff --git a/apps/api/internal/api/handlers/teams/members.go b/apps/api/internal/api/handlers/teams/members.go
index 08f659e6e..698e6a96b 100644
--- a/apps/api/internal/api/handlers/teams/members.go
+++ b/apps/api/internal/api/handlers/teams/members.go
@@ -12,7 +12,8 @@ import (
type ListTeamMembersInput struct {
server.BaseAuthInput
- TeamID uuid.UUID `query:"team_id" format:"uuid" required:"true"`
+ TeamID uuid.UUID `query:"team_id" format:"uuid" required:"true"`
+ ProjectID uuid.UUID `query:"project_id" format:"uuid" required:"false" doc:"If present, list who can reach this project of the team"`
}
type ListTeamMembersResponse struct {
@@ -27,7 +28,7 @@ func (self *HandlerGroup) ListTeamMembers(ctx context.Context, input *ListTeamMe
return nil, err
}
- members, err := self.srv.TeamService.ListMembers(ctx, user.ID, input.TeamID)
+ members, err := self.srv.TeamService.ListMembers(ctx, user.ID, input.TeamID, optionalID(input.ProjectID))
if err != nil {
return nil, oapi.MapError(err)
}
@@ -110,3 +111,10 @@ func (self *HandlerGroup) RemoveTeamMember(ctx context.Context, input *RemoveTea
resp.Body.Data = server.SuccessResponse{Success: true}
return resp, nil
}
+
+func optionalID(id uuid.UUID) *uuid.UUID {
+ if id == uuid.Nil {
+ return nil
+ }
+ return &id
+}
diff --git a/apps/api/internal/api/handlers/teams/teams.go b/apps/api/internal/api/handlers/teams/teams.go
index 336b6fffa..6e7cb93d2 100644
--- a/apps/api/internal/api/handlers/teams/teams.go
+++ b/apps/api/internal/api/handlers/teams/teams.go
@@ -97,7 +97,7 @@ func RegisterHandlers(server *server.Server, grp *huma.Group) {
oapi.Register(grp, oapi.Read, huma.Operation{
OperationID: "list-team-members",
Summary: "List Team Members",
- Description: "List who can reach the team: members with a role on it, and users who reach it through another group.",
+ Description: "List who can reach the team: members with a role on it, and users who reach it through another group. With project_id, list who can reach that project instead: its own members, the team's members and other groups.",
Path: "/members",
Method: http.MethodGet,
}, handlers.ListTeamMembers, oapi.SessionOnly)
@@ -105,7 +105,7 @@ func RegisterHandlers(server *server.Server, grp *huma.Group) {
oapi.Register(grp, oapi.Update, huma.Operation{
OperationID: "add-team-member",
Summary: "Add Team Member",
- Description: "Give an existing account a role on the team. Requires team admin.",
+ Description: "Give an existing account a role on the team, or on one project of it with project_id. Requires admin on the team or that project.",
Path: "/members/add",
Method: http.MethodPost,
}, handlers.AddTeamMember, oapi.SessionOnly)
@@ -113,7 +113,7 @@ func RegisterHandlers(server *server.Server, grp *huma.Group) {
oapi.Register(grp, oapi.Update, huma.Operation{
OperationID: "update-team-member",
Summary: "Update Team Member",
- Description: "Change a member's role on the team. Requires team admin.",
+ Description: "Change a member's role on the team, or on one project of it with project_id. Requires admin on the team or that project.",
Path: "/members/update",
Method: http.MethodPut,
}, handlers.UpdateTeamMember, oapi.SessionOnly)
@@ -121,7 +121,7 @@ func RegisterHandlers(server *server.Server, grp *huma.Group) {
oapi.Register(grp, oapi.Update, huma.Operation{
OperationID: "remove-team-member",
Summary: "Remove Team Member",
- Description: "Remove a member from the team. Requires team admin, or the member leaving on their own.",
+ Description: "Remove a member from the team, or from one project of it with project_id. Requires admin on the team or that project, or the member leaving on their own.",
Path: "/members/remove",
Method: http.MethodDelete,
}, handlers.RemoveTeamMember, oapi.SessionOnly)
@@ -129,7 +129,7 @@ func RegisterHandlers(server *server.Server, grp *huma.Group) {
oapi.Register(grp, oapi.Create, huma.Operation{
OperationID: "invite-team-member",
Summary: "Invite Team Member",
- Description: "Invite an email address to the team. An existing account is added at once; a new one gets an invitation link, emailed when a mail relay is configured. Requires team admin.",
+ Description: "Invite an email address to the team, or to one project of it with project_id. An existing account is added at once; a new one gets an invitation link, emailed when a mail relay is configured. Requires admin on the team or that project.",
Path: "/members/invite",
Method: http.MethodPost,
}, handlers.InviteTeamMember, oapi.SessionOnly)
@@ -137,7 +137,7 @@ func RegisterHandlers(server *server.Server, grp *huma.Group) {
oapi.Register(grp, oapi.Read, huma.Operation{
OperationID: "list-team-invitations",
Summary: "List Team Invitations",
- Description: "List pending invitations to the team. Requires team admin.",
+ Description: "List pending invitations to the team, or to one project of it with project_id. Requires admin on the team or that project.",
Path: "/invitations",
Method: http.MethodGet,
}, handlers.ListTeamInvitations, oapi.SessionOnly)
@@ -145,7 +145,7 @@ func RegisterHandlers(server *server.Server, grp *huma.Group) {
oapi.Register(grp, oapi.Delete, huma.Operation{
OperationID: "revoke-team-invitation",
Summary: "Revoke Team Invitation",
- Description: "Revoke a pending invitation so its link stops working. Requires team admin.",
+ Description: "Revoke a pending invitation so its link stops working. Requires admin on the team, or on the project the invitation is to.",
Path: "/invitations/revoke",
Method: http.MethodDelete,
}, handlers.RevokeTeamInvitation, oapi.SessionOnly)
diff --git a/apps/api/internal/models/group_response.go b/apps/api/internal/models/group_response.go
index 287585f6f..5b85f6964 100644
--- a/apps/api/internal/models/group_response.go
+++ b/apps/api/internal/models/group_response.go
@@ -13,7 +13,8 @@ type GroupResponse struct {
Name string `json:"name"`
Description string `json:"description"`
TeamID *uuid.UUID `json:"team_id,omitempty" format:"uuid" doc:"Set when the group is a role group owned by a team; such groups are managed through the team's members"`
- Role *schema.PermittedAction `json:"role,omitempty" doc:"The role a team role group grants on its team"`
+ ProjectID *uuid.UUID `json:"project_id,omitempty" format:"uuid" doc:"Set when the group is a role group owned by a project; such groups are managed through the project's members"`
+ Role *schema.PermittedAction `json:"role,omitempty" doc:"The role a role group grants on its team or project"`
CreatedAt time.Time `json:"created_at"`
}
@@ -26,6 +27,7 @@ func TransformGroupEntity(entity *ent.Group) *GroupResponse {
Name: entity.Name,
Description: entity.Description,
TeamID: entity.TeamID,
+ ProjectID: entity.ProjectID,
Role: entity.Role,
CreatedAt: entity.CreatedAt,
}
diff --git a/apps/api/internal/models/invitation_response.go b/apps/api/internal/models/invitation_response.go
index a0eedaf1c..e0ff62d23 100644
--- a/apps/api/internal/models/invitation_response.go
+++ b/apps/api/internal/models/invitation_response.go
@@ -11,6 +11,7 @@ import (
type InvitationResponse struct {
ID uuid.UUID `json:"id" format:"uuid"`
TeamID uuid.UUID `json:"team_id" format:"uuid"`
+ ProjectID *uuid.UUID `json:"project_id,omitempty" format:"uuid" doc:"Set when the invitation is to one project of the team"`
Email string `json:"email"`
Role schema.PermittedAction `json:"role"`
ExpiresAt time.Time `json:"expires_at"`
@@ -23,6 +24,7 @@ func TransformInvitationEntity(entity *ent.Invitation) *InvitationResponse {
return &InvitationResponse{
ID: entity.ID,
TeamID: entity.TeamID,
+ ProjectID: entity.ProjectID,
Email: entity.Email,
Role: entity.Role,
ExpiresAt: entity.ExpiresAt,
@@ -49,7 +51,8 @@ type InviteMemberResponse struct {
type InvitationPreviewResponse struct {
Email string `json:"email"`
TeamName string `json:"team_name"`
+ ProjectName *string `json:"project_name,omitempty" doc:"Set when the invitation is to one project of the team"`
Role schema.PermittedAction `json:"role"`
ExpiresAt time.Time `json:"expires_at"`
- AccountExists bool `json:"account_exists" doc:"True when an account with this email already exists, so accepting only adds it to the team"`
+ AccountExists bool `json:"account_exists" doc:"True when an account with this email already exists, so accepting only adds it to the team or project"`
}
diff --git a/apps/api/internal/models/team_member_response.go b/apps/api/internal/models/team_member_response.go
index 3202b38cb..3f23985c0 100644
--- a/apps/api/internal/models/team_member_response.go
+++ b/apps/api/internal/models/team_member_response.go
@@ -7,15 +7,16 @@ import (
const (
// TeamMemberSourceTeam means the user holds a role on the team itself
- TeamMemberSourceTeam = "team"
- // TeamMemberSourceGroup means the user reaches the team through another group, such as superusers
+ TeamMemberSourceTeam = "team"
+ TeamMemberSourceProject = "project"
+ // TeamMemberSourceGroup means the user reaches the team or project through another group, such as superusers
TeamMemberSourceGroup = "group"
)
type TeamMemberResponse struct {
UserResponse
- Role schema.PermittedAction `json:"role" doc:"Strongest role the user holds on the team"`
- Source string `json:"source" enum:"team,group" doc:"team: holds a role on the team and can be managed here. group: reaches the team through another group and is read-only here"`
+ Role schema.PermittedAction `json:"role" doc:"Strongest role the user holds on the team or project listed"`
+ Source string `json:"source" enum:"team,project,group" doc:"team: holds a role on the team. project: holds a role on the project. group: reaches it through another group. A member is managed in the list of what the role is on, so a team member is read-only in a project's list"`
GroupName *string `json:"group_name,omitempty" doc:"The group the access comes from, when source is group"`
}
@@ -27,6 +28,14 @@ func TransformTeamMember(user *ent.User, role schema.PermittedAction) *TeamMembe
}
}
+func TransformProjectMember(user *ent.User, role schema.PermittedAction) *TeamMemberResponse {
+ return &TeamMemberResponse{
+ UserResponse: *TransformUserEntity(user),
+ Role: role,
+ Source: TeamMemberSourceProject,
+ }
+}
+
func TransformInheritedTeamMember(user *ent.User, role schema.PermittedAction, groupName string) *TeamMemberResponse {
return &TeamMemberResponse{
UserResponse: *TransformUserEntity(user),
diff --git a/apps/api/internal/repositories/bootstrap/bootstrap_repository_iface.go b/apps/api/internal/repositories/bootstrap/bootstrap_repository_iface.go
index d65f76482..ca7732b52 100644
--- a/apps/api/internal/repositories/bootstrap/bootstrap_repository_iface.go
+++ b/apps/api/internal/repositories/bootstrap/bootstrap_repository_iface.go
@@ -15,7 +15,7 @@ type BootstrapRepositoryInterface interface {
CreateUser(ctx context.Context, email, password string) (user *ent.User, err error)
IsBootstrapped(ctx context.Context, tx repository.TxInterface) (userExists bool, isBootstrapped bool, err error)
// Create the superuser group with system and team admin permissions, if no
- // instance-level group exists yet. Team role groups do not count: they exist
- // from the first start and grant nothing on the system.
+ // instance-level group exists yet. Team and project role groups do not count:
+ // they grant nothing on the system.
EnsureSuperuserGroup(ctx context.Context, tx repository.TxInterface) error
}
diff --git a/apps/api/internal/repositories/bootstrap/create_user.go b/apps/api/internal/repositories/bootstrap/create_user.go
index f6cf9bf97..6fc80e271 100644
--- a/apps/api/internal/repositories/bootstrap/create_user.go
+++ b/apps/api/internal/repositories/bootstrap/create_user.go
@@ -41,8 +41,8 @@ func (self *BootstrapRepository) CreateUser(ctx context.Context, email, password
return err
}
- // The first user joins every instance-level group, never a team's role groups
- groups, err := tx.Client().Group.Query().Where(group.TeamIDIsNil()).All(ctx)
+ // The first user joins every instance-level group, never a team's or project's role groups
+ groups, err := tx.Client().Group.Query().Where(group.TeamIDIsNil(), group.ProjectIDIsNil()).All(ctx)
if err != nil {
log.Errorf("Error querying groups: %v\n", err)
return err
diff --git a/apps/api/internal/repositories/bootstrap/superuser_group.go b/apps/api/internal/repositories/bootstrap/superuser_group.go
index 0eb1da5a5..6f3c19d61 100644
--- a/apps/api/internal/repositories/bootstrap/superuser_group.go
+++ b/apps/api/internal/repositories/bootstrap/superuser_group.go
@@ -9,12 +9,12 @@ import (
)
// Create the superuser group with system and team admin permissions, if no
-// instance-level group exists yet. Team role groups do not count: they exist
-// from the first start and grant nothing on the system.
+// instance-level group exists yet. Team and project role groups do not count:
+// they grant nothing on the system.
func (self *BootstrapRepository) EnsureSuperuserGroup(ctx context.Context, tx repository.TxInterface) error {
db := tx.Client()
- groupCount, err := db.Group.Query().Where(group.TeamIDIsNil()).Count(ctx)
+ groupCount, err := db.Group.Query().Where(group.TeamIDIsNil(), group.ProjectIDIsNil()).Count(ctx)
if err != nil {
return err
}
diff --git a/apps/api/internal/repositories/project/mutations.go b/apps/api/internal/repositories/project/mutations.go
index bc9ce4d05..ec6e5aaf0 100644
--- a/apps/api/internal/repositories/project/mutations.go
+++ b/apps/api/internal/repositories/project/mutations.go
@@ -8,7 +8,9 @@ import (
"github.com/google/uuid"
"github.com/unbindapp/unbind-api/ent"
"github.com/unbindapp/unbind-api/ent/environment"
+ "github.com/unbindapp/unbind-api/ent/permission"
"github.com/unbindapp/unbind-api/ent/project"
+ "github.com/unbindapp/unbind-api/ent/schema"
"github.com/unbindapp/unbind-api/internal/models"
repository "github.com/unbindapp/unbind-api/internal/repositories"
)
@@ -138,5 +140,24 @@ func (self *ProjectRepository) Delete(ctx context.Context, tx repository.TxInter
if tx != nil {
db = tx.Client()
}
+
+ grants, err := db.Permission.Query().
+ Where(permission.ResourceTypeEQ(schema.ResourceTypeProject)).
+ All(ctx)
+ if err != nil {
+ return err
+ }
+ var stale []uuid.UUID
+ for _, grant := range grants {
+ if grant.ResourceSelector.ID == projectID {
+ stale = append(stale, grant.ID)
+ }
+ }
+ if len(stale) > 0 {
+ if _, err := db.Permission.Delete().Where(permission.IDIn(stale...)).Exec(ctx); err != nil {
+ return err
+ }
+ }
+
return db.Project.DeleteOneID(projectID).Exec(ctx)
}
diff --git a/apps/api/internal/repositories/project/mutations_test.go b/apps/api/internal/repositories/project/mutations_test.go
index a451bc70e..8ebfae4fa 100644
--- a/apps/api/internal/repositories/project/mutations_test.go
+++ b/apps/api/internal/repositories/project/mutations_test.go
@@ -7,6 +7,8 @@ import (
"github.com/google/uuid"
"github.com/stretchr/testify/suite"
"github.com/unbindapp/unbind-api/ent"
+ "github.com/unbindapp/unbind-api/ent/group"
+ "github.com/unbindapp/unbind-api/ent/schema"
"github.com/unbindapp/unbind-api/internal/common/errdefs"
"github.com/unbindapp/unbind-api/internal/models"
repository "github.com/unbindapp/unbind-api/internal/repositories/repositorytest"
@@ -457,6 +459,24 @@ func (suite *ProjectMutationsSuite) TestDelete() {
suite.Error(err)
}
+func (suite *ProjectMutationsSuite) TestDeleteRemovesRoleGroupsAndGrantsNamingTheProject() {
+ doomed := suite.DB.Project.Create().SetTeamID(suite.testTeam.ID).SetKubernetesName("doomed-k8s").SetName("Doomed").SetKubernetesSecret("test-secret").SaveX(suite.Ctx)
+ kept := suite.DB.Project.Create().SetTeamID(suite.testTeam.ID).SetKubernetesName("kept-k8s").SetName("Kept").SetKubernetesSecret("test-secret").SaveX(suite.Ctx)
+ grant := func(projectID uuid.UUID) *ent.Permission {
+ return suite.DB.Permission.Create().SetAction(schema.ActionEditor).SetResourceType(schema.ResourceTypeProject).SetResourceSelector(schema.ResourceSelector{ID: projectID}).SaveX(suite.Ctx)
+ }
+ suite.DB.Group.Create().SetName("project-doomed-k8s-editor").SetProjectID(doomed.ID).SetRole(schema.ActionEditor).AddPermissions(grant(doomed.ID)).AddUsers(suite.testUser).SaveX(suite.Ctx)
+ suite.DB.Group.Create().SetName("custom").AddPermissions(grant(doomed.ID), grant(kept.ID)).SaveX(suite.Ctx)
+
+ suite.Require().NoError(suite.projectRepo.Delete(suite.Ctx, nil, doomed.ID))
+
+ suite.Equal(0, suite.DB.Group.Query().Where(group.ProjectID(doomed.ID)).CountX(suite.Ctx))
+ suite.Equal(1, suite.DB.Group.Query().CountX(suite.Ctx))
+ remaining := suite.DB.Permission.Query().AllX(suite.Ctx)
+ suite.Require().Len(remaining, 1)
+ suite.Equal(kept.ID, remaining[0].ResourceSelector.ID)
+}
+
func (suite *ProjectMutationsSuite) TestDeleteWithTransaction() {
// Create a project
project := suite.DB.Project.Create().
diff --git a/apps/api/internal/repositories/team/invitations.go b/apps/api/internal/repositories/team/invitations.go
index cf1b73237..191ed108c 100644
--- a/apps/api/internal/repositories/team/invitations.go
+++ b/apps/api/internal/repositories/team/invitations.go
@@ -7,11 +7,13 @@ import (
"github.com/google/uuid"
"github.com/unbindapp/unbind-api/ent"
"github.com/unbindapp/unbind-api/ent/invitation"
+ "github.com/unbindapp/unbind-api/ent/predicate"
"github.com/unbindapp/unbind-api/ent/schema"
)
type CreateInvitationInput struct {
TeamID uuid.UUID
+ ProjectID *uuid.UUID
Email string
Role schema.PermittedAction
TokenHash string
@@ -19,16 +21,18 @@ type CreateInvitationInput struct {
InvitedBy uuid.UUID
}
-// CreateInvitation replaces any pending invitation for the same address on the team.
+// CreateInvitation replaces any pending invitation for the same address on the
+// same team or project.
func (self *TeamRepository) CreateInvitation(ctx context.Context, input *CreateInvitationInput) (*ent.Invitation, error) {
_, err := self.base.DB.Invitation.Delete().
- Where(invitation.TeamID(input.TeamID), invitation.EmailEqualFold(input.Email), invitation.AcceptedAtIsNil()).
+ Where(invitation.TeamID(input.TeamID), invitedTo(input.ProjectID), invitation.EmailEqualFold(input.Email), invitation.AcceptedAtIsNil()).
Exec(ctx)
if err != nil {
return nil, err
}
return self.base.DB.Invitation.Create().
SetTeamID(input.TeamID).
+ SetNillableProjectID(input.ProjectID).
SetEmail(input.Email).
SetRole(input.Role).
SetTokenHash(input.TokenHash).
@@ -41,19 +45,20 @@ func (self *TeamRepository) GetInvitationByTokenHash(ctx context.Context, tokenH
return self.base.DB.Invitation.Query().
Where(invitation.TokenHash(tokenHash)).
WithTeam().
+ WithProject().
Only(ctx)
}
-func (self *TeamRepository) GetPendingInvitations(ctx context.Context, teamID uuid.UUID) ([]*ent.Invitation, error) {
+func (self *TeamRepository) GetPendingInvitations(ctx context.Context, teamID uuid.UUID, projectID *uuid.UUID) ([]*ent.Invitation, error) {
return self.base.DB.Invitation.Query().
- Where(invitation.TeamID(teamID), invitation.AcceptedAtIsNil(), invitation.ExpiresAtGT(time.Now())).
+ Where(invitation.TeamID(teamID), invitedTo(projectID), invitation.AcceptedAtIsNil(), invitation.ExpiresAtGT(time.Now())).
Order(ent.Asc(invitation.FieldEmail)).
All(ctx)
}
-func (self *TeamRepository) DeleteInvitation(ctx context.Context, teamID, invitationID uuid.UUID) error {
+func (self *TeamRepository) DeleteInvitation(ctx context.Context, teamID uuid.UUID, projectID *uuid.UUID, invitationID uuid.UUID) error {
deleted, err := self.base.DB.Invitation.Delete().
- Where(invitation.ID(invitationID), invitation.TeamID(teamID)).
+ Where(invitation.ID(invitationID), invitation.TeamID(teamID), invitedTo(projectID)).
Exec(ctx)
if err != nil {
return err
@@ -67,3 +72,10 @@ func (self *TeamRepository) DeleteInvitation(ctx context.Context, teamID, invita
func (self *TeamRepository) MarkInvitationAccepted(ctx context.Context, invitationID uuid.UUID) error {
return self.base.DB.Invitation.UpdateOneID(invitationID).SetAcceptedAt(time.Now()).Exec(ctx)
}
+
+func invitedTo(projectID *uuid.UUID) predicate.Invitation {
+ if projectID == nil {
+ return invitation.ProjectIDIsNil()
+ }
+ return invitation.ProjectID(*projectID)
+}
diff --git a/apps/api/internal/repositories/team/invitations_test.go b/apps/api/internal/repositories/team/invitations_test.go
index cb0f23ea1..16f9d3c3f 100644
--- a/apps/api/internal/repositories/team/invitations_test.go
+++ b/apps/api/internal/repositories/team/invitations_test.go
@@ -49,13 +49,41 @@ func (suite *InvitationsSuite) TestReinviteReplacesPendingAndListSkipsSpentOrExp
suite.True(ent.IsNotFound(err), "the first invitation was replaced")
_ = first
- pending, err := suite.teamRepo.GetPendingInvitations(suite.Ctx, suite.team.ID)
+ pending, err := suite.teamRepo.GetPendingInvitations(suite.Ctx, suite.team.ID, nil)
suite.Require().NoError(err)
suite.Require().Len(pending, 1)
suite.Equal(second.ID, pending[0].ID)
- suite.Require().NoError(suite.teamRepo.DeleteInvitation(suite.Ctx, suite.team.ID, second.ID))
- suite.True(ent.IsNotFound(suite.teamRepo.DeleteInvitation(suite.Ctx, uuid.New(), accepted.ID)), "another team cannot revoke it")
+ suite.Require().NoError(suite.teamRepo.DeleteInvitation(suite.Ctx, suite.team.ID, nil, second.ID))
+ suite.True(ent.IsNotFound(suite.teamRepo.DeleteInvitation(suite.Ctx, uuid.New(), nil, accepted.ID)), "another team cannot revoke it")
+}
+
+func (suite *InvitationsSuite) TestProjectInvitationsStayApartFromTheTeams() {
+ project := suite.DB.Project.Create().SetTeamID(suite.team.ID).SetKubernetesName("web-abc").SetName("Web").SetKubernetesSecret("web-abc").SaveX(suite.Ctx)
+ later := time.Now().Add(time.Hour)
+ toTeam := suite.invite("dev@example.com", "h1", later)
+ toProject, err := suite.teamRepo.CreateInvitation(suite.Ctx, &CreateInvitationInput{
+ TeamID: suite.team.ID, ProjectID: &project.ID, Email: "dev@example.com", Role: schema.ActionEditor, TokenHash: "h2", ExpiresAt: later, InvitedBy: suite.inviter.ID,
+ })
+ suite.Require().NoError(err)
+
+ teamPending, err := suite.teamRepo.GetPendingInvitations(suite.Ctx, suite.team.ID, nil)
+ suite.Require().NoError(err)
+ suite.Require().Len(teamPending, 1)
+ suite.Equal(toTeam.ID, teamPending[0].ID)
+
+ projectPending, err := suite.teamRepo.GetPendingInvitations(suite.Ctx, suite.team.ID, &project.ID)
+ suite.Require().NoError(err)
+ suite.Require().Len(projectPending, 1)
+ suite.Equal(toProject.ID, projectPending[0].ID)
+
+ loaded, err := suite.teamRepo.GetInvitationByTokenHash(suite.Ctx, "h2")
+ suite.Require().NoError(err)
+ suite.Equal(project.ID, loaded.Edges.Project.ID)
+
+ suite.True(ent.IsNotFound(suite.teamRepo.DeleteInvitation(suite.Ctx, suite.team.ID, nil, toProject.ID)), "a team revoke cannot reach a project invitation")
+ suite.True(ent.IsNotFound(suite.teamRepo.DeleteInvitation(suite.Ctx, suite.team.ID, &project.ID, toTeam.ID)), "a project revoke cannot reach a team invitation")
+ suite.Require().NoError(suite.teamRepo.DeleteInvitation(suite.Ctx, suite.team.ID, &project.ID, toProject.ID))
}
func TestInvitationsSuite(t *testing.T) {
diff --git a/apps/api/internal/repositories/team/mutations.go b/apps/api/internal/repositories/team/mutations.go
index 5ae4b3c8d..2bf1f2376 100644
--- a/apps/api/internal/repositories/team/mutations.go
+++ b/apps/api/internal/repositories/team/mutations.go
@@ -6,6 +6,7 @@ import (
"github.com/google/uuid"
"github.com/unbindapp/unbind-api/ent"
+ "github.com/unbindapp/unbind-api/ent/group"
"github.com/unbindapp/unbind-api/ent/permission"
"github.com/unbindapp/unbind-api/ent/schema"
"github.com/unbindapp/unbind-api/ent/team"
@@ -91,6 +92,43 @@ func (self *TeamRepository) EnsureRoleGroups(ctx context.Context, tx repository.
if err != nil {
return nil, err
}
+ return ensureRoleGroups(ctx, db, existing, roleGroupOwner{
+ resourceType: schema.ResourceTypeTeam,
+ resourceID: team.ID,
+ name: func(role schema.PermittedAction) string { return RoleGroupName(team, role) },
+ description: fmt.Sprintf("role on team %s", team.Name),
+ own: func(create *ent.GroupCreate) { create.SetTeamID(team.ID) },
+ })
+}
+
+func (self *TeamRepository) EnsureProjectRoleGroups(ctx context.Context, tx repository.TxInterface, project *ent.Project) ([]*ent.Group, error) {
+ db := self.base.DB
+ if tx != nil {
+ db = tx.Client()
+ }
+
+ existing, err := db.Group.Query().Where(group.ProjectID(project.ID)).WithUsers().All(ctx)
+ if err != nil {
+ return nil, err
+ }
+ return ensureRoleGroups(ctx, db, existing, roleGroupOwner{
+ resourceType: schema.ResourceTypeProject,
+ resourceID: project.ID,
+ name: func(role schema.PermittedAction) string { return ProjectRoleGroupName(project, role) },
+ description: fmt.Sprintf("role on project %s", project.Name),
+ own: func(create *ent.GroupCreate) { create.SetProjectID(project.ID) },
+ })
+}
+
+type roleGroupOwner struct {
+ resourceType schema.ResourceType
+ resourceID uuid.UUID
+ name func(role schema.PermittedAction) string
+ description string
+ own func(create *ent.GroupCreate)
+}
+
+func ensureRoleGroups(ctx context.Context, db *ent.Client, existing []*ent.Group, owner roleGroupOwner) ([]*ent.Group, error) {
byRole := map[schema.PermittedAction]*ent.Group{}
for _, group := range existing {
if group.Role != nil {
@@ -107,20 +145,20 @@ func (self *TeamRepository) EnsureRoleGroups(ctx context.Context, tx repository.
perm, err := db.Permission.Create().
SetAction(role).
- SetResourceType(schema.ResourceTypeTeam).
- SetResourceSelector(schema.ResourceSelector{ID: team.ID}).
+ SetResourceType(owner.resourceType).
+ SetResourceSelector(schema.ResourceSelector{ID: owner.resourceID}).
Save(ctx)
if err != nil {
return nil, err
}
- group, err := db.Group.Create().
- SetName(RoleGroupName(team, role)).
- SetDescription(fmt.Sprintf("%s role on team %s", role, team.Name)).
- SetTeamID(team.ID).
+ create := db.Group.Create().
+ SetName(owner.name(role)).
+ SetDescription(fmt.Sprintf("%s %s", role, owner.description)).
SetRole(role).
- AddPermissions(perm).
- Save(ctx)
+ AddPermissions(perm)
+ owner.own(create)
+ group, err := create.Save(ctx)
if err != nil {
return nil, err
}
@@ -135,3 +173,7 @@ func (self *TeamRepository) EnsureRoleGroups(ctx context.Context, tx repository.
func RoleGroupName(team *ent.Team, role schema.PermittedAction) string {
return fmt.Sprintf("team-%s-%s", team.KubernetesName, role)
}
+
+func ProjectRoleGroupName(project *ent.Project, role schema.PermittedAction) string {
+ return fmt.Sprintf("project-%s-%s", project.KubernetesName, role)
+}
diff --git a/apps/api/internal/repositories/team/queries.go b/apps/api/internal/repositories/team/queries.go
index 4ce82d8c0..03a98cd44 100644
--- a/apps/api/internal/repositories/team/queries.go
+++ b/apps/api/internal/repositories/team/queries.go
@@ -2,6 +2,7 @@ package team_repo
import (
"context"
+ "slices"
"github.com/google/uuid"
"github.com/unbindapp/unbind-api/ent"
@@ -81,18 +82,50 @@ func (self *TeamRepository) GetRoleGroups(ctx context.Context, teamID uuid.UUID)
All(ctx)
}
+// Empty until the project gets its first member.
+func (self *TeamRepository) GetProjectRoleGroups(ctx context.Context, projectID uuid.UUID) ([]*ent.Group, error) {
+ return self.base.DB.Group.Query().
+ Where(group.ProjectID(projectID)).
+ WithUsers().
+ All(ctx)
+}
+
+type MemberScope struct {
+ TeamID uuid.UUID
+ ProjectID *uuid.UUID
+}
+
+func (self MemberScope) ReachedBy(grant *ent.Permission) bool {
+ switch grant.ResourceType {
+ case schema.ResourceTypeTeam:
+ return grant.ResourceSelector.Superuser || grant.ResourceSelector.ID == self.TeamID
+ case schema.ResourceTypeProject:
+ return self.ProjectID != nil && (grant.ResourceSelector.Superuser || grant.ResourceSelector.ID == *self.ProjectID)
+ default:
+ return false
+ }
+}
+
// GetGroupsReachingTeam returns every group that is not one of the team's own
// role groups but holds a grant on the team, with members and grants loaded.
// Their members reach the team without being on it.
func (self *TeamRepository) GetGroupsReachingTeam(ctx context.Context, teamID uuid.UUID) ([]*ent.Group, error) {
+ return self.groupsReaching(ctx, MemberScope{TeamID: teamID}, group.Or(group.TeamIDIsNil(), group.TeamIDNEQ(teamID)))
+}
+
+// Includes the role groups of the project's team: its members reach every project.
+func (self *TeamRepository) GetGroupsReachingProject(ctx context.Context, teamID, projectID uuid.UUID) ([]*ent.Group, error) {
+ scope := MemberScope{TeamID: teamID, ProjectID: &projectID}
+ return self.groupsReaching(ctx, scope, group.Or(group.ProjectIDIsNil(), group.ProjectIDNEQ(projectID)))
+}
+
+func (self *TeamRepository) groupsReaching(ctx context.Context, scope MemberScope, notOwnRoleGroup predicate.Group) ([]*ent.Group, error) {
+ grantTypes := permission.ResourceTypeIn(schema.ResourceTypeTeam, schema.ResourceTypeProject)
groups, err := self.base.DB.Group.Query().
- Where(
- group.Or(group.TeamIDIsNil(), group.TeamIDNEQ(teamID)),
- group.HasPermissionsWith(permission.ResourceTypeEQ(schema.ResourceTypeTeam)),
- ).
+ Where(notOwnRoleGroup, group.HasPermissionsWith(grantTypes)).
WithUsers().
WithPermissions(func(q *ent.PermissionQuery) {
- q.Where(permission.ResourceTypeEQ(schema.ResourceTypeTeam))
+ q.Where(grantTypes)
}).
All(ctx)
if err != nil {
@@ -101,11 +134,8 @@ func (self *TeamRepository) GetGroupsReachingTeam(ctx context.Context, teamID uu
var reaching []*ent.Group
for _, g := range groups {
- for _, p := range g.Edges.Permissions {
- if p.ResourceSelector.Superuser || p.ResourceSelector.ID == teamID {
- reaching = append(reaching, g)
- break
- }
+ if slices.ContainsFunc(g.Edges.Permissions, scope.ReachedBy) {
+ reaching = append(reaching, g)
}
}
return reaching, nil
diff --git a/apps/api/internal/repositories/team/role_groups_test.go b/apps/api/internal/repositories/team/role_groups_test.go
index 9f3c8a8f6..a2a6a7062 100644
--- a/apps/api/internal/repositories/team/role_groups_test.go
+++ b/apps/api/internal/repositories/team/role_groups_test.go
@@ -93,6 +93,70 @@ func (suite *RoleGroupsSuite) TestDeleteRemovesRoleGroupsAndGrantsNamingTheTeam(
}
}
+func (suite *RoleGroupsSuite) project(name string) *ent.Project {
+ return suite.DB.Project.Create().SetTeamID(suite.team.ID).SetKubernetesName(name).SetName(name).SetKubernetesSecret(name).SaveX(suite.Ctx)
+}
+
+func (suite *RoleGroupsSuite) TestEnsureProjectRoleGroupsIsIdempotentAndGrantsOnlyTheProject() {
+ web := suite.project("web-abc")
+ _, err := suite.teamRepo.EnsureRoleGroups(suite.Ctx, nil, suite.team)
+ suite.Require().NoError(err)
+
+ first, err := suite.teamRepo.EnsureProjectRoleGroups(suite.Ctx, nil, web)
+ suite.Require().NoError(err)
+ suite.DB.Group.UpdateOne(first[1]).AddUsers(suite.user).ExecX(suite.Ctx)
+ again, err := suite.teamRepo.EnsureProjectRoleGroups(suite.Ctx, nil, web)
+ suite.Require().NoError(err)
+
+ suite.Len(first, 3)
+ suite.Len(again, 3)
+ suite.Equal(3, suite.DB.Group.Query().Where(group.ProjectID(web.ID)).CountX(suite.Ctx))
+ suite.Require().Len(again[1].Edges.Users, 1, "members come back loaded")
+
+ for i, role := range MemberRoles {
+ suite.Equal(first[i].ID, again[i].ID)
+ suite.Equal(role, *first[i].Role)
+ suite.Nil(first[i].TeamID)
+ suite.Equal("project-web-abc-"+string(role), first[i].Name)
+ perms := suite.DB.Group.QueryPermissions(first[i]).AllX(suite.Ctx)
+ suite.Require().Len(perms, 1)
+ suite.Equal(role, perms[0].Action)
+ suite.Equal(schema.ResourceTypeProject, perms[0].ResourceType)
+ suite.Equal(schema.ResourceSelector{ID: web.ID}, perms[0].ResourceSelector)
+ }
+
+ teamGroups, err := suite.teamRepo.GetRoleGroups(suite.Ctx, suite.team.ID)
+ suite.Require().NoError(err)
+ suite.Len(teamGroups, 3, "project role groups are not the team's")
+
+ projectGroups, err := suite.teamRepo.GetProjectRoleGroups(suite.Ctx, web.ID)
+ suite.Require().NoError(err)
+ suite.Len(projectGroups, 3)
+}
+
+func (suite *RoleGroupsSuite) TestGetGroupsReachingProjectHoldsTeamAccessAndSkipsOwnAndSiblingProjects() {
+ web, api := suite.project("web-abc"), suite.project("api-abc")
+ teamGroups, err := suite.teamRepo.EnsureRoleGroups(suite.Ctx, nil, suite.team)
+ suite.Require().NoError(err)
+ _, err = suite.teamRepo.EnsureProjectRoleGroups(suite.Ctx, nil, web)
+ suite.Require().NoError(err)
+ _, err = suite.teamRepo.EnsureProjectRoleGroups(suite.Ctx, nil, api)
+ suite.Require().NoError(err)
+ superusers := suite.grantGroup("superuser", schema.ResourceSelector{Superuser: true}, schema.ActionAdmin)
+ suite.grantGroup("beta-admins", schema.ResourceSelector{ID: suite.other.ID}, schema.ActionAdmin)
+ webGrant := suite.DB.Permission.Create().SetAction(schema.ActionViewer).SetResourceType(schema.ResourceTypeProject).SetResourceSelector(schema.ResourceSelector{ID: web.ID}).SaveX(suite.Ctx)
+ webViewers := suite.DB.Group.Create().SetName("web-viewers").AddPermissions(webGrant).SaveX(suite.Ctx)
+
+ reaching, err := suite.teamRepo.GetGroupsReachingProject(suite.Ctx, suite.team.ID, web.ID)
+ suite.Require().NoError(err)
+
+ var names []string
+ for _, g := range reaching {
+ names = append(names, g.Name)
+ }
+ suite.ElementsMatch([]string{superusers.Name, webViewers.Name, teamGroups[0].Name, teamGroups[1].Name, teamGroups[2].Name}, names)
+}
+
func TestRoleGroupsSuite(t *testing.T) {
suite.Run(t, new(RoleGroupsSuite))
}
diff --git a/apps/api/internal/repositories/team/team_repository_iface.go b/apps/api/internal/repositories/team/team_repository_iface.go
index 8d91d18ba..6049008ac 100644
--- a/apps/api/internal/repositories/team/team_repository_iface.go
+++ b/apps/api/internal/repositories/team/team_repository_iface.go
@@ -16,11 +16,12 @@ type TeamRepositoryInterface interface {
GetIcon(ctx context.Context, teamID uuid.UUID) (*ent.TeamIcon, error)
SetIcon(ctx context.Context, teamID uuid.UUID, contentType string, data []byte) error
DeleteIcon(ctx context.Context, teamID uuid.UUID) error
- // CreateInvitation replaces any pending invitation for the same address on the team.
+ // CreateInvitation replaces any pending invitation for the same address on the
+ // same team or project.
CreateInvitation(ctx context.Context, input *CreateInvitationInput) (*ent.Invitation, error)
GetInvitationByTokenHash(ctx context.Context, tokenHash string) (*ent.Invitation, error)
- GetPendingInvitations(ctx context.Context, teamID uuid.UUID) ([]*ent.Invitation, error)
- DeleteInvitation(ctx context.Context, teamID, invitationID uuid.UUID) error
+ GetPendingInvitations(ctx context.Context, teamID uuid.UUID, projectID *uuid.UUID) ([]*ent.Invitation, error)
+ DeleteInvitation(ctx context.Context, teamID uuid.UUID, projectID *uuid.UUID, invitationID uuid.UUID) error
MarkInvitationAccepted(ctx context.Context, invitationID uuid.UUID) error
Create(ctx context.Context, tx repository.TxInterface, kubernetesName, name, namespace, kubernetesSecret string, description *string) (*ent.Team, error)
Update(ctx context.Context, teamID uuid.UUID, name string, description *string) (*ent.Team, error)
@@ -30,6 +31,7 @@ type TeamRepositoryInterface interface {
// EnsureRoleGroups creates the team's admin, editor and viewer groups where they
// are missing, each holding exactly that role on the team.
EnsureRoleGroups(ctx context.Context, tx repository.TxInterface, team *ent.Team) ([]*ent.Group, error)
+ EnsureProjectRoleGroups(ctx context.Context, tx repository.TxInterface, project *ent.Project) ([]*ent.Group, error)
GetAll(ctx context.Context, authPredicate predicate.Team) ([]*ent.Team, error)
GetByID(ctx context.Context, id uuid.UUID) (*ent.Team, error)
GetNamespace(ctx context.Context, id uuid.UUID) (string, error)
@@ -37,8 +39,12 @@ type TeamRepositoryInterface interface {
GetNames(ctx context.Context, tx repository.TxInterface) ([]string, error)
// GetRoleGroups returns the team's role groups with their members loaded.
GetRoleGroups(ctx context.Context, teamID uuid.UUID) ([]*ent.Group, error)
+ // Empty until the project gets its first member.
+ GetProjectRoleGroups(ctx context.Context, projectID uuid.UUID) ([]*ent.Group, error)
// GetGroupsReachingTeam returns every group that is not one of the team's own
// role groups but holds a grant on the team, with members and grants loaded.
// Their members reach the team without being on it.
GetGroupsReachingTeam(ctx context.Context, teamID uuid.UUID) ([]*ent.Group, error)
+ // Includes the role groups of the project's team: its members reach every project.
+ GetGroupsReachingProject(ctx context.Context, teamID, projectID uuid.UUID) ([]*ent.Group, error)
}
diff --git a/apps/api/internal/services/group/managed.go b/apps/api/internal/services/group/managed.go
index c4d2fb6b9..cd5659cb3 100644
--- a/apps/api/internal/services/group/managed.go
+++ b/apps/api/internal/services/group/managed.go
@@ -5,11 +5,14 @@ import (
"github.com/unbindapp/unbind-api/internal/common/errdefs"
)
-// Role groups belong to their team. Their grants and members change through the
-// team members endpoints, so every member holds exactly one role on the team.
+// Role groups belong to their team or project. Their grants and members change
+// through the members endpoints, so every member holds exactly one role there.
func ensureNotManaged(group *ent.Group) error {
- if group.TeamID == nil {
- return nil
+ if group.TeamID != nil {
+ return errdefs.NewCustomError(errdefs.ErrTypeInvalidInput, "This group is managed by its team")
}
- return errdefs.NewCustomError(errdefs.ErrTypeInvalidInput, "This group is managed by its team")
+ if group.ProjectID != nil {
+ return errdefs.NewCustomError(errdefs.ErrTypeInvalidInput, "This group is managed by its project")
+ }
+ return nil
}
diff --git a/apps/api/internal/services/metrics/metrics_test.go b/apps/api/internal/services/metrics/metrics_test.go
index d47db1f00..fde7698a2 100644
--- a/apps/api/internal/services/metrics/metrics_test.go
+++ b/apps/api/internal/services/metrics/metrics_test.go
@@ -9,6 +9,7 @@ import (
"github.com/unbindapp/unbind-api/ent/schema"
"github.com/unbindapp/unbind-api/internal/infrastructure/prometheus"
"github.com/unbindapp/unbind-api/internal/models"
+ permissions_repo "github.com/unbindapp/unbind-api/internal/repositories/permissions"
)
func TestPermissionCheckForType(t *testing.T) {
@@ -86,3 +87,20 @@ func TestMetricsByServerName(t *testing.T) {
assert.NotContains(t, result, "10.0.0.9", "instances of unknown servers are dropped")
assert.Len(t, result, 3)
}
+
+func TestVolumeViewChecksCoverEveryLevelTheVolumeBelongsTo(t *testing.T) {
+ teamID, projectID, environmentID := uuid.New(), uuid.New(), uuid.New()
+ viewer := func(resourceType schema.ResourceType, id uuid.UUID) permissions_repo.PermissionCheck {
+ return permissions_repo.PermissionCheck{Action: schema.ActionViewer, ResourceType: resourceType, ResourceID: id}
+ }
+
+ teamVolume := volumeViewChecks(&models.PVCInfo{TeamID: teamID})
+ assert.Equal(t, []permissions_repo.PermissionCheck{viewer(schema.ResourceTypeTeam, teamID)}, teamVolume)
+
+ environmentVolume := volumeViewChecks(&models.PVCInfo{TeamID: teamID, ProjectID: &projectID, EnvironmentID: &environmentID})
+ assert.Equal(t, []permissions_repo.PermissionCheck{
+ viewer(schema.ResourceTypeTeam, teamID),
+ viewer(schema.ResourceTypeProject, projectID),
+ viewer(schema.ResourceTypeEnvironment, environmentID),
+ }, environmentVolume)
+}
diff --git a/apps/api/internal/services/metrics/read_volume.go b/apps/api/internal/services/metrics/read_volume.go
index 752a98746..a54bf25ef 100644
--- a/apps/api/internal/services/metrics/read_volume.go
+++ b/apps/api/internal/services/metrics/read_volume.go
@@ -14,16 +14,7 @@ import (
)
func (self *MetricsService) GetVolumeMetrics(ctx context.Context, requesterUserID uuid.UUID, input *models.MetricsVolumeQueryInput) (*models.VolumeMetricsResult, error) {
- permissionChecks := []permissions_repo.PermissionCheck{
- //Can read team, project, environmnent, or service depending on inputs
- {
- Action: schema.ActionViewer,
- ResourceType: schema.ResourceTypeTeam,
- ResourceID: input.TeamID,
- },
- }
-
- if err := self.repo.Permissions().Check(ctx, requesterUserID, permissionChecks); err != nil {
+ if err := self.repo.Permissions().CheckVisible(ctx, requesterUserID, schema.ResourceTypeTeam, input.TeamID); err != nil {
return nil, errdefs.MaskAsNotFound(err, "Team not found")
}
@@ -35,6 +26,14 @@ func (self *MetricsService) GetVolumeMetrics(ctx context.Context, requesterUserI
return nil, err
}
+ volume, err := self.k8s.GetPersistentVolumeClaim(ctx, team.Namespace, input.PVCID, self.k8s.GetInternalClient())
+ if err != nil {
+ return nil, err
+ }
+ if err := self.repo.Permissions().Check(ctx, requesterUserID, volumeViewChecks(volume)); err != nil {
+ return nil, errdefs.MaskAsNotFound(err, fmt.Sprintf("PersistentVolumeClaim '%s' not found", input.PVCID))
+ }
+
var start time.Time
if input.Start.IsZero() {
// Default to 24 hours ago
@@ -72,3 +71,16 @@ func (self *MetricsService) GetVolumeMetrics(ctx context.Context, requesterUserI
return models.TransformVolumeStatsEntity(rawMetrics, step), nil
}
+
+func volumeViewChecks(volume *models.PVCInfo) []permissions_repo.PermissionCheck {
+ checks := []permissions_repo.PermissionCheck{
+ {Action: schema.ActionViewer, ResourceType: schema.ResourceTypeTeam, ResourceID: volume.TeamID},
+ }
+ if volume.ProjectID != nil {
+ checks = append(checks, permissions_repo.PermissionCheck{Action: schema.ActionViewer, ResourceType: schema.ResourceTypeProject, ResourceID: *volume.ProjectID})
+ }
+ if volume.EnvironmentID != nil {
+ checks = append(checks, permissions_repo.PermissionCheck{Action: schema.ActionViewer, ResourceType: schema.ResourceTypeEnvironment, ResourceID: *volume.EnvironmentID})
+ }
+ return checks
+}
diff --git a/apps/api/internal/services/team/invitations.go b/apps/api/internal/services/team/invitations.go
index a6b401fe9..e82c51fd9 100644
--- a/apps/api/internal/services/team/invitations.go
+++ b/apps/api/internal/services/team/invitations.go
@@ -30,14 +30,16 @@ type Mailer interface {
}
type InviteMemberInput struct {
- TeamID uuid.UUID `json:"team_id" format:"uuid" required:"true"`
- Email string `json:"email" format:"email" required:"true"`
- Role schema.PermittedAction `json:"role" required:"true" doc:"admin, editor or viewer on this team"`
+ TeamID uuid.UUID `json:"team_id" format:"uuid" required:"true"`
+ ProjectID *uuid.UUID `json:"project_id,omitempty" format:"uuid" required:"false" doc:"Set to invite to this project of the team only"`
+ Email string `json:"email" format:"email" required:"true"`
+ Role schema.PermittedAction `json:"role" required:"true" doc:"admin, editor or viewer on this team or project"`
}
type RevokeInvitationInput struct {
- TeamID uuid.UUID `json:"team_id" format:"uuid" required:"true"`
- InvitationID uuid.UUID `json:"invitation_id" format:"uuid" required:"true"`
+ TeamID uuid.UUID `json:"team_id" format:"uuid" required:"true"`
+ ProjectID *uuid.UUID `json:"project_id,omitempty" format:"uuid" required:"false" doc:"Set when the invitation is to this project of the team"`
+ InvitationID uuid.UUID `json:"invitation_id" format:"uuid" required:"true"`
}
type AcceptInvitationInput struct {
@@ -45,14 +47,15 @@ type AcceptInvitationInput struct {
Password string `json:"password" required:"false" minLength:"8" doc:"Required unless an account with the invited email already exists"`
}
-// InviteMember adds an existing account to the team at once, or records an
-// invitation for a new one and mails the link when a relay is configured. The
-// link always comes back to the inviter so it can be shared by hand.
+// InviteMember adds an existing account to the team or project at once, or
+// records an invitation for a new one and mails the link when a relay is
+// configured. The link always comes back to the inviter so it can be shared by hand.
func (self *TeamService) InviteMember(ctx context.Context, requesterUserID uuid.UUID, input *InviteMemberInput) (*models.InviteMemberResponse, error) {
if err := validateMemberRole(input.Role); err != nil {
return nil, err
}
- if err := self.checkTeam(ctx, requesterUserID, schema.ActionAdmin, input.TeamID); err != nil {
+ project, err := self.authorize(ctx, requesterUserID, schema.ActionAdmin, input.TeamID, input.ProjectID)
+ if err != nil {
return nil, err
}
email := strings.TrimSpace(strings.ToLower(input.Email))
@@ -65,17 +68,18 @@ func (self *TeamService) InviteMember(ctx context.Context, requesterUserID uuid.
if err != nil {
return nil, err
}
+ joined := self.newJoinedResource(team, project)
_, err = self.repo.User().GetByEmail(ctx, email)
if err != nil && !ent.IsNotFound(err) {
return nil, err
}
if err == nil {
- member, err := self.AddMember(ctx, requesterUserID, &TeamMemberAddInput{TeamID: input.TeamID, Email: email, Role: input.Role})
+ member, err := self.AddMember(ctx, requesterUserID, &TeamMemberAddInput{TeamID: input.TeamID, ProjectID: input.ProjectID, Email: email, Role: input.Role})
if err != nil {
return nil, err
}
- self.notifyAdded(ctx, member.Email, team, inviter.Email, input.Role)
+ self.notifyAdded(ctx, member.Email, joined, inviter.Email, input.Role)
return &models.InviteMemberResponse{Member: member}, nil
}
@@ -85,6 +89,7 @@ func (self *TeamService) InviteMember(ctx context.Context, requesterUserID uuid.
}
invitation, err := self.repo.Team().CreateInvitation(ctx, &team_repo.CreateInvitationInput{
TeamID: input.TeamID,
+ ProjectID: input.ProjectID,
Email: email,
Role: input.Role,
TokenHash: tokenHash,
@@ -98,9 +103,9 @@ func (self *TeamService) InviteMember(ctx context.Context, requesterUserID uuid.
resp := models.TransformInvitationEntity(invitation)
resp.InviteURL, _ = utils.JoinURLPaths(self.cfg.ExternalUIUrl, "invite", token)
resp.EmailSent, err = self.mailer.Send(ctx, email, mail.Content{
- Subject: fmt.Sprintf("%s invited you to %s on Unbind", inviter.Email, team.Name),
- Heading: fmt.Sprintf("Join %s", team.Name),
- Paragraphs: []string{fmt.Sprintf("%s invited you to the team %s as %s.", inviter.Email, team.Name, input.Role), "Accept the invitation to create your account and get started."},
+ Subject: fmt.Sprintf("%s invited you to %s on Unbind", inviter.Email, joined.name),
+ Heading: fmt.Sprintf("Join %s", joined.name),
+ Paragraphs: []string{fmt.Sprintf("%s invited you to %s as %s.", inviter.Email, joined.description, input.Role), "Accept the invitation to create your account and get started."},
ButtonLabel: "Accept invitation",
ButtonURL: resp.InviteURL,
Note: "This invitation expires in 7 days. If you were not expecting it, you can ignore this email.",
@@ -111,11 +116,11 @@ func (self *TeamService) InviteMember(ctx context.Context, requesterUserID uuid.
return &models.InviteMemberResponse{Invitation: resp}, nil
}
-func (self *TeamService) ListInvitations(ctx context.Context, requesterUserID uuid.UUID, teamID uuid.UUID) ([]*models.InvitationResponse, error) {
- if err := self.checkTeam(ctx, requesterUserID, schema.ActionAdmin, teamID); err != nil {
+func (self *TeamService) ListInvitations(ctx context.Context, requesterUserID uuid.UUID, teamID uuid.UUID, projectID *uuid.UUID) ([]*models.InvitationResponse, error) {
+ if _, err := self.authorize(ctx, requesterUserID, schema.ActionAdmin, teamID, projectID); err != nil {
return nil, err
}
- invitations, err := self.repo.Team().GetPendingInvitations(ctx, teamID)
+ invitations, err := self.repo.Team().GetPendingInvitations(ctx, teamID, projectID)
if err != nil {
return nil, err
}
@@ -123,10 +128,10 @@ func (self *TeamService) ListInvitations(ctx context.Context, requesterUserID uu
}
func (self *TeamService) RevokeInvitation(ctx context.Context, requesterUserID uuid.UUID, input *RevokeInvitationInput) error {
- if err := self.checkTeam(ctx, requesterUserID, schema.ActionAdmin, input.TeamID); err != nil {
+ if _, err := self.authorize(ctx, requesterUserID, schema.ActionAdmin, input.TeamID, input.ProjectID); err != nil {
return err
}
- return self.repo.Team().DeleteInvitation(ctx, input.TeamID, input.InvitationID)
+ return self.repo.Team().DeleteInvitation(ctx, input.TeamID, input.ProjectID, input.InvitationID)
}
// GetInvitation is public: holding the token is the only credential.
@@ -139,17 +144,22 @@ func (self *TeamService) GetInvitation(ctx context.Context, token string) (*mode
if err != nil && !ent.IsNotFound(err) {
return nil, err
}
- return &models.InvitationPreviewResponse{
+ preview := &models.InvitationPreviewResponse{
Email: invitation.Email,
TeamName: invitation.Edges.Team.Name,
Role: invitation.Role,
ExpiresAt: invitation.ExpiresAt,
AccountExists: err == nil,
- }, nil
+ }
+ if invitation.Edges.Project != nil {
+ preview.ProjectName = &invitation.Edges.Project.Name
+ }
+ return preview, nil
}
// AcceptInvitation is public. It creates the account when none exists for the
-// invited email, puts it on the team at the invited role and spends the token.
+// invited email, puts it on the team or project at the invited role and spends
+// the token.
func (self *TeamService) AcceptInvitation(ctx context.Context, input *AcceptInvitationInput) (*models.UserResponse, error) {
invitation, err := self.pendingInvitation(ctx, input.Token)
if err != nil {
@@ -170,14 +180,14 @@ func (self *TeamService) AcceptInvitation(ctx context.Context, input *AcceptInvi
}
}
- roleGroups, err := self.repo.Team().GetRoleGroups(ctx, invitation.TeamID)
+ roleGroups, err := self.roleGroupsToJoin(ctx, invitation.TeamID, invitation.Edges.Project)
if err != nil {
return nil, err
}
if groupHoldingUser(roleGroups, user.ID) == nil {
target := roleGroup(roleGroups, invitation.Role)
if target == nil {
- return nil, fmt.Errorf("team %s has no %s role group", invitation.TeamID, invitation.Role)
+ return nil, missingRoleGroup(invitation.TeamID, invitation.ProjectID, invitation.Role)
}
if err := self.repo.Group().AddUser(ctx, target.ID, user.ID); err != nil {
return nil, err
@@ -202,20 +212,38 @@ func (self *TeamService) pendingInvitation(ctx context.Context, token string) (*
if invitation.AcceptedAt != nil || time.Now().After(invitation.ExpiresAt) || invitation.Edges.Team == nil {
return nil, invalid
}
+ if invitation.ProjectID != nil && invitation.Edges.Project == nil {
+ return nil, invalid
+ }
return invitation, nil
}
-func (self *TeamService) notifyAdded(ctx context.Context, to string, team *ent.Team, by string, role schema.PermittedAction) {
- url, _ := utils.JoinURLPaths(self.cfg.ExternalUIUrl, team.ID.String())
+type joinedResource struct {
+ kind string
+ name string
+ description string
+ url string
+}
+
+func (self *TeamService) newJoinedResource(team *ent.Team, project *ent.Project) joinedResource {
+ if project == nil {
+ url, _ := utils.JoinURLPaths(self.cfg.ExternalUIUrl, team.ID.String())
+ return joinedResource{kind: "team", name: team.Name, description: fmt.Sprintf("the team %s", team.Name), url: url}
+ }
+ url, _ := utils.JoinURLPaths(self.cfg.ExternalUIUrl, team.ID.String(), "project", project.ID.String())
+ return joinedResource{kind: "project", name: project.Name, description: fmt.Sprintf("the project %s in the team %s", project.Name, team.Name), url: url}
+}
+
+func (self *TeamService) notifyAdded(ctx context.Context, to string, joined joinedResource, by string, role schema.PermittedAction) {
_, err := self.mailer.Send(ctx, to, mail.Content{
- Subject: fmt.Sprintf("You were added to %s on Unbind", team.Name),
- Heading: fmt.Sprintf("You are now on %s", team.Name),
- Paragraphs: []string{fmt.Sprintf("%s added you to the team %s as %s.", by, team.Name, role)},
- ButtonLabel: "Open the team",
- ButtonURL: url,
+ Subject: fmt.Sprintf("You were added to %s on Unbind", joined.name),
+ Heading: fmt.Sprintf("You are now on %s", joined.name),
+ Paragraphs: []string{fmt.Sprintf("%s added you to %s as %s.", by, joined.description, role)},
+ ButtonLabel: fmt.Sprintf("Open the %s", joined.kind),
+ ButtonURL: joined.url,
})
if err != nil {
- log.Warnf("Failed to email team notification to %s: %v", to, err)
+ log.Warnf("Failed to email %s notification to %s: %v", joined.kind, to, err)
}
}
diff --git a/apps/api/internal/services/team/invitations_test.go b/apps/api/internal/services/team/invitations_test.go
index e6a2b846e..7ff0f691c 100644
--- a/apps/api/internal/services/team/invitations_test.go
+++ b/apps/api/internal/services/team/invitations_test.go
@@ -144,6 +144,50 @@ func (suite *InvitationsSuite) TestAcceptRefusesSpentExpiredOrUnknownTokens() {
}
}
+func (suite *InvitationsSuite) TestProjectInvitationNamesTheProjectAndJoinsItsRoleGroup() {
+ project := &ent.Project{ID: uuid.New(), Name: "Web", TeamID: suite.team.ID}
+ projectGroups := make([]*ent.Group, 0, 3)
+ for _, role := range []schema.PermittedAction{schema.ActionAdmin, schema.ActionEditor, schema.ActionViewer} {
+ projectGroups = append(projectGroups, &ent.Group{ID: uuid.New(), ProjectID: &project.ID, Role: new(role)})
+ }
+ suite.mailer.configured = true
+ suite.MockPermissionsRepo.EXPECT().
+ Check(suite.Ctx, suite.adminID, []permissions_repo.PermissionCheck{{Action: schema.ActionAdmin, ResourceType: schema.ResourceTypeProject, ResourceID: project.ID}}).
+ Return(nil).Once()
+ suite.MockProjectRepo.EXPECT().GetByID(suite.Ctx, project.ID).Return(project, nil).Once()
+ suite.MockTeamRepo.EXPECT().GetByID(suite.Ctx, suite.team.ID).Return(suite.team, nil).Once()
+ suite.MockUserRepo.EXPECT().GetByID(suite.Ctx, suite.adminID).Return(&ent.User{ID: suite.adminID, Email: "admin@example.com"}, nil).Once()
+ suite.MockUserRepo.EXPECT().GetByEmail(suite.Ctx, "new@example.com").Return(nil, &ent.NotFoundError{}).Twice()
+
+ var stored *ent.Invitation
+ suite.MockTeamRepo.EXPECT().CreateInvitation(suite.Ctx, mock.Anything).
+ RunAndReturn(func(_ context.Context, in *team_repo.CreateInvitationInput) (*ent.Invitation, error) {
+ stored = &ent.Invitation{ID: uuid.New(), TeamID: in.TeamID, ProjectID: in.ProjectID, Email: in.Email, Role: in.Role, ExpiresAt: in.ExpiresAt}
+ return stored, nil
+ }).Once()
+
+ result, err := suite.service.InviteMember(suite.Ctx, suite.adminID, &InviteMemberInput{TeamID: suite.team.ID, ProjectID: &project.ID, Email: "new@example.com", Role: schema.ActionEditor})
+ suite.Require().NoError(err)
+ suite.Equal(project.ID, *result.Invitation.ProjectID)
+ suite.Require().Len(suite.mailer.sent, 1)
+ suite.Equal("Join Web", suite.mailer.sent[0].Heading)
+ suite.Contains(suite.mailer.sent[0].Paragraphs[0], "the project Web in the team Acme as editor")
+
+ token := strings.TrimPrefix(result.Invitation.InviteURL, "https://unbind.example/invite/")
+ stored.Edges.Team = suite.team
+ stored.Edges.Project = project
+ created := &ent.User{ID: uuid.New(), Email: "new@example.com"}
+ suite.MockTeamRepo.EXPECT().GetInvitationByTokenHash(suite.Ctx, hashInvitationToken(token)).Return(stored, nil).Once()
+ suite.MockUserRepo.EXPECT().Create(suite.Ctx, "new@example.com", "correct horse").Return(created, nil).Once()
+ suite.MockTeamRepo.EXPECT().EnsureProjectRoleGroups(suite.Ctx, nil, project).Return(projectGroups, nil).Once()
+ suite.MockGroupRepo.EXPECT().AddUser(suite.Ctx, projectGroups[1].ID, created.ID).Return(nil).Once()
+ suite.MockTeamRepo.EXPECT().MarkInvitationAccepted(suite.Ctx, stored.ID).Return(nil).Once()
+
+ user, err := suite.service.AcceptInvitation(suite.Ctx, &AcceptInvitationInput{Token: token, Password: "correct horse"})
+ suite.Require().NoError(err)
+ suite.Equal(created.ID, user.ID)
+}
+
func TestInvitationsSuite(t *testing.T) {
suite.Run(t, new(InvitationsSuite))
}
diff --git a/apps/api/internal/services/team/members.go b/apps/api/internal/services/team/members.go
index 801d13a7c..a9aa3597b 100644
--- a/apps/api/internal/services/team/members.go
+++ b/apps/api/internal/services/team/members.go
@@ -16,30 +16,33 @@ import (
)
type TeamMemberAddInput struct {
- TeamID uuid.UUID `json:"team_id" format:"uuid" required:"true"`
- Email string `json:"email" format:"email" required:"true" doc:"Email of an existing account. Accounts are created by instance admins."`
- Role schema.PermittedAction `json:"role" required:"true" doc:"admin, editor or viewer on this team"`
+ TeamID uuid.UUID `json:"team_id" format:"uuid" required:"true"`
+ ProjectID *uuid.UUID `json:"project_id,omitempty" format:"uuid" required:"false" doc:"Set to give the role on this project of the team only"`
+ Email string `json:"email" format:"email" required:"true" doc:"Email of an existing account. Accounts are created by instance admins."`
+ Role schema.PermittedAction `json:"role" required:"true" doc:"admin, editor or viewer on this team or project"`
}
type TeamMemberRoleInput struct {
- TeamID uuid.UUID `json:"team_id" format:"uuid" required:"true"`
- UserID uuid.UUID `json:"user_id" format:"uuid" required:"true"`
- Role schema.PermittedAction `json:"role" required:"true" doc:"admin, editor or viewer on this team"`
+ TeamID uuid.UUID `json:"team_id" format:"uuid" required:"true"`
+ ProjectID *uuid.UUID `json:"project_id,omitempty" format:"uuid" required:"false" doc:"Set to change the role held on this project of the team"`
+ UserID uuid.UUID `json:"user_id" format:"uuid" required:"true"`
+ Role schema.PermittedAction `json:"role" required:"true" doc:"admin, editor or viewer on this team or project"`
}
type TeamMemberRemoveInput struct {
- TeamID uuid.UUID `json:"team_id" format:"uuid" required:"true"`
- UserID uuid.UUID `json:"user_id" format:"uuid" required:"true"`
+ TeamID uuid.UUID `json:"team_id" format:"uuid" required:"true"`
+ ProjectID *uuid.UUID `json:"project_id,omitempty" format:"uuid" required:"false" doc:"Set to remove the role held on this project of the team"`
+ UserID uuid.UUID `json:"user_id" format:"uuid" required:"true"`
}
-// ListMembers shows who reaches the team: members holding a role on it, and
-// users who reach it through another group, so the list never hides access.
-func (self *TeamService) ListMembers(ctx context.Context, requesterUserID uuid.UUID, teamID uuid.UUID) ([]*models.TeamMemberResponse, error) {
- if err := self.checkTeam(ctx, requesterUserID, schema.ActionViewer, teamID); err != nil {
+// ListMembers shows who reaches the team or project: members holding a role on
+// it, and users who reach it through another group, so the list never hides access.
+func (self *TeamService) ListMembers(ctx context.Context, requesterUserID uuid.UUID, teamID uuid.UUID, projectID *uuid.UUID) ([]*models.TeamMemberResponse, error) {
+ if _, err := self.authorize(ctx, requesterUserID, schema.ActionViewer, teamID, projectID); err != nil {
return nil, err
}
- roleGroups, err := self.repo.Team().GetRoleGroups(ctx, teamID)
+ roleGroups, err := self.roleGroups(ctx, teamID, projectID)
if err != nil {
return nil, err
}
@@ -49,22 +52,23 @@ func (self *TeamService) ListMembers(ctx context.Context, requesterUserID uuid.U
continue
}
for _, user := range group.Edges.Users {
- members[user.ID] = models.TransformTeamMember(user, *group.Role)
+ members[user.ID] = directMember(user, *group.Role, projectID)
}
}
- reaching, err := self.repo.Team().GetGroupsReachingTeam(ctx, teamID)
+ reaching, err := self.groupsReaching(ctx, teamID, projectID)
if err != nil {
return nil, err
}
+ scope := team_repo.MemberScope{TeamID: teamID, ProjectID: projectID}
for _, group := range reaching {
- role := grantedRole(group, teamID)
+ role := grantedRole(group, scope)
for _, user := range group.Edges.Users {
current, listed := members[user.ID]
- if listed && (current.Source == models.TeamMemberSourceTeam || permissions_repo.StrongerAction(current.Role, role) == current.Role) {
+ if listed && (current.Source == directSource(projectID) || permissions_repo.StrongerAction(current.Role, role) == current.Role) {
continue
}
- members[user.ID] = models.TransformInheritedTeamMember(user, role, group.Name)
+ members[user.ID] = inheritedMember(user, role, group, teamID)
}
}
@@ -82,7 +86,8 @@ func (self *TeamService) AddMember(ctx context.Context, requesterUserID uuid.UUI
if err := validateMemberRole(input.Role); err != nil {
return nil, err
}
- if err := self.checkTeam(ctx, requesterUserID, schema.ActionAdmin, input.TeamID); err != nil {
+ project, err := self.authorize(ctx, requesterUserID, schema.ActionAdmin, input.TeamID, input.ProjectID)
+ if err != nil {
return nil, err
}
@@ -94,47 +99,47 @@ func (self *TeamService) AddMember(ctx context.Context, requesterUserID uuid.UUI
return nil, err
}
- roleGroups, err := self.repo.Team().GetRoleGroups(ctx, input.TeamID)
+ roleGroups, err := self.roleGroupsToJoin(ctx, input.TeamID, project)
if err != nil {
return nil, err
}
if current := groupHoldingUser(roleGroups, user.ID); current != nil {
- return nil, errdefs.NewCustomError(errdefs.ErrTypeConflict, "User is already a member of this team")
+ return nil, errdefs.NewCustomError(errdefs.ErrTypeConflict, fmt.Sprintf("User is already a member of this %s", scopeNoun(input.ProjectID)))
}
target := roleGroup(roleGroups, input.Role)
if target == nil {
- return nil, fmt.Errorf("team %s has no %s role group", input.TeamID, input.Role)
+ return nil, missingRoleGroup(input.TeamID, input.ProjectID, input.Role)
}
if err := self.repo.Group().AddUser(ctx, target.ID, user.ID); err != nil {
return nil, err
}
- return models.TransformTeamMember(user, input.Role), nil
+ return directMember(user, input.Role, input.ProjectID), nil
}
func (self *TeamService) UpdateMemberRole(ctx context.Context, requesterUserID uuid.UUID, input *TeamMemberRoleInput) (*models.TeamMemberResponse, error) {
if err := validateMemberRole(input.Role); err != nil {
return nil, err
}
- if err := self.checkTeam(ctx, requesterUserID, schema.ActionAdmin, input.TeamID); err != nil {
+ if _, err := self.authorize(ctx, requesterUserID, schema.ActionAdmin, input.TeamID, input.ProjectID); err != nil {
return nil, err
}
- roleGroups, err := self.repo.Team().GetRoleGroups(ctx, input.TeamID)
+ roleGroups, err := self.roleGroups(ctx, input.TeamID, input.ProjectID)
if err != nil {
return nil, err
}
current := groupHoldingUser(roleGroups, input.UserID)
if current == nil {
- return nil, errdefs.NewCustomError(errdefs.ErrTypeNotFound, "User is not a member of this team")
+ return nil, notAMember(input.ProjectID)
}
user := userIn(current, input.UserID)
if *current.Role == input.Role {
- return models.TransformTeamMember(user, input.Role), nil
+ return directMember(user, input.Role, input.ProjectID), nil
}
target := roleGroup(roleGroups, input.Role)
if target == nil {
- return nil, fmt.Errorf("team %s has no %s role group", input.TeamID, input.Role)
+ return nil, missingRoleGroup(input.TeamID, input.ProjectID, input.Role)
}
if err := self.repo.Group().AddUser(ctx, target.ID, input.UserID); err != nil {
@@ -143,28 +148,75 @@ func (self *TeamService) UpdateMemberRole(ctx context.Context, requesterUserID u
if err := self.repo.Group().RemoveUser(ctx, current.ID, input.UserID); err != nil {
return nil, err
}
- return models.TransformTeamMember(user, input.Role), nil
+ return directMember(user, input.Role, input.ProjectID), nil
}
-// RemoveMember takes a team admin, or the member leaving on their own.
+// RemoveMember takes an admin of the team or project, or the member leaving on their own.
func (self *TeamService) RemoveMember(ctx context.Context, requesterUserID uuid.UUID, input *TeamMemberRemoveInput) error {
if requesterUserID != input.UserID {
- if err := self.checkTeam(ctx, requesterUserID, schema.ActionAdmin, input.TeamID); err != nil {
+ if _, err := self.authorize(ctx, requesterUserID, schema.ActionAdmin, input.TeamID, input.ProjectID); err != nil {
return err
}
}
- roleGroups, err := self.repo.Team().GetRoleGroups(ctx, input.TeamID)
+ roleGroups, err := self.roleGroups(ctx, input.TeamID, input.ProjectID)
if err != nil {
return err
}
current := groupHoldingUser(roleGroups, input.UserID)
if current == nil {
- return errdefs.NewCustomError(errdefs.ErrTypeNotFound, "User is not a member of this team")
+ return notAMember(input.ProjectID)
}
return self.repo.Group().RemoveUser(ctx, current.ID, input.UserID)
}
+func (self *TeamService) authorize(ctx context.Context, requesterUserID uuid.UUID, action schema.PermittedAction, teamID uuid.UUID, projectID *uuid.UUID) (*ent.Project, error) {
+ if projectID == nil {
+ return nil, self.checkTeam(ctx, requesterUserID, action, teamID)
+ }
+
+ err := self.repo.Permissions().Check(ctx, requesterUserID, []permissions_repo.PermissionCheck{
+ {
+ Action: action,
+ ResourceType: schema.ResourceTypeProject,
+ ResourceID: *projectID,
+ },
+ })
+ if err != nil {
+ return nil, err
+ }
+
+ project, err := self.repo.Project().GetByID(ctx, *projectID)
+ if err != nil && !ent.IsNotFound(err) {
+ return nil, err
+ }
+ if err != nil || project.TeamID != teamID {
+ return nil, errdefs.NewCustomError(errdefs.ErrTypeNotFound, "Project not found")
+ }
+ return project, nil
+}
+
+func (self *TeamService) roleGroups(ctx context.Context, teamID uuid.UUID, projectID *uuid.UUID) ([]*ent.Group, error) {
+ if projectID == nil {
+ return self.repo.Team().GetRoleGroups(ctx, teamID)
+ }
+ return self.repo.Team().GetProjectRoleGroups(ctx, *projectID)
+}
+
+func (self *TeamService) roleGroupsToJoin(ctx context.Context, teamID uuid.UUID, project *ent.Project) ([]*ent.Group, error) {
+ if project == nil {
+ return self.repo.Team().GetRoleGroups(ctx, teamID)
+ }
+ return self.repo.Team().EnsureProjectRoleGroups(ctx, nil, project)
+}
+
+func (self *TeamService) groupsReaching(ctx context.Context, teamID uuid.UUID, projectID *uuid.UUID) ([]*ent.Group, error) {
+ if projectID == nil {
+ return self.repo.Team().GetGroupsReachingTeam(ctx, teamID)
+ }
+ return self.repo.Team().GetGroupsReachingProject(ctx, teamID, *projectID)
+}
+
func (self *TeamService) checkTeam(ctx context.Context, requesterUserID uuid.UUID, action schema.PermittedAction, teamID uuid.UUID) error {
return self.repo.Permissions().Check(ctx, requesterUserID, []permissions_repo.PermissionCheck{
{
@@ -200,16 +252,53 @@ func userIn(group *ent.Group, userID uuid.UUID) *ent.User {
return nil
}
-// grantedRole is the strongest role a group's team grants give on the team.
-func grantedRole(group *ent.Group, teamID uuid.UUID) schema.PermittedAction {
+// grantedRole is the strongest role a group's grants give on the team or project.
+func grantedRole(group *ent.Group, scope team_repo.MemberScope) schema.PermittedAction {
var best schema.PermittedAction
- for _, p := range group.Edges.Permissions {
- if p.ResourceType != schema.ResourceTypeTeam {
- continue
- }
- if p.ResourceSelector.Superuser || p.ResourceSelector.ID == teamID {
- best = permissions_repo.StrongerAction(best, p.Action)
+ for _, grant := range group.Edges.Permissions {
+ if scope.ReachedBy(grant) {
+ best = permissions_repo.StrongerAction(best, grant.Action)
}
}
return best
}
+
+func directSource(projectID *uuid.UUID) string {
+ if projectID == nil {
+ return models.TeamMemberSourceTeam
+ }
+ return models.TeamMemberSourceProject
+}
+
+func directMember(user *ent.User, role schema.PermittedAction, projectID *uuid.UUID) *models.TeamMemberResponse {
+ if projectID == nil {
+ return models.TransformTeamMember(user, role)
+ }
+ return models.TransformProjectMember(user, role)
+}
+
+func inheritedMember(user *ent.User, role schema.PermittedAction, group *ent.Group, teamID uuid.UUID) *models.TeamMemberResponse {
+ isRoleGroupOfTheTeam := group.TeamID != nil && *group.TeamID == teamID
+ if isRoleGroupOfTheTeam {
+ return models.TransformTeamMember(user, role)
+ }
+ return models.TransformInheritedTeamMember(user, role, group.Name)
+}
+
+func scopeNoun(projectID *uuid.UUID) string {
+ if projectID == nil {
+ return "team"
+ }
+ return "project"
+}
+
+func notAMember(projectID *uuid.UUID) error {
+ return errdefs.NewCustomError(errdefs.ErrTypeNotFound, fmt.Sprintf("User is not a member of this %s", scopeNoun(projectID)))
+}
+
+func missingRoleGroup(teamID uuid.UUID, projectID *uuid.UUID, role schema.PermittedAction) error {
+ if projectID == nil {
+ return fmt.Errorf("team %s has no %s role group", teamID, role)
+ }
+ return fmt.Errorf("project %s has no %s role group", *projectID, role)
+}
diff --git a/apps/api/internal/services/team/members_test.go b/apps/api/internal/services/team/members_test.go
index 4097c2b4b..e4f638eef 100644
--- a/apps/api/internal/services/team/members_test.go
+++ b/apps/api/internal/services/team/members_test.go
@@ -111,7 +111,7 @@ func (suite *MembersSuite) TestListMembersShowsInheritedAccessWithoutOverridingD
suite.MockTeamRepo.EXPECT().GetRoleGroups(suite.Ctx, suite.teamID).Return(suite.groups, nil).Once()
suite.MockTeamRepo.EXPECT().GetGroupsReachingTeam(suite.Ctx, suite.teamID).Return([]*ent.Group{superusers}, nil).Once()
- members, err := suite.service.ListMembers(suite.Ctx, suite.adminID, suite.teamID)
+ members, err := suite.service.ListMembers(suite.Ctx, suite.adminID, suite.teamID, nil)
suite.Require().NoError(err)
suite.Require().Len(members, 2)
@@ -125,6 +125,78 @@ func (suite *MembersSuite) TestListMembersShowsInheritedAccessWithoutOverridingD
suite.Equal("superuser", *members[1].GroupName)
}
+func (suite *MembersSuite) projectWithRoleGroups() (*ent.Project, []*ent.Group) {
+ project := &ent.Project{ID: uuid.New(), Name: "Web", TeamID: suite.teamID}
+ groups := make([]*ent.Group, 0, 3)
+ for _, role := range []schema.PermittedAction{schema.ActionAdmin, schema.ActionEditor, schema.ActionViewer} {
+ groups = append(groups, &ent.Group{ID: uuid.New(), Name: "project-web-" + string(role), ProjectID: &project.ID, Role: new(role)})
+ }
+ return project, groups
+}
+
+func (suite *MembersSuite) expectProjectCheck(action schema.PermittedAction, projectID uuid.UUID) {
+ suite.MockPermissionsRepo.EXPECT().
+ Check(suite.Ctx, suite.adminID, []permissions_repo.PermissionCheck{{Action: action, ResourceType: schema.ResourceTypeProject, ResourceID: projectID}}).
+ Return(nil).Once()
+}
+
+func (suite *MembersSuite) TestAddProjectMemberJoinsTheProjectRoleGroupOnly() {
+ project, projectGroups := suite.projectWithRoleGroups()
+ suite.expectProjectCheck(schema.ActionAdmin, project.ID)
+ suite.MockProjectRepo.EXPECT().GetByID(suite.Ctx, project.ID).Return(project, nil).Once()
+ suite.MockUserRepo.EXPECT().GetByEmail(suite.Ctx, "dev@example.com").Return(suite.member, nil).Once()
+ suite.MockTeamRepo.EXPECT().EnsureProjectRoleGroups(suite.Ctx, nil, project).Return(projectGroups, nil).Once()
+ suite.MockGroupRepo.EXPECT().AddUser(suite.Ctx, projectGroups[2].ID, suite.member.ID).Return(nil).Once()
+
+ added, err := suite.service.AddMember(suite.Ctx, suite.adminID, &TeamMemberAddInput{TeamID: suite.teamID, ProjectID: &project.ID, Email: "dev@example.com", Role: schema.ActionViewer})
+ suite.Require().NoError(err)
+ suite.Equal(schema.ActionViewer, added.Role)
+ suite.Equal(models.TeamMemberSourceProject, added.Source)
+}
+
+func (suite *MembersSuite) TestProjectOfAnotherTeamIsNotFound() {
+ project := &ent.Project{ID: uuid.New(), TeamID: uuid.New()}
+ suite.expectProjectCheck(schema.ActionAdmin, project.ID)
+ suite.MockProjectRepo.EXPECT().GetByID(suite.Ctx, project.ID).Return(project, nil).Once()
+
+ _, err := suite.service.AddMember(suite.Ctx, suite.adminID, &TeamMemberAddInput{TeamID: suite.teamID, ProjectID: &project.ID, Email: "dev@example.com", Role: schema.ActionViewer})
+ suite.ErrorIs(err, errdefs.ErrNotFound)
+}
+
+func (suite *MembersSuite) TestListProjectMembersShowsTeamMembersAsInherited() {
+ project, projectGroups := suite.projectWithRoleGroups()
+ guest := &ent.User{ID: uuid.New(), Email: "guest@example.com"}
+ projectGroups[0].Edges.Users = []*ent.User{guest, suite.member}
+ teamGrant := func(action schema.PermittedAction) []*ent.Permission {
+ return []*ent.Permission{{Action: action, ResourceType: schema.ResourceTypeTeam, ResourceSelector: schema.ResourceSelector{ID: suite.teamID}}}
+ }
+ owner := &ent.User{ID: uuid.New(), Email: "owner@example.com"}
+ suite.adminGrp.Edges.Users = []*ent.User{owner}
+ suite.adminGrp.Edges.Permissions = teamGrant(schema.ActionAdmin)
+ suite.editorGrp.Edges.Permissions = teamGrant(schema.ActionEditor)
+
+ suite.expectProjectCheck(schema.ActionViewer, project.ID)
+ suite.MockProjectRepo.EXPECT().GetByID(suite.Ctx, project.ID).Return(project, nil).Once()
+ suite.MockTeamRepo.EXPECT().GetProjectRoleGroups(suite.Ctx, project.ID).Return(projectGroups, nil).Once()
+ suite.MockTeamRepo.EXPECT().GetGroupsReachingProject(suite.Ctx, suite.teamID, project.ID).Return([]*ent.Group{suite.adminGrp, suite.editorGrp}, nil).Once()
+
+ members, err := suite.service.ListMembers(suite.Ctx, suite.adminID, suite.teamID, &project.ID)
+ suite.Require().NoError(err)
+ suite.Require().Len(members, 3)
+
+ suite.Equal("dev@example.com", members[0].Email)
+ suite.Equal(schema.ActionAdmin, members[0].Role, "the role held on the project is the one listed")
+ suite.Equal(models.TeamMemberSourceProject, members[0].Source)
+
+ suite.Equal("guest@example.com", members[1].Email)
+ suite.Equal(models.TeamMemberSourceProject, members[1].Source)
+
+ suite.Equal("owner@example.com", members[2].Email)
+ suite.Equal(schema.ActionAdmin, members[2].Role)
+ suite.Equal(models.TeamMemberSourceTeam, members[2].Source)
+ suite.Nil(members[2].GroupName)
+}
+
func TestMembersSuite(t *testing.T) {
suite.Run(t, new(MembersSuite))
}
diff --git a/apps/api/mocks/repository/team/team_repository_mock.go b/apps/api/mocks/repository/team/team_repository_mock.go
index 3c6bb6ba6..6fe37c3ef 100644
--- a/apps/api/mocks/repository/team/team_repository_mock.go
+++ b/apps/api/mocks/repository/team/team_repository_mock.go
@@ -338,16 +338,16 @@ func (_c *TeamRepositoryMock_DeleteIcon_Call) RunAndReturn(run func(ctx context.
}
// DeleteInvitation provides a mock function for the type TeamRepositoryMock
-func (_mock *TeamRepositoryMock) DeleteInvitation(ctx context.Context, teamID uuid.UUID, invitationID uuid.UUID) error {
- ret := _mock.Called(ctx, teamID, invitationID)
+func (_mock *TeamRepositoryMock) DeleteInvitation(ctx context.Context, teamID uuid.UUID, projectID *uuid.UUID, invitationID uuid.UUID) error {
+ ret := _mock.Called(ctx, teamID, projectID, invitationID)
if len(ret) == 0 {
panic("no return value specified for DeleteInvitation")
}
var r0 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, uuid.UUID) error); ok {
- r0 = returnFunc(ctx, teamID, invitationID)
+ if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, *uuid.UUID, uuid.UUID) error); ok {
+ r0 = returnFunc(ctx, teamID, projectID, invitationID)
} else {
r0 = ret.Error(0)
}
@@ -362,12 +362,13 @@ type TeamRepositoryMock_DeleteInvitation_Call struct {
// DeleteInvitation is a helper method to define mock.On call
// - ctx context.Context
// - teamID uuid.UUID
+// - projectID *uuid.UUID
// - invitationID uuid.UUID
-func (_e *TeamRepositoryMock_Expecter) DeleteInvitation(ctx any, teamID any, invitationID any) *TeamRepositoryMock_DeleteInvitation_Call {
- return &TeamRepositoryMock_DeleteInvitation_Call{Call: _e.mock.On("DeleteInvitation", ctx, teamID, invitationID)}
+func (_e *TeamRepositoryMock_Expecter) DeleteInvitation(ctx any, teamID any, projectID any, invitationID any) *TeamRepositoryMock_DeleteInvitation_Call {
+ return &TeamRepositoryMock_DeleteInvitation_Call{Call: _e.mock.On("DeleteInvitation", ctx, teamID, projectID, invitationID)}
}
-func (_c *TeamRepositoryMock_DeleteInvitation_Call) Run(run func(ctx context.Context, teamID uuid.UUID, invitationID uuid.UUID)) *TeamRepositoryMock_DeleteInvitation_Call {
+func (_c *TeamRepositoryMock_DeleteInvitation_Call) Run(run func(ctx context.Context, teamID uuid.UUID, projectID *uuid.UUID, invitationID uuid.UUID)) *TeamRepositoryMock_DeleteInvitation_Call {
_c.Call.Run(func(args mock.Arguments) {
var arg0 context.Context
if args[0] != nil {
@@ -377,14 +378,19 @@ func (_c *TeamRepositoryMock_DeleteInvitation_Call) Run(run func(ctx context.Con
if args[1] != nil {
arg1 = args[1].(uuid.UUID)
}
- var arg2 uuid.UUID
+ var arg2 *uuid.UUID
if args[2] != nil {
- arg2 = args[2].(uuid.UUID)
+ arg2 = args[2].(*uuid.UUID)
+ }
+ var arg3 uuid.UUID
+ if args[3] != nil {
+ arg3 = args[3].(uuid.UUID)
}
run(
arg0,
arg1,
arg2,
+ arg3,
)
})
return _c
@@ -395,7 +401,81 @@ func (_c *TeamRepositoryMock_DeleteInvitation_Call) Return(err error) *TeamRepos
return _c
}
-func (_c *TeamRepositoryMock_DeleteInvitation_Call) RunAndReturn(run func(ctx context.Context, teamID uuid.UUID, invitationID uuid.UUID) error) *TeamRepositoryMock_DeleteInvitation_Call {
+func (_c *TeamRepositoryMock_DeleteInvitation_Call) RunAndReturn(run func(ctx context.Context, teamID uuid.UUID, projectID *uuid.UUID, invitationID uuid.UUID) error) *TeamRepositoryMock_DeleteInvitation_Call {
+ _c.Call.Return(run)
+ return _c
+}
+
+// EnsureProjectRoleGroups provides a mock function for the type TeamRepositoryMock
+func (_mock *TeamRepositoryMock) EnsureProjectRoleGroups(ctx context.Context, tx repository.TxInterface, project *ent.Project) ([]*ent.Group, error) {
+ ret := _mock.Called(ctx, tx, project)
+
+ if len(ret) == 0 {
+ panic("no return value specified for EnsureProjectRoleGroups")
+ }
+
+ var r0 []*ent.Group
+ var r1 error
+ if returnFunc, ok := ret.Get(0).(func(context.Context, repository.TxInterface, *ent.Project) ([]*ent.Group, error)); ok {
+ return returnFunc(ctx, tx, project)
+ }
+ if returnFunc, ok := ret.Get(0).(func(context.Context, repository.TxInterface, *ent.Project) []*ent.Group); ok {
+ r0 = returnFunc(ctx, tx, project)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).([]*ent.Group)
+ }
+ }
+ if returnFunc, ok := ret.Get(1).(func(context.Context, repository.TxInterface, *ent.Project) error); ok {
+ r1 = returnFunc(ctx, tx, project)
+ } else {
+ r1 = ret.Error(1)
+ }
+ return r0, r1
+}
+
+// TeamRepositoryMock_EnsureProjectRoleGroups_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'EnsureProjectRoleGroups'
+type TeamRepositoryMock_EnsureProjectRoleGroups_Call struct {
+ *mock.Call
+}
+
+// EnsureProjectRoleGroups is a helper method to define mock.On call
+// - ctx context.Context
+// - tx repository.TxInterface
+// - project *ent.Project
+func (_e *TeamRepositoryMock_Expecter) EnsureProjectRoleGroups(ctx any, tx any, project any) *TeamRepositoryMock_EnsureProjectRoleGroups_Call {
+ return &TeamRepositoryMock_EnsureProjectRoleGroups_Call{Call: _e.mock.On("EnsureProjectRoleGroups", ctx, tx, project)}
+}
+
+func (_c *TeamRepositoryMock_EnsureProjectRoleGroups_Call) Run(run func(ctx context.Context, tx repository.TxInterface, project *ent.Project)) *TeamRepositoryMock_EnsureProjectRoleGroups_Call {
+ _c.Call.Run(func(args mock.Arguments) {
+ var arg0 context.Context
+ if args[0] != nil {
+ arg0 = args[0].(context.Context)
+ }
+ var arg1 repository.TxInterface
+ if args[1] != nil {
+ arg1 = args[1].(repository.TxInterface)
+ }
+ var arg2 *ent.Project
+ if args[2] != nil {
+ arg2 = args[2].(*ent.Project)
+ }
+ run(
+ arg0,
+ arg1,
+ arg2,
+ )
+ })
+ return _c
+}
+
+func (_c *TeamRepositoryMock_EnsureProjectRoleGroups_Call) Return(groups []*ent.Group, err error) *TeamRepositoryMock_EnsureProjectRoleGroups_Call {
+ _c.Call.Return(groups, err)
+ return _c
+}
+
+func (_c *TeamRepositoryMock_EnsureProjectRoleGroups_Call) RunAndReturn(run func(ctx context.Context, tx repository.TxInterface, project *ent.Project) ([]*ent.Group, error)) *TeamRepositoryMock_EnsureProjectRoleGroups_Call {
_c.Call.Return(run)
return _c
}
@@ -610,6 +690,80 @@ func (_c *TeamRepositoryMock_GetByID_Call) RunAndReturn(run func(ctx context.Con
return _c
}
+// GetGroupsReachingProject provides a mock function for the type TeamRepositoryMock
+func (_mock *TeamRepositoryMock) GetGroupsReachingProject(ctx context.Context, teamID uuid.UUID, projectID uuid.UUID) ([]*ent.Group, error) {
+ ret := _mock.Called(ctx, teamID, projectID)
+
+ if len(ret) == 0 {
+ panic("no return value specified for GetGroupsReachingProject")
+ }
+
+ var r0 []*ent.Group
+ var r1 error
+ if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, uuid.UUID) ([]*ent.Group, error)); ok {
+ return returnFunc(ctx, teamID, projectID)
+ }
+ if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, uuid.UUID) []*ent.Group); ok {
+ r0 = returnFunc(ctx, teamID, projectID)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).([]*ent.Group)
+ }
+ }
+ if returnFunc, ok := ret.Get(1).(func(context.Context, uuid.UUID, uuid.UUID) error); ok {
+ r1 = returnFunc(ctx, teamID, projectID)
+ } else {
+ r1 = ret.Error(1)
+ }
+ return r0, r1
+}
+
+// TeamRepositoryMock_GetGroupsReachingProject_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetGroupsReachingProject'
+type TeamRepositoryMock_GetGroupsReachingProject_Call struct {
+ *mock.Call
+}
+
+// GetGroupsReachingProject is a helper method to define mock.On call
+// - ctx context.Context
+// - teamID uuid.UUID
+// - projectID uuid.UUID
+func (_e *TeamRepositoryMock_Expecter) GetGroupsReachingProject(ctx any, teamID any, projectID any) *TeamRepositoryMock_GetGroupsReachingProject_Call {
+ return &TeamRepositoryMock_GetGroupsReachingProject_Call{Call: _e.mock.On("GetGroupsReachingProject", ctx, teamID, projectID)}
+}
+
+func (_c *TeamRepositoryMock_GetGroupsReachingProject_Call) Run(run func(ctx context.Context, teamID uuid.UUID, projectID uuid.UUID)) *TeamRepositoryMock_GetGroupsReachingProject_Call {
+ _c.Call.Run(func(args mock.Arguments) {
+ var arg0 context.Context
+ if args[0] != nil {
+ arg0 = args[0].(context.Context)
+ }
+ var arg1 uuid.UUID
+ if args[1] != nil {
+ arg1 = args[1].(uuid.UUID)
+ }
+ var arg2 uuid.UUID
+ if args[2] != nil {
+ arg2 = args[2].(uuid.UUID)
+ }
+ run(
+ arg0,
+ arg1,
+ arg2,
+ )
+ })
+ return _c
+}
+
+func (_c *TeamRepositoryMock_GetGroupsReachingProject_Call) Return(groups []*ent.Group, err error) *TeamRepositoryMock_GetGroupsReachingProject_Call {
+ _c.Call.Return(groups, err)
+ return _c
+}
+
+func (_c *TeamRepositoryMock_GetGroupsReachingProject_Call) RunAndReturn(run func(ctx context.Context, teamID uuid.UUID, projectID uuid.UUID) ([]*ent.Group, error)) *TeamRepositoryMock_GetGroupsReachingProject_Call {
+ _c.Call.Return(run)
+ return _c
+}
+
// GetGroupsReachingTeam provides a mock function for the type TeamRepositoryMock
func (_mock *TeamRepositoryMock) GetGroupsReachingTeam(ctx context.Context, teamID uuid.UUID) ([]*ent.Group, error) {
ret := _mock.Called(ctx, teamID)
@@ -949,8 +1103,8 @@ func (_c *TeamRepositoryMock_GetNamespace_Call) RunAndReturn(run func(ctx contex
}
// GetPendingInvitations provides a mock function for the type TeamRepositoryMock
-func (_mock *TeamRepositoryMock) GetPendingInvitations(ctx context.Context, teamID uuid.UUID) ([]*ent.Invitation, error) {
- ret := _mock.Called(ctx, teamID)
+func (_mock *TeamRepositoryMock) GetPendingInvitations(ctx context.Context, teamID uuid.UUID, projectID *uuid.UUID) ([]*ent.Invitation, error) {
+ ret := _mock.Called(ctx, teamID, projectID)
if len(ret) == 0 {
panic("no return value specified for GetPendingInvitations")
@@ -958,18 +1112,18 @@ func (_mock *TeamRepositoryMock) GetPendingInvitations(ctx context.Context, team
var r0 []*ent.Invitation
var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID) ([]*ent.Invitation, error)); ok {
- return returnFunc(ctx, teamID)
+ if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, *uuid.UUID) ([]*ent.Invitation, error)); ok {
+ return returnFunc(ctx, teamID, projectID)
}
- if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID) []*ent.Invitation); ok {
- r0 = returnFunc(ctx, teamID)
+ if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, *uuid.UUID) []*ent.Invitation); ok {
+ r0 = returnFunc(ctx, teamID, projectID)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).([]*ent.Invitation)
}
}
- if returnFunc, ok := ret.Get(1).(func(context.Context, uuid.UUID) error); ok {
- r1 = returnFunc(ctx, teamID)
+ if returnFunc, ok := ret.Get(1).(func(context.Context, uuid.UUID, *uuid.UUID) error); ok {
+ r1 = returnFunc(ctx, teamID, projectID)
} else {
r1 = ret.Error(1)
}
@@ -984,11 +1138,12 @@ type TeamRepositoryMock_GetPendingInvitations_Call struct {
// GetPendingInvitations is a helper method to define mock.On call
// - ctx context.Context
// - teamID uuid.UUID
-func (_e *TeamRepositoryMock_Expecter) GetPendingInvitations(ctx any, teamID any) *TeamRepositoryMock_GetPendingInvitations_Call {
- return &TeamRepositoryMock_GetPendingInvitations_Call{Call: _e.mock.On("GetPendingInvitations", ctx, teamID)}
+// - projectID *uuid.UUID
+func (_e *TeamRepositoryMock_Expecter) GetPendingInvitations(ctx any, teamID any, projectID any) *TeamRepositoryMock_GetPendingInvitations_Call {
+ return &TeamRepositoryMock_GetPendingInvitations_Call{Call: _e.mock.On("GetPendingInvitations", ctx, teamID, projectID)}
}
-func (_c *TeamRepositoryMock_GetPendingInvitations_Call) Run(run func(ctx context.Context, teamID uuid.UUID)) *TeamRepositoryMock_GetPendingInvitations_Call {
+func (_c *TeamRepositoryMock_GetPendingInvitations_Call) Run(run func(ctx context.Context, teamID uuid.UUID, projectID *uuid.UUID)) *TeamRepositoryMock_GetPendingInvitations_Call {
_c.Call.Run(func(args mock.Arguments) {
var arg0 context.Context
if args[0] != nil {
@@ -998,9 +1153,14 @@ func (_c *TeamRepositoryMock_GetPendingInvitations_Call) Run(run func(ctx contex
if args[1] != nil {
arg1 = args[1].(uuid.UUID)
}
+ var arg2 *uuid.UUID
+ if args[2] != nil {
+ arg2 = args[2].(*uuid.UUID)
+ }
run(
arg0,
arg1,
+ arg2,
)
})
return _c
@@ -1011,7 +1171,75 @@ func (_c *TeamRepositoryMock_GetPendingInvitations_Call) Return(invitations []*e
return _c
}
-func (_c *TeamRepositoryMock_GetPendingInvitations_Call) RunAndReturn(run func(ctx context.Context, teamID uuid.UUID) ([]*ent.Invitation, error)) *TeamRepositoryMock_GetPendingInvitations_Call {
+func (_c *TeamRepositoryMock_GetPendingInvitations_Call) RunAndReturn(run func(ctx context.Context, teamID uuid.UUID, projectID *uuid.UUID) ([]*ent.Invitation, error)) *TeamRepositoryMock_GetPendingInvitations_Call {
+ _c.Call.Return(run)
+ return _c
+}
+
+// GetProjectRoleGroups provides a mock function for the type TeamRepositoryMock
+func (_mock *TeamRepositoryMock) GetProjectRoleGroups(ctx context.Context, projectID uuid.UUID) ([]*ent.Group, error) {
+ ret := _mock.Called(ctx, projectID)
+
+ if len(ret) == 0 {
+ panic("no return value specified for GetProjectRoleGroups")
+ }
+
+ var r0 []*ent.Group
+ var r1 error
+ if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID) ([]*ent.Group, error)); ok {
+ return returnFunc(ctx, projectID)
+ }
+ if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID) []*ent.Group); ok {
+ r0 = returnFunc(ctx, projectID)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).([]*ent.Group)
+ }
+ }
+ if returnFunc, ok := ret.Get(1).(func(context.Context, uuid.UUID) error); ok {
+ r1 = returnFunc(ctx, projectID)
+ } else {
+ r1 = ret.Error(1)
+ }
+ return r0, r1
+}
+
+// TeamRepositoryMock_GetProjectRoleGroups_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetProjectRoleGroups'
+type TeamRepositoryMock_GetProjectRoleGroups_Call struct {
+ *mock.Call
+}
+
+// GetProjectRoleGroups is a helper method to define mock.On call
+// - ctx context.Context
+// - projectID uuid.UUID
+func (_e *TeamRepositoryMock_Expecter) GetProjectRoleGroups(ctx any, projectID any) *TeamRepositoryMock_GetProjectRoleGroups_Call {
+ return &TeamRepositoryMock_GetProjectRoleGroups_Call{Call: _e.mock.On("GetProjectRoleGroups", ctx, projectID)}
+}
+
+func (_c *TeamRepositoryMock_GetProjectRoleGroups_Call) Run(run func(ctx context.Context, projectID uuid.UUID)) *TeamRepositoryMock_GetProjectRoleGroups_Call {
+ _c.Call.Run(func(args mock.Arguments) {
+ var arg0 context.Context
+ if args[0] != nil {
+ arg0 = args[0].(context.Context)
+ }
+ var arg1 uuid.UUID
+ if args[1] != nil {
+ arg1 = args[1].(uuid.UUID)
+ }
+ run(
+ arg0,
+ arg1,
+ )
+ })
+ return _c
+}
+
+func (_c *TeamRepositoryMock_GetProjectRoleGroups_Call) Return(groups []*ent.Group, err error) *TeamRepositoryMock_GetProjectRoleGroups_Call {
+ _c.Call.Return(groups, err)
+ return _c
+}
+
+func (_c *TeamRepositoryMock_GetProjectRoleGroups_Call) RunAndReturn(run func(ctx context.Context, projectID uuid.UUID) ([]*ent.Group, error)) *TeamRepositoryMock_GetProjectRoleGroups_Call {
_c.Call.Return(run)
return _c
}
diff --git a/apps/docs/content/(platform)/teams/members-and-permissions.mdx b/apps/docs/content/(platform)/teams/members-and-permissions.mdx
index 50975e13d..3feac7979 100644
--- a/apps/docs/content/(platform)/teams/members-and-permissions.mdx
+++ b/apps/docs/content/(platform)/teams/members-and-permissions.mdx
@@ -42,9 +42,26 @@ Instance owners can also create accounts without an invitation, from the server
Use the menu on a member's row. Removing someone takes away the role they had on this team and nothing else. Their account, their other teams and their API keys stay as they are.
+## Project members
+
+To give someone one project and nothing else in the team, add them to the project instead of the team. **Project** > **Settings** > **Members** works like the team's page: press **Invite**, enter an email address and pick a role. Project admins manage it, and so do team admins.
+
+A project member:
+
+- sees the team with that one project in it. Other projects, team members, team variables, team volumes and S3 storage stay hidden.
+- does in the project what their role allows: an editor deploys and changes services, an admin also deletes and invites others to the project.
+- can create [API keys](/api/authentication) and approve [connected apps](/api/connected-apps), including for MCP. They reach that project only.
+- cannot create projects in the team.
+
+The page lists everyone who can open the project. Team members are on it too, marked as coming from the team, because a role on the team covers all of its projects. Change those on the team's page.
+
+Someone can be on a team and on one of its projects at once. The stronger role applies in that project. A viewer on the team who is an admin on one project is an admin there and a viewer everywhere else.
+
+Invitations to a project are listed on the project's page, not the team's. Deleting a project removes its members and pending invitations.
+
## Groups
-Under the hood a role on a team is a group with that one permission, and every team has an admin, editor and viewer group. These groups are managed from the members page and cannot be renamed, deleted or changed through the group endpoints. Instance owners can still make groups of their own for finer grants, such as an editor on one service.
+Under the hood a role on a team is a group with that one permission, and every team has an admin, editor and viewer group. A project gets the same three groups when its first member is added. These groups are managed from the members pages and cannot be renamed, deleted or changed through the group endpoints. Instance owners can still make groups of their own for finer grants, such as an editor on one service.
## Roles for API keys and apps
diff --git a/apps/docs/content/api/index.mdx b/apps/docs/content/api/index.mdx
index 50c41a1f4..bf2576aae 100644
--- a/apps/docs/content/api/index.mdx
+++ b/apps/docs/content/api/index.mdx
@@ -87,4 +87,4 @@ Names are unique among siblings and case sensitive. Creating or renaming into a
## What is in the reference
-The [reference](/api/reference/teams/list-teams) lists every operation an API key can call. A few areas are left out because they only work from a signed-in browser session: managing API keys and connected apps, connecting GitHub, system settings including email, users and groups, creating and deleting teams, team members and invitations, and the terminal.
+The [reference](/api/reference/teams/list-teams) lists every operation an API key can call. A few areas are left out because they only work from a signed-in browser session: managing API keys and connected apps, connecting GitHub, system settings including email, users and groups, creating and deleting teams, team and project members and invitations, and the terminal.
diff --git a/apps/web/src/components/team/settings/members/invitation-card.tsx b/apps/web/src/components/team/settings/members/invitation-card.tsx
index 89d22f436..a414f3ef0 100644
--- a/apps/web/src/components/team/settings/members/invitation-card.tsx
+++ b/apps/web/src/components/team/settings/members/invitation-card.tsx
@@ -43,7 +43,11 @@ export default function InvitationCard({ invitation }: { invitation: TTeamInvita
onDialogClose={reset}
error={error}
onSubmit={async () => {
- await revoke({ teamId: invitation.team_id, invitationId: invitation.id });
+ await revoke({
+ teamId: invitation.team_id,
+ projectId: invitation.project_id,
+ invitationId: invitation.id,
+ });
}}
>
{inherited && (
- {roleTitle(member.role)} via {member.group_name}
+ {roleTitle(member.role)} via {member.group_name ?? `the ${member.source}`}
)}
@@ -73,12 +73,12 @@ export default function MemberCard({ member, isPlaceholder }: TProps) {
disabled={isUpdatingRole}
onChange={(role) => {
if (role === member.role) return;
- updateRole({ teamId, userId: member.id, role });
+ updateRole({ teamId, projectId, userId: member.id, role });
}}
/>
{
- await removeMember({ teamId, userId: member.id });
+ await removeMember({ teamId, projectId, userId: member.id });
}}
>