Skip to content

A continuation of HomeBox the inventory and organization system built for the Home User

fix: bugs around groups

Matthew Kilgoreed3216a80998
diff --git a/backend/app/api/handlers/v1/v1_ctrl_actions.go b/backend/app/api/handlers/v1/v1_ctrl_actions.go
index 765d6791..e6a08dd9 100644
--- a/backend/app/api/handlers/v1/v1_ctrl_actions.go
+++ b/backend/app/api/handlers/v1/v1_ctrl_actions.go
@@ -122,8 +122,11 @@ func (ctrl *V1Controller) HandleWipeInventory() errchain.HandlerFunc {
ctx := services.NewContext(r.Context())
- // Check if user is owner
- if !ctx.User.IsOwner {
+ isOwner, err := ctrl.repo.Groups.IsOwnerOf(ctx, ctx.UID, ctx.GID)
+ if err != nil {
+ return validate.NewRequestError(err, http.StatusInternalServerError)
+ }
+ if !isOwner {
return validate.NewRequestError(errors.New("only group owners can wipe inventory"), http.StatusForbidden)
}
diff --git a/backend/app/api/handlers/v1/v1_ctrl_group.go b/backend/app/api/handlers/v1/v1_ctrl_group.go
index a0ad1bf0..534297b7 100644
--- a/backend/app/api/handlers/v1/v1_ctrl_group.go
+++ b/backend/app/api/handlers/v1/v1_ctrl_group.go
@@ -28,10 +28,6 @@ type (
Uses int `json:"uses"`
}
- GroupMemberAdd struct {
- UserID uuid.UUID `json:"userId" validate:"required"`
- }
-
GroupAcceptInvitationResponse struct {
ID uuid.UUID `json:"id"`
Name string `json:"name"`
@@ -231,25 +227,6 @@ func (ctrl *V1Controller) HandleGroupMembersGetAll() errchain.HandlerFunc {
return adapters.Command(fn, http.StatusOK)
}
-// HandleGroupMemberAdd godoc
-//
-// @Summary Add User to Group
-// @Tags Group
-// @Produce json
-// @Param payload body GroupMemberAdd true "User ID"
-// @Success 204
-// @Router /v1/groups/members [Post]
-// @Security Bearer
-func (ctrl *V1Controller) HandleGroupMemberAdd() errchain.HandlerFunc {
- fn := func(r *http.Request, body GroupMemberAdd) (any, error) {
- auth := services.NewContext(r.Context())
- err := ctrl.svc.Group.AddMember(auth, body.UserID)
- return nil, err
- }
-
- return adapters.Action(fn, http.StatusNoContent)
-}
-
// HandleGroupMemberRemove godoc
//
// @Summary Remove User from Group
diff --git a/backend/app/api/handlers/v1/v1_ctrl_maintenance.go b/backend/app/api/handlers/v1/v1_ctrl_maintenance.go
index becab81b..0d5d9776 100644
--- a/backend/app/api/handlers/v1/v1_ctrl_maintenance.go
+++ b/backend/app/api/handlers/v1/v1_ctrl_maintenance.go
@@ -41,7 +41,7 @@ func (ctrl *V1Controller) HandleMaintenanceGetAll() errchain.HandlerFunc {
func (ctrl *V1Controller) HandleMaintenanceEntryUpdate() errchain.HandlerFunc {
fn := func(r *http.Request, entryID uuid.UUID, body repo.MaintenanceEntryUpdate) (repo.MaintenanceEntry, error) {
auth := services.NewContext(r.Context())
- return ctrl.repo.MaintEntry.Update(auth, entryID, body)
+ return ctrl.repo.MaintEntry.Update(auth, auth.GID, entryID, body)
}
return adapters.ActionID("id", fn, http.StatusOK)
@@ -59,7 +59,7 @@ func (ctrl *V1Controller) HandleMaintenanceEntryUpdate() errchain.HandlerFunc {
func (ctrl *V1Controller) HandleMaintenanceEntryDelete() errchain.HandlerFunc {
fn := func(r *http.Request, entryID uuid.UUID) (any, error) {
auth := services.NewContext(r.Context())
- err := ctrl.repo.MaintEntry.Delete(auth, entryID)
+ err := ctrl.repo.MaintEntry.Delete(auth, auth.GID, entryID)
return nil, err
}
diff --git a/backend/app/api/routes.go b/backend/app/api/routes.go
index 473470ff..e354e181 100644
--- a/backend/app/api/routes.go
+++ b/backend/app/api/routes.go
@@ -125,7 +125,6 @@ func (a *app) mountRoutes(r *chi.Mux, chain *errchain.ErrChain, repos *repo.AllR
r.Delete("/groups", chain.ToHandlerFunc(v1Ctrl.HandleGroupDelete(), userMW...))
r.Get("/groups/members", chain.ToHandlerFunc(v1Ctrl.HandleGroupMembersGetAll(), userMW...))
- r.Post("/groups/members", chain.ToHandlerFunc(v1Ctrl.HandleGroupMemberAdd(), userMW...))
r.Delete("/groups/members/{user_id}", chain.ToHandlerFunc(v1Ctrl.HandleGroupMemberRemove(), userMW...))
r.Get("/groups/invitations", chain.ToHandlerFunc(v1Ctrl.HandleGroupInvitationsGetAll(), userMW...))
diff --git a/backend/internal/core/services/service_group.go b/backend/internal/core/services/service_group.go
index eaac5afa..6a8501f6 100644
--- a/backend/internal/core/services/service_group.go
+++ b/backend/internal/core/services/service_group.go
@@ -56,14 +56,6 @@ func (svc *GroupService) NewInvitation(ctx Context, uses int, expiresAt time.Tim
return invitation, token.Raw, nil
}
-func (svc *GroupService) AddMember(ctx Context, userID uuid.UUID) error {
- if userID == uuid.Nil {
- return errors.New("user ID cannot be empty")
- }
-
- return svc.repos.Groups.AddMember(ctx.Context, ctx.GID, userID)
-}
-
func (svc *GroupService) RemoveMember(ctx Context, userID uuid.UUID) error {
if userID == uuid.Nil {
return errors.New("user ID cannot be empty")
diff --git a/backend/internal/data/ent/client.go b/backend/internal/data/ent/client.go
index e9fc8975..f3970b48 100644
--- a/backend/internal/data/ent/client.go
+++ b/backend/internal/data/ent/client.go
@@ -31,6 +31,7 @@ import (
"github.com/sysadminsmedia/homebox/backend/internal/data/ent/tag"
"github.com/sysadminsmedia/homebox/backend/internal/data/ent/templatefield"
"github.com/sysadminsmedia/homebox/backend/internal/data/ent/user"
+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent/usergroup"
)
// Client is the client that holds all ent builders.
@@ -68,6 +69,8 @@ type Client struct {
TemplateField *TemplateFieldClient
// User is the client for interacting with the User builders.
User *UserClient
+ // UserGroup is the client for interacting with the UserGroup builders.
+ UserGroup *UserGroupClient
}
// NewClient creates a new client configured with the given options.
@@ -94,6 +97,7 @@ func (c *Client) init() {
c.Tag = NewTagClient(c.config)
c.TemplateField = NewTemplateFieldClient(c.config)
c.User = NewUserClient(c.config)
+ c.UserGroup = NewUserGroupClient(c.config)
}
type (
@@ -201,6 +205,7 @@ func (c *Client) Tx(ctx context.Context) (*Tx, error) {
Tag: NewTagClient(cfg),
TemplateField: NewTemplateFieldClient(cfg),
User: NewUserClient(cfg),
+ UserGroup: NewUserGroupClient(cfg),
}, nil
}
@@ -235,6 +240,7 @@ func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error)
Tag: NewTagClient(cfg),
TemplateField: NewTemplateFieldClient(cfg),
User: NewUserClient(cfg),
+ UserGroup: NewUserGroupClient(cfg),
}, nil
}
@@ -266,7 +272,7 @@ func (c *Client) Use(hooks ...Hook) {
for _, n := range []interface{ Use(...Hook) }{
c.APIKey, c.Attachment, c.AuthRoles, c.AuthTokens, c.Entity, c.EntityField,
c.EntityTemplate, c.EntityType, c.Group, c.GroupInvitationToken,
- c.MaintenanceEntry, c.Notifier, c.Tag, c.TemplateField, c.User,
+ c.MaintenanceEntry, c.Notifier, c.Tag, c.TemplateField, c.User, c.UserGroup,
} {
n.Use(hooks...)
}
@@ -278,7 +284,7 @@ func (c *Client) Intercept(interceptors ...Interceptor) {
for _, n := range []interface{ Intercept(...Interceptor) }{
c.APIKey, c.Attachment, c.AuthRoles, c.AuthTokens, c.Entity, c.EntityField,
c.EntityTemplate, c.EntityType, c.Group, c.GroupInvitationToken,
- c.MaintenanceEntry, c.Notifier, c.Tag, c.TemplateField, c.User,
+ c.MaintenanceEntry, c.Notifier, c.Tag, c.TemplateField, c.User, c.UserGroup,
} {
n.Intercept(interceptors...)
}
@@ -317,6 +323,8 @@ func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) {
return c.TemplateField.mutate(ctx, m)
case *UserMutation:
return c.User.mutate(ctx, m)
+ case *UserGroupMutation:
+ return c.UserGroup.mutate(ctx, m)
default:
return nil, fmt.Errorf("ent: unknown mutation type %T", m)
}
@@ -1942,6 +1950,22 @@ func (c *GroupClient) QueryEntityTemplates(_m *Group) *EntityTemplateQuery {
return query
}
+// QueryUserGroups queries the user_groups edge of a Group.
+func (c *GroupClient) QueryUserGroups(_m *Group) *UserGroupQuery {
+ query := (&UserGroupClient{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(usergroup.Table, usergroup.GroupColumn),
+ sqlgraph.Edge(sqlgraph.O2M, true, group.UserGroupsTable, group.UserGroupsColumn),
+ )
+ 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
@@ -2948,6 +2972,22 @@ func (c *UserClient) QueryNotifiers(_m *User) *NotifierQuery {
return query
}
+// QueryUserGroups queries the user_groups edge of a User.
+func (c *UserClient) QueryUserGroups(_m *User) *UserGroupQuery {
+ query := (&UserGroupClient{config: c.config}).Query()
+ query.path = func(context.Context) (fromV *sql.Selector, _ error) {
+ id := _m.ID
+ step := sqlgraph.NewStep(
+ sqlgraph.From(user.Table, user.FieldID, id),
+ sqlgraph.To(usergroup.Table, usergroup.UserColumn),
+ sqlgraph.Edge(sqlgraph.O2M, true, user.UserGroupsTable, user.UserGroupsColumn),
+ )
+ fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step)
+ return fromV, nil
+ }
+ return query
+}
+
// Hooks returns the client hooks.
func (c *UserClient) Hooks() []Hook {
return c.hooks.User
@@ -2973,16 +3013,132 @@ func (c *UserClient) mutate(ctx context.Context, m *UserMutation) (Value, error)
}
}
+// UserGroupClient is a client for the UserGroup schema.
+type UserGroupClient struct {
+ config
+}
+
+// NewUserGroupClient returns a client for the UserGroup from the given config.
+func NewUserGroupClient(c config) *UserGroupClient {
+ return &UserGroupClient{config: c}
+}
+
+// Use adds a list of mutation hooks to the hooks stack.
+// A call to `Use(f, g, h)` equals to `usergroup.Hooks(f(g(h())))`.
+func (c *UserGroupClient) Use(hooks ...Hook) {
+ c.hooks.UserGroup = append(c.hooks.UserGroup, hooks...)
+}
+
+// Intercept adds a list of query interceptors to the interceptors stack.
+// A call to `Intercept(f, g, h)` equals to `usergroup.Intercept(f(g(h())))`.
+func (c *UserGroupClient) Intercept(interceptors ...Interceptor) {
+ c.inters.UserGroup = append(c.inters.UserGroup, interceptors...)
+}
+
+// Create returns a builder for creating a UserGroup entity.
+func (c *UserGroupClient) Create() *UserGroupCreate {
+ mutation := newUserGroupMutation(c.config, OpCreate)
+ return &UserGroupCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
+}
+
+// CreateBulk returns a builder for creating a bulk of UserGroup entities.
+func (c *UserGroupClient) CreateBulk(builders ...*UserGroupCreate) *UserGroupCreateBulk {
+ return &UserGroupCreateBulk{config: c.config, builders: builders}
+}
+
+// MapCreateBulk creates a bulk creation builder from the given slice. For each item in the slice, the function creates
+// a builder and applies setFunc on it.
+func (c *UserGroupClient) MapCreateBulk(slice any, setFunc func(*UserGroupCreate, int)) *UserGroupCreateBulk {
+ rv := reflect.ValueOf(slice)
+ if rv.Kind() != reflect.Slice {
+ return &UserGroupCreateBulk{err: fmt.Errorf("calling to UserGroupClient.MapCreateBulk with wrong type %T, need slice", slice)}
+ }
+ builders := make([]*UserGroupCreate, rv.Len())
+ for i := 0; i < rv.Len(); i++ {
+ builders[i] = c.Create()
+ setFunc(builders[i], i)
+ }
+ return &UserGroupCreateBulk{config: c.config, builders: builders}
+}
+
+// Update returns an update builder for UserGroup.
+func (c *UserGroupClient) Update() *UserGroupUpdate {
+ mutation := newUserGroupMutation(c.config, OpUpdate)
+ return &UserGroupUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}
+}
+
+// UpdateOne returns an update builder for the given entity.
+func (c *UserGroupClient) UpdateOne(_m *UserGroup) *UserGroupUpdateOne {
+ mutation := newUserGroupMutation(c.config, OpUpdateOne)
+ mutation.user = &_m.UserID
+ mutation.group = &_m.GroupID
+ return &UserGroupUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
+}
+
+// Delete returns a delete builder for UserGroup.
+func (c *UserGroupClient) Delete() *UserGroupDelete {
+ mutation := newUserGroupMutation(c.config, OpDelete)
+ return &UserGroupDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
+}
+
+// Query returns a query builder for UserGroup.
+func (c *UserGroupClient) Query() *UserGroupQuery {
+ return &UserGroupQuery{
+ config: c.config,
+ ctx: &QueryContext{Type: TypeUserGroup},
+ inters: c.Interceptors(),
+ }
+}
+
+// QueryUser queries the user edge of a UserGroup.
+func (c *UserGroupClient) QueryUser(_m *UserGroup) *UserQuery {
+ return c.Query().
+ Where(usergroup.UserID(_m.UserID), usergroup.GroupID(_m.GroupID)).
+ QueryUser()
+}
+
+// QueryGroup queries the group edge of a UserGroup.
+func (c *UserGroupClient) QueryGroup(_m *UserGroup) *GroupQuery {
+ return c.Query().
+ Where(usergroup.UserID(_m.UserID), usergroup.GroupID(_m.GroupID)).
+ QueryGroup()
+}
+
+// Hooks returns the client hooks.
+func (c *UserGroupClient) Hooks() []Hook {
+ return c.hooks.UserGroup
+}
+
+// Interceptors returns the client interceptors.
+func (c *UserGroupClient) Interceptors() []Interceptor {
+ return c.inters.UserGroup
+}
+
+func (c *UserGroupClient) mutate(ctx context.Context, m *UserGroupMutation) (Value, error) {
+ switch m.Op() {
+ case OpCreate:
+ return (&UserGroupCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
+ case OpUpdate:
+ return (&UserGroupUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
+ case OpUpdateOne:
+ return (&UserGroupUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
+ case OpDelete, OpDeleteOne:
+ return (&UserGroupDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx)
+ default:
+ return nil, fmt.Errorf("ent: unknown UserGroup mutation op: %q", m.Op())
+ }
+}
+
// hooks and interceptors per client, for fast access.
type (
hooks struct {
APIKey, Attachment, AuthRoles, AuthTokens, Entity, EntityField, EntityTemplate,
EntityType, Group, GroupInvitationToken, MaintenanceEntry, Notifier, Tag,
- TemplateField, User []ent.Hook
+ TemplateField, User, UserGroup []ent.Hook
}
inters struct {
APIKey, Attachment, AuthRoles, AuthTokens, Entity, EntityField, EntityTemplate,
EntityType, Group, GroupInvitationToken, MaintenanceEntry, Notifier, Tag,
- TemplateField, User []ent.Interceptor
+ TemplateField, User, UserGroup []ent.Interceptor
}
)
diff --git a/backend/internal/data/ent/ent.go b/backend/internal/data/ent/ent.go
index 834abdd7..a6374045 100644
--- a/backend/internal/data/ent/ent.go
+++ b/backend/internal/data/ent/ent.go
@@ -27,6 +27,7 @@ import (
"github.com/sysadminsmedia/homebox/backend/internal/data/ent/tag"
"github.com/sysadminsmedia/homebox/backend/internal/data/ent/templatefield"
"github.com/sysadminsmedia/homebox/backend/internal/data/ent/user"
+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent/usergroup"
)
// ent aliases to avoid import conflicts in user's code.
@@ -102,6 +103,7 @@ func checkColumn(t, c string) error {
tag.Table: tag.ValidColumn,
templatefield.Table: templatefield.ValidColumn,
user.Table: user.ValidColumn,
+ usergroup.Table: usergroup.ValidColumn,
})
})
return columnCheck(t, c)
diff --git a/backend/internal/data/ent/group.go b/backend/internal/data/ent/group.go
index 5061efb1..2a59ead4 100644
--- a/backend/internal/data/ent/group.go
+++ b/backend/internal/data/ent/group.go
@@ -48,9 +48,11 @@ type GroupEdges struct {
Notifiers []*Notifier `json:"notifiers,omitempty"`
// EntityTemplates holds the value of the entity_templates edge.
EntityTemplates []*EntityTemplate `json:"entity_templates,omitempty"`
+ // UserGroups holds the value of the user_groups edge.
+ UserGroups []*UserGroup `json:"user_groups,omitempty"`
// loadedTypes holds the information for reporting if a
// type was loaded (or requested) in eager-loading or not.
- loadedTypes [7]bool
+ loadedTypes [8]bool
}
// UsersOrErr returns the Users value or an error if the edge
@@ -116,6 +118,15 @@ func (e GroupEdges) EntityTemplatesOrErr() ([]*EntityTemplate, error) {
return nil, &NotLoadedError{edge: "entity_templates"}
}
+// UserGroupsOrErr returns the UserGroups value or an error if the edge
+// was not loaded in eager-loading.
+func (e GroupEdges) UserGroupsOrErr() ([]*UserGroup, error) {
+ if e.loadedTypes[7] {
+ return e.UserGroups, nil
+ }
+ return nil, &NotLoadedError{edge: "user_groups"}
+}
+
// scanValues returns the types for scanning values from sql.Rows.
func (*Group) scanValues(columns []string) ([]any, error) {
values := make([]any, len(columns))
@@ -220,6 +231,11 @@ func (_m *Group) QueryEntityTemplates() *EntityTemplateQuery {
return NewGroupClient(_m.config).QueryEntityTemplates(_m)
}
+// QueryUserGroups queries the "user_groups" edge of the Group entity.
+func (_m *Group) QueryUserGroups() *UserGroupQuery {
+ return NewGroupClient(_m.config).QueryUserGroups(_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.
diff --git a/backend/internal/data/ent/group/group.go b/backend/internal/data/ent/group/group.go
index adc26a4e..2be8540c 100644
--- a/backend/internal/data/ent/group/group.go
+++ b/backend/internal/data/ent/group/group.go
@@ -37,6 +37,8 @@ const (
EdgeNotifiers = "notifiers"
// EdgeEntityTemplates holds the string denoting the entity_templates edge name in mutations.
EdgeEntityTemplates = "entity_templates"
+ // EdgeUserGroups holds the string denoting the user_groups edge name in mutations.
+ EdgeUserGroups = "user_groups"
// 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.
@@ -86,6 +88,13 @@ const (
EntityTemplatesInverseTable = "entity_templates"
// EntityTemplatesColumn is the table column denoting the entity_templates relation/edge.
EntityTemplatesColumn = "group_entity_templates"
+ // UserGroupsTable is the table that holds the user_groups relation/edge.
+ UserGroupsTable = "user_groups"
+ // UserGroupsInverseTable is the table name for the UserGroup entity.
+ // It exists in this package in order to avoid circular dependency with the "usergroup" package.
+ UserGroupsInverseTable = "user_groups"
+ // UserGroupsColumn is the table column denoting the user_groups relation/edge.
+ UserGroupsColumn = "group_id"
)
// Columns holds all SQL columns for group fields.
@@ -253,6 +262,20 @@ func ByEntityTemplates(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption {
sqlgraph.OrderByNeighborTerms(s, newEntityTemplatesStep(), append([]sql.OrderTerm{term}, terms...)...)
}
}
+
+// ByUserGroupsCount orders the results by user_groups count.
+func ByUserGroupsCount(opts ...sql.OrderTermOption) OrderOption {
+ return func(s *sql.Selector) {
+ sqlgraph.OrderByNeighborsCount(s, newUserGroupsStep(), opts...)
+ }
+}
+
+// ByUserGroups orders the results by user_groups terms.
+func ByUserGroups(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption {
+ return func(s *sql.Selector) {
+ sqlgraph.OrderByNeighborTerms(s, newUserGroupsStep(), append([]sql.OrderTerm{term}, terms...)...)
+ }
+}
func newUsersStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
@@ -302,3 +325,10 @@ func newEntityTemplatesStep() *sqlgraph.Step {
sqlgraph.Edge(sqlgraph.O2M, false, EntityTemplatesTable, EntityTemplatesColumn),
)
}
+func newUserGroupsStep() *sqlgraph.Step {
+ return sqlgraph.NewStep(
+ sqlgraph.From(Table, FieldID),
+ sqlgraph.To(UserGroupsInverseTable, UserGroupsColumn),
+ sqlgraph.Edge(sqlgraph.O2M, true, UserGroupsTable, UserGroupsColumn),
+ )
+}
diff --git a/backend/internal/data/ent/group/where.go b/backend/internal/data/ent/group/where.go
index d55d0d58..a7f28d99 100644
--- a/backend/internal/data/ent/group/where.go
+++ b/backend/internal/data/ent/group/where.go
@@ -447,6 +447,29 @@ func HasEntityTemplatesWith(preds ...predicate.EntityTemplate) predicate.Group {
})
}
+// HasUserGroups applies the HasEdge predicate on the "user_groups" edge.
+func HasUserGroups() predicate.Group {
+ return predicate.Group(func(s *sql.Selector) {
+ step := sqlgraph.NewStep(
+ sqlgraph.From(Table, FieldID),
+ sqlgraph.Edge(sqlgraph.O2M, true, UserGroupsTable, UserGroupsColumn),
+ )
+ sqlgraph.HasNeighbors(s, step)
+ })
+}
+
+// HasUserGroupsWith applies the HasEdge predicate on the "user_groups" edge with a given conditions (other predicates).
+func HasUserGroupsWith(preds ...predicate.UserGroup) predicate.Group {
+ return predicate.Group(func(s *sql.Selector) {
+ step := newUserGroupsStep()
+ 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/backend/internal/data/ent/group_create.go b/backend/internal/data/ent/group_create.go
index 51f3f1a0..30b6ffbf 100644
--- a/backend/internal/data/ent/group_create.go
+++ b/backend/internal/data/ent/group_create.go
@@ -332,6 +332,10 @@ func (_c *GroupCreate) createSpec() (*Group, *sqlgraph.CreateSpec) {
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
+ createE := &UserGroupCreate{config: _c.config, mutation: newUserGroupMutation(_c.config, OpCreate)}
+ createE.defaults()
+ _, specE := createE.createSpec()
+ edge.Target.Fields = specE.Fields
_spec.Edges = append(_spec.Edges, edge)
}
if nodes := _c.mutation.EntityTypesIDs(); len(nodes) > 0 {
diff --git a/backend/internal/data/ent/group_query.go b/backend/internal/data/ent/group_query.go
index 38bf2925..e22780fc 100644
--- a/backend/internal/data/ent/group_query.go
+++ b/backend/internal/data/ent/group_query.go
@@ -22,6 +22,7 @@ import (
"github.com/sysadminsmedia/homebox/backend/internal/data/ent/predicate"
"github.com/sysadminsmedia/homebox/backend/internal/data/ent/tag"
"github.com/sysadminsmedia/homebox/backend/internal/data/ent/user"
+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent/usergroup"
)
// GroupQuery is the builder for querying Group entities.
@@ -38,6 +39,7 @@ type GroupQuery struct {
withInvitationTokens *GroupInvitationTokenQuery
withNotifiers *NotifierQuery
withEntityTemplates *EntityTemplateQuery
+ withUserGroups *UserGroupQuery
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
@@ -228,6 +230,28 @@ func (_q *GroupQuery) QueryEntityTemplates() *EntityTemplateQuery {
return query
}
+// QueryUserGroups chains the current query on the "user_groups" edge.
+func (_q *GroupQuery) QueryUserGroups() *UserGroupQuery {
+ query := (&UserGroupClient{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(usergroup.Table, usergroup.GroupColumn),
+ sqlgraph.Edge(sqlgraph.O2M, true, group.UserGroupsTable, group.UserGroupsColumn),
+ )
+ 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) {
@@ -427,6 +451,7 @@ func (_q *GroupQuery) Clone() *GroupQuery {
withInvitationTokens: _q.withInvitationTokens.Clone(),
withNotifiers: _q.withNotifiers.Clone(),
withEntityTemplates: _q.withEntityTemplates.Clone(),
+ withUserGroups: _q.withUserGroups.Clone(),
// clone intermediate query.
sql: _q.sql.Clone(),
path: _q.path,
@@ -510,6 +535,17 @@ func (_q *GroupQuery) WithEntityTemplates(opts ...func(*EntityTemplateQuery)) *G
return _q
}
+// WithUserGroups tells the query-builder to eager-load the nodes that are connected to
+// the "user_groups" edge. The optional arguments are used to configure the query builder of the edge.
+func (_q *GroupQuery) WithUserGroups(opts ...func(*UserGroupQuery)) *GroupQuery {
+ query := (&UserGroupClient{config: _q.config}).Query()
+ for _, opt := range opts {
+ opt(query)
+ }
+ _q.withUserGroups = 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.
//
@@ -588,7 +624,7 @@ func (_q *GroupQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Group,
var (
nodes = []*Group{}
_spec = _q.querySpec()
- loadedTypes = [7]bool{
+ loadedTypes = [8]bool{
_q.withUsers != nil,
_q.withEntityTypes != nil,
_q.withEntities != nil,
@@ -596,6 +632,7 @@ func (_q *GroupQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Group,
_q.withInvitationTokens != nil,
_q.withNotifiers != nil,
_q.withEntityTemplates != nil,
+ _q.withUserGroups != nil,
}
)
_spec.ScanValues = func(columns []string) ([]any, error) {
@@ -667,6 +704,13 @@ func (_q *GroupQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Group,
return nil, err
}
}
+ if query := _q.withUserGroups; query != nil {
+ if err := _q.loadUserGroups(ctx, query, nodes,
+ func(n *Group) { n.Edges.UserGroups = []*UserGroup{} },
+ func(n *Group, e *UserGroup) { n.Edges.UserGroups = append(n.Edges.UserGroups, e) }); err != nil {
+ return nil, err
+ }
+ }
return nodes, nil
}
@@ -916,6 +960,36 @@ func (_q *GroupQuery) loadEntityTemplates(ctx context.Context, query *EntityTemp
}
return nil
}
+func (_q *GroupQuery) loadUserGroups(ctx context.Context, query *UserGroupQuery, nodes []*Group, init func(*Group), assign func(*Group, *UserGroup)) error {
+ fks := make([]driver.Value, 0, len(nodes))
+ nodeids := make(map[uuid.UUID]*Group)
+ 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(usergroup.FieldGroupID)
+ }
+ query.Where(predicate.UserGroup(func(s *sql.Selector) {
+ s.Where(sql.InValues(s.C(group.UserGroupsColumn), fks...))
+ }))
+ neighbors, err := query.All(ctx)
+ if err != nil {
+ return err
+ }
+ for _, n := range neighbors {
+ fk := n.GroupID
+ node, ok := nodeids[fk]
+ if !ok {
+ return fmt.Errorf(`unexpected referenced foreign-key "group_id" returned %v for node %v`, fk, n)
+ }
+ assign(node, n)
+ }
+ return nil
+}
func (_q *GroupQuery) sqlCount(ctx context.Context) (int, error) {
_spec := _q.querySpec()
diff --git a/backend/internal/data/ent/group_update.go b/backend/internal/data/ent/group_update.go
index 254c8d7a..51458c0c 100644
--- a/backend/internal/data/ent/group_update.go
+++ b/backend/internal/data/ent/group_update.go
@@ -405,6 +405,10 @@ func (_u *GroupUpdate) sqlSave(ctx context.Context) (_node int, err error) {
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID),
},
}
+ createE := &UserGroupCreate{config: _u.config, mutation: newUserGroupMutation(_u.config, OpCreate)}
+ createE.defaults()
+ _, specE := createE.createSpec()
+ edge.Target.Fields = specE.Fields
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.RemovedUsersIDs(); len(nodes) > 0 && !_u.mutation.UsersCleared() {
@@ -421,6 +425,10 @@ func (_u *GroupUpdate) sqlSave(ctx context.Context) (_node int, err error) {
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
+ createE := &UserGroupCreate{config: _u.config, mutation: newUserGroupMutation(_u.config, OpCreate)}
+ createE.defaults()
+ _, specE := createE.createSpec()
+ edge.Target.Fields = specE.Fields
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.UsersIDs(); len(nodes) > 0 {
@@ -437,6 +445,10 @@ func (_u *GroupUpdate) sqlSave(ctx context.Context) (_node int, err error) {
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
+ createE := &UserGroupCreate{config: _u.config, mutation: newUserGroupMutation(_u.config, OpCreate)}
+ createE.defaults()
+ _, specE := createE.createSpec()
+ edge.Target.Fields = specE.Fields
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if _u.mutation.EntityTypesCleared() {
@@ -1128,6 +1140,10 @@ func (_u *GroupUpdateOne) sqlSave(ctx context.Context) (_node *Group, err error)
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID),
},
}
+ createE := &UserGroupCreate{config: _u.config, mutation: newUserGroupMutation(_u.config, OpCreate)}
+ createE.defaults()
+ _, specE := createE.createSpec()
+ edge.Target.Fields = specE.Fields
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.RemovedUsersIDs(); len(nodes) > 0 && !_u.mutation.UsersCleared() {
@@ -1144,6 +1160,10 @@ func (_u *GroupUpdateOne) sqlSave(ctx context.Context) (_node *Group, err error)
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
+ createE := &UserGroupCreate{config: _u.config, mutation: newUserGroupMutation(_u.config, OpCreate)}
+ createE.defaults()
+ _, specE := createE.createSpec()
+ edge.Target.Fields = specE.Fields
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.UsersIDs(); len(nodes) > 0 {
@@ -1160,6 +1180,10 @@ func (_u *GroupUpdateOne) sqlSave(ctx context.Context) (_node *Group, err error)
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
+ createE := &UserGroupCreate{config: _u.config, mutation: newUserGroupMutation(_u.config, OpCreate)}
+ createE.defaults()
+ _, specE := createE.createSpec()
+ edge.Target.Fields = specE.Fields
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if _u.mutation.EntityTypesCleared() {
diff --git a/backend/internal/data/ent/hook/hook.go b/backend/internal/data/ent/hook/hook.go
index cc26469c..675f999b 100644
--- a/backend/internal/data/ent/hook/hook.go
+++ b/backend/internal/data/ent/hook/hook.go
@@ -189,6 +189,18 @@ func (f UserFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error)
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.UserMutation", m)
}
+// The UserGroupFunc type is an adapter to allow the use of ordinary
+// function as UserGroup mutator.
+type UserGroupFunc func(context.Context, *ent.UserGroupMutation) (ent.Value, error)
+
+// Mutate calls f(ctx, m).
+func (f UserGroupFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
+ if mv, ok := m.(*ent.UserGroupMutation); ok {
+ return f(ctx, mv)
+ }
+ return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.UserGroupMutation", m)
+}
+
// Condition is a hook condition function.
type Condition func(context.Context, ent.Mutation) bool
diff --git a/backend/internal/data/ent/migrate/schema.go b/backend/internal/data/ent/migrate/schema.go
index e53a7883..294a7a2e 100644
--- a/backend/internal/data/ent/migrate/schema.go
+++ b/backend/internal/data/ent/migrate/schema.go
@@ -3,6 +3,7 @@
package migrate
import (
+ "entgo.io/ent/dialect/entsql"
"entgo.io/ent/dialect/sql/schema"
"entgo.io/ent/schema/field"
)
@@ -514,7 +515,6 @@ var (
{Name: "password", Type: field.TypeString, Nullable: true, Size: 255},
{Name: "is_superuser", Type: field.TypeBool, Default: false},
{Name: "superuser", Type: field.TypeBool, Default: false},
- {Name: "role", Type: field.TypeEnum, Enums: []string{"user", "owner"}, Default: "user"},
{Name: "activated_on", Type: field.TypeTime, Nullable: true},
{Name: "oidc_issuer", Type: field.TypeString, Nullable: true},
{Name: "oidc_subject", Type: field.TypeString, Nullable: true},
@@ -530,7 +530,33 @@ var (
{
Name: "user_oidc_issuer_oidc_subject",
Unique: true,
- Columns: []*schema.Column{UsersColumns[10], UsersColumns[11]},
+ Columns: []*schema.Column{UsersColumns[9], UsersColumns[10]},
+ },
+ },
+ }
+ // UserGroupsColumns holds the columns for the "user_groups" table.
+ UserGroupsColumns = []*schema.Column{
+ {Name: "role", Type: field.TypeEnum, Enums: []string{"user", "owner"}, Default: "user"},
+ {Name: "user_id", Type: field.TypeUUID},
+ {Name: "group_id", Type: field.TypeUUID},
+ }
+ // UserGroupsTable holds the schema information for the "user_groups" table.
+ UserGroupsTable = &schema.Table{
+ Name: "user_groups",
+ Columns: UserGroupsColumns,
+ PrimaryKey: []*schema.Column{UserGroupsColumns[1], UserGroupsColumns[2]},
+ ForeignKeys: []*schema.ForeignKey{
+ {
+ Symbol: "user_groups_users_user",
+ Columns: []*schema.Column{UserGroupsColumns[1]},
+ RefColumns: []*schema.Column{UsersColumns[0]},
+ OnDelete: schema.Cascade,
+ },
+ {
+ Symbol: "user_groups_groups_group",
+ Columns: []*schema.Column{UserGroupsColumns[2]},
+ RefColumns: []*schema.Column{GroupsColumns[0]},
+ OnDelete: schema.Cascade,
},
},
}
@@ -559,31 +585,6 @@ var (
},
},
}
- // UserGroupsColumns holds the columns for the "user_groups" table.
- UserGroupsColumns = []*schema.Column{
- {Name: "user_id", Type: field.TypeUUID},
- {Name: "group_id", Type: field.TypeUUID},
- }
- // UserGroupsTable holds the schema information for the "user_groups" table.
- UserGroupsTable = &schema.Table{
- Name: "user_groups",
- Columns: UserGroupsColumns,
- PrimaryKey: []*schema.Column{UserGroupsColumns[0], UserGroupsColumns[1]},
- ForeignKeys: []*schema.ForeignKey{
- {
- Symbol: "user_groups_user_id",
- Columns: []*schema.Column{UserGroupsColumns[0]},
- RefColumns: []*schema.Column{UsersColumns[0]},
- OnDelete: schema.Cascade,
- },
- {
- Symbol: "user_groups_group_id",
- Columns: []*schema.Column{UserGroupsColumns[1]},
- RefColumns: []*schema.Column{GroupsColumns[0]},
- OnDelete: schema.Cascade,
- },
- },
- }
// Tables holds all the tables in the schema.
Tables = []*schema.Table{
APIKeysTable,
@@ -601,8 +602,8 @@ var (
TagsTable,
TemplateFieldsTable,
UsersTable,
- TagEntitiesTable,
UserGroupsTable,
+ TagEntitiesTable,
}
)
@@ -627,8 +628,11 @@ func init() {
TagsTable.ForeignKeys[0].RefTable = GroupsTable
TagsTable.ForeignKeys[1].RefTable = TagsTable
TemplateFieldsTable.ForeignKeys[0].RefTable = EntityTemplatesTable
- TagEntitiesTable.ForeignKeys[0].RefTable = TagsTable
- TagEntitiesTable.ForeignKeys[1].RefTable = EntitiesTable
UserGroupsTable.ForeignKeys[0].RefTable = UsersTable
UserGroupsTable.ForeignKeys[1].RefTable = GroupsTable
+ UserGroupsTable.Annotation = &entsql.Annotation{
+ Table: "user_groups",
+ }
+ TagEntitiesTable.ForeignKeys[0].RefTable = TagsTable
+ TagEntitiesTable.ForeignKeys[1].RefTable = EntitiesTable
}
diff --git a/backend/internal/data/ent/mutation.go b/backend/internal/data/ent/mutation.go
index dbbd2c89..694ad0e3 100644
--- a/backend/internal/data/ent/mutation.go
+++ b/backend/internal/data/ent/mutation.go
@@ -28,6 +28,7 @@ import (
"github.com/sysadminsmedia/homebox/backend/internal/data/ent/tag"
"github.com/sysadminsmedia/homebox/backend/internal/data/ent/templatefield"
"github.com/sysadminsmedia/homebox/backend/internal/data/ent/user"
+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent/usergroup"
)
const (
@@ -54,6 +55,7 @@ const (
TypeTag = "Tag"
TypeTemplateField = "TemplateField"
TypeUser = "User"
+ TypeUserGroup = "UserGroup"
)
// APIKeyMutation represents an operation that mutates the APIKey nodes in the graph.
@@ -13809,7 +13811,6 @@ type UserMutation struct {
password *string
is_superuser *bool
superuser *bool
- role *user.Role
activated_on *time.Time
oidc_issuer *string
oidc_subject *string
@@ -14202,42 +14203,6 @@ func (m *UserMutation) ResetSuperuser() {
m.superuser = nil
}
-// SetRole sets the "role" field.
-func (m *UserMutation) SetRole(u user.Role) {
- m.role = &u
-}
-
-// Role returns the value of the "role" field in the mutation.
-func (m *UserMutation) Role() (r user.Role, exists bool) {
- v := m.role
- if v == nil {
- return
- }
- return *v, true
-}
-
-// OldRole returns the old "role" field's value of the User entity.
-// If the User 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 *UserMutation) OldRole(ctx context.Context) (v user.Role, err error) {
- if !m.op.Is(OpUpdateOne) {
- return v, errors.New("OldRole is only allowed on UpdateOne operations")
- }
- if m.id == nil || m.oldValue == nil {
- return v, errors.New("OldRole requires an ID field in the mutation")
- }
- oldValue, err := m.oldValue(ctx)
- if err != nil {
- return v, fmt.Errorf("querying old value for OldRole: %w", err)
- }
- return oldValue.Role, nil
-}
-
-// ResetRole resets all changes to the "role" field.
-func (m *UserMutation) ResetRole() {
- m.role = nil
-}
-
// SetActivatedOn sets the "activated_on" field.
func (m *UserMutation) SetActivatedOn(t time.Time) {
m.activated_on = &t
@@ -14733,7 +14698,7 @@ func (m *UserMutation) Type() string {
// order to get all numeric fields that were incremented/decremented, call
// AddedFields().
func (m *UserMutation) Fields() []string {
- fields := make([]string, 0, 13)
+ fields := make([]string, 0, 12)
if m.created_at != nil {
fields = append(fields, user.FieldCreatedAt)
}
@@ -14755,9 +14720,6 @@ func (m *UserMutation) Fields() []string {
if m.superuser != nil {
fields = append(fields, user.FieldSuperuser)
}
- if m.role != nil {
- fields = append(fields, user.FieldRole)
- }
if m.activated_on != nil {
fields = append(fields, user.FieldActivatedOn)
}
@@ -14795,8 +14757,6 @@ func (m *UserMutation) Field(name string) (ent.Value, bool) {
return m.IsSuperuser()
case user.FieldSuperuser:
return m.Superuser()
- case user.FieldRole:
- return m.Role()
case user.FieldActivatedOn:
return m.ActivatedOn()
case user.FieldOidcIssuer:
@@ -14830,8 +14790,6 @@ func (m *UserMutation) OldField(ctx context.Context, name string) (ent.Value, er
return m.OldIsSuperuser(ctx)
case user.FieldSuperuser:
return m.OldSuperuser(ctx)
- case user.FieldRole:
- return m.OldRole(ctx)
case user.FieldActivatedOn:
return m.OldActivatedOn(ctx)
case user.FieldOidcIssuer:
@@ -14900,13 +14858,6 @@ func (m *UserMutation) SetField(name string, value ent.Value) error {
}
m.SetSuperuser(v)
return nil
- case user.FieldRole:
- v, ok := value.(user.Role)
- if !ok {
- return fmt.Errorf("unexpected type %T for field %s", value, name)
- }
- m.SetRole(v)
- return nil
case user.FieldActivatedOn:
v, ok := value.(time.Time)
if !ok {
@@ -15051,9 +15002,6 @@ func (m *UserMutation) ResetField(name string) error {
case user.FieldSuperuser:
m.ResetSuperuser()
return nil
- case user.FieldRole:
- m.ResetRole()
- return nil
case user.FieldActivatedOn:
m.ResetActivatedOn()
return nil
@@ -15234,3 +15182,417 @@ func (m *UserMutation) ResetEdge(name string) error {
}
return fmt.Errorf("unknown User edge %s", name)
}
+
+// UserGroupMutation represents an operation that mutates the UserGroup nodes in the graph.
+type UserGroupMutation struct {
+ config
+ op Op
+ typ string
+ role *usergroup.Role
+ clearedFields map[string]struct{}
+ user *uuid.UUID
+ cleareduser bool
+ group *uuid.UUID
+ clearedgroup bool
+ done bool
+ oldValue func(context.Context) (*UserGroup, error)
+ predicates []predicate.UserGroup
+}
+
+var _ ent.Mutation = (*UserGroupMutation)(nil)
+
+// usergroupOption allows management of the mutation configuration using functional options.
+type usergroupOption func(*UserGroupMutation)
+
+// newUserGroupMutation creates new mutation for the UserGroup entity.
+func newUserGroupMutation(c config, op Op, opts ...usergroupOption) *UserGroupMutation {
+ m := &UserGroupMutation{
+ config: c,
+ op: op,
+ typ: TypeUserGroup,
+ clearedFields: make(map[string]struct{}),
+ }
+ for _, opt := range opts {
+ opt(m)
+ }
+ return m
+}
+
+// Client returns a new `ent.Client` from the mutation. If the mutation was
+// executed in a transaction (ent.Tx), a transactional client is returned.
+func (m UserGroupMutation) Client() *Client {
+ client := &Client{config: m.config}
+ client.init()
+ return client
+}
+
+// Tx returns an `ent.Tx` for mutations that were executed in transactions;
+// it returns an error otherwise.
+func (m UserGroupMutation) Tx() (*Tx, error) {
+ if _, ok := m.driver.(*txDriver); !ok {
+ return nil, errors.New("ent: mutation is not running in a transaction")
+ }
+ tx := &Tx{config: m.config}
+ tx.init()
+ return tx, nil
+}
+
+// SetUserID sets the "user_id" field.
+func (m *UserGroupMutation) SetUserID(u uuid.UUID) {
+ m.user = &u
+}
+
+// UserID returns the value of the "user_id" field in the mutation.
+func (m *UserGroupMutation) UserID() (r uuid.UUID, exists bool) {
+ v := m.user
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// ResetUserID resets all changes to the "user_id" field.
+func (m *UserGroupMutation) ResetUserID() {
+ m.user = nil
+}
+
+// SetGroupID sets the "group_id" field.
+func (m *UserGroupMutation) SetGroupID(u uuid.UUID) {
+ m.group = &u
+}
+
+// GroupID returns the value of the "group_id" field in the mutation.
+func (m *UserGroupMutation) GroupID() (r uuid.UUID, exists bool) {
+ v := m.group
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// ResetGroupID resets all changes to the "group_id" field.
+func (m *UserGroupMutation) ResetGroupID() {
+ m.group = nil
+}
+
+// SetRole sets the "role" field.
+func (m *UserGroupMutation) SetRole(u usergroup.Role) {
+ m.role = &u
+}
+
+// Role returns the value of the "role" field in the mutation.
+func (m *UserGroupMutation) Role() (r usergroup.Role, exists bool) {
+ v := m.role
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// ResetRole resets all changes to the "role" field.
+func (m *UserGroupMutation) ResetRole() {
+ m.role = nil
+}
+
+// ClearUser clears the "user" edge to the User entity.
+func (m *UserGroupMutation) ClearUser() {
+ m.cleareduser = true
+ m.clearedFields[usergroup.FieldUserID] = struct{}{}
+}
+
+// UserCleared reports if the "user" edge to the User entity was cleared.
+func (m *UserGroupMutation) UserCleared() bool {
+ return m.cleareduser
+}
+
+// UserIDs returns the "user" edge IDs in the mutation.
+// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use
+// UserID instead. It exists only for internal usage by the builders.
+func (m *UserGroupMutation) UserIDs() (ids []uuid.UUID) {
+ if id := m.user; id != nil {
+ ids = append(ids, *id)
+ }
+ return
+}
+
+// ResetUser resets all changes to the "user" edge.
+func (m *UserGroupMutation) ResetUser() {
+ m.user = nil
+ m.cleareduser = false
+}
+
+// ClearGroup clears the "group" edge to the Group entity.
+func (m *UserGroupMutation) ClearGroup() {
+ m.clearedgroup = true
+ m.clearedFields[usergroup.FieldGroupID] = struct{}{}
+}
+
+// GroupCleared reports if the "group" edge to the Group entity was cleared.
+func (m *UserGroupMutation) GroupCleared() bool {
+ return m.clearedgroup
+}
+
+// GroupIDs returns the "group" edge IDs in the mutation.
+// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use
+// GroupID instead. It exists only for internal usage by the builders.
+func (m *UserGroupMutation) GroupIDs() (ids []uuid.UUID) {
+ if id := m.group; id != nil {
+ ids = append(ids, *id)
+ }
+ return
+}
+
+// ResetGroup resets all changes to the "group" edge.
+func (m *UserGroupMutation) ResetGroup() {
+ m.group = nil
+ m.clearedgroup = false
+}
+
+// Where appends a list predicates to the UserGroupMutation builder.
+func (m *UserGroupMutation) Where(ps ...predicate.UserGroup) {
+ m.predicates = append(m.predicates, ps...)
+}
+
+// WhereP appends storage-level predicates to the UserGroupMutation builder. Using this method,
+// users can use type-assertion to append predicates that do not depend on any generated package.
+func (m *UserGroupMutation) WhereP(ps ...func(*sql.Selector)) {
+ p := make([]predicate.UserGroup, len(ps))
+ for i := range ps {
+ p[i] = ps[i]
+ }
+ m.Where(p...)
+}
+
+// Op returns the operation name.
+func (m *UserGroupMutation) Op() Op {
+ return m.op
+}
+
+// SetOp allows setting the mutation operation.
+func (m *UserGroupMutation) SetOp(op Op) {
+ m.op = op
+}
+
+// Type returns the node type of this mutation (UserGroup).
+func (m *UserGroupMutation) Type() string {
+ return m.typ
+}
+
+// Fields returns all fields that were changed during this mutation. Note that in
+// order to get all numeric fields that were incremented/decremented, call
+// AddedFields().
+func (m *UserGroupMutation) Fields() []string {
+ fields := make([]string, 0, 3)
+ if m.user != nil {
+ fields = append(fields, usergroup.FieldUserID)
+ }
+ if m.group != nil {
+ fields = append(fields, usergroup.FieldGroupID)
+ }
+ if m.role != nil {
+ fields = append(fields, usergroup.FieldRole)
+ }
+ return fields
+}
+
+// Field returns the value of a field with the given name. The second boolean
+// return value indicates that this field was not set, or was not defined in the
+// schema.
+func (m *UserGroupMutation) Field(name string) (ent.Value, bool) {
+ switch name {
+ case usergroup.FieldUserID:
+ return m.UserID()
+ case usergroup.FieldGroupID:
+ return m.GroupID()
+ case usergroup.FieldRole:
+ return m.Role()
+ }
+ return nil, false
+}
+
+// OldField returns the old value of the field from the database. An error is
+// returned if the mutation operation is not UpdateOne, or the query to the
+// database failed.
+func (m *UserGroupMutation) OldField(ctx context.Context, name string) (ent.Value, error) {
+ return nil, errors.New("edge schema UserGroup does not support getting old values")
+}
+
+// SetField sets the value of a field with the given name. It returns an error if
+// the field is not defined in the schema, or if the type mismatched the field
+// type.
+func (m *UserGroupMutation) SetField(name string, value ent.Value) error {
+ switch name {
+ case usergroup.FieldUserID:
+ v, ok := value.(uuid.UUID)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetUserID(v)
+ return nil
+ case usergroup.FieldGroupID:
+ v, ok := value.(uuid.UUID)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetGroupID(v)
+ return nil
+ case usergroup.FieldRole:
+ v, ok := value.(usergroup.Role)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetRole(v)
+ return nil
+ }
+ return fmt.Errorf("unknown UserGroup field %s", name)
+}
+
+// AddedFields returns all numeric fields that were incremented/decremented during
+// this mutation.
+func (m *UserGroupMutation) AddedFields() []string {
+ return nil
+}
+
+// AddedField returns the numeric value that was incremented/decremented on a field
+// with the given name. The second boolean return value indicates that this field
+// was not set, or was not defined in the schema.
+func (m *UserGroupMutation) AddedField(name string) (ent.Value, bool) {
+ return nil, false
+}
+
+// AddField adds the value to the field with the given name. It returns an error if
+// the field is not defined in the schema, or if the type mismatched the field
+// type.
+func (m *UserGroupMutation) AddField(name string, value ent.Value) error {
+ switch name {
+ }
+ return fmt.Errorf("unknown UserGroup numeric field %s", name)
+}
+
+// ClearedFields returns all nullable fields that were cleared during this
+// mutation.
+func (m *UserGroupMutation) ClearedFields() []string {
+ return nil
+}
+
+// FieldCleared returns a boolean indicating if a field with the given name was
+// cleared in this mutation.
+func (m *UserGroupMutation) FieldCleared(name string) bool {
+ _, ok := m.clearedFields[name]
+ return ok
+}
+
+// ClearField clears the value of the field with the given name. It returns an
+// error if the field is not defined in the schema.
+func (m *UserGroupMutation) ClearField(name string) error {
+ return fmt.Errorf("unknown UserGroup nullable field %s", name)
+}
+
+// ResetField resets all changes in the mutation for the field with the given name.
+// It returns an error if the field is not defined in the schema.
+func (m *UserGroupMutation) ResetField(name string) error {
+ switch name {
+ case usergroup.FieldUserID:
+ m.ResetUserID()
+ return nil
+ case usergroup.FieldGroupID:
+ m.ResetGroupID()
+ return nil
+ case usergroup.FieldRole:
+ m.ResetRole()
+ return nil
+ }
+ return fmt.Errorf("unknown UserGroup field %s", name)
+}
+
+// AddedEdges returns all edge names that were set/added in this mutation.
+func (m *UserGroupMutation) AddedEdges() []string {
+ edges := make([]string, 0, 2)
+ if m.user != nil {
+ edges = append(edges, usergroup.EdgeUser)
+ }
+ if m.group != nil {
+ edges = append(edges, usergroup.EdgeGroup)
+ }
+ return edges
+}
+
+// AddedIDs returns all IDs (to other nodes) that were added for the given edge
+// name in this mutation.
+func (m *UserGroupMutation) AddedIDs(name string) []ent.Value {
+ switch name {
+ case usergroup.EdgeUser:
+ if id := m.user; id != nil {
+ return []ent.Value{*id}
+ }
+ case usergroup.EdgeGroup:
+ if id := m.group; id != nil {
+ return []ent.Value{*id}
+ }
+ }
+ return nil
+}
+
+// RemovedEdges returns all edge names that were removed in this mutation.
+func (m *UserGroupMutation) RemovedEdges() []string {
+ edges := make([]string, 0, 2)
+ return edges
+}
+
+// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with
+// the given name in this mutation.
+func (m *UserGroupMutation) RemovedIDs(name string) []ent.Value {
+ return nil
+}
+
+// ClearedEdges returns all edge names that were cleared in this mutation.
+func (m *UserGroupMutation) ClearedEdges() []string {
+ edges := make([]string, 0, 2)
+ if m.cleareduser {
+ edges = append(edges, usergroup.EdgeUser)
+ }
+ if m.clearedgroup {
+ edges = append(edges, usergroup.EdgeGroup)
+ }
+ return edges
+}
+
+// EdgeCleared returns a boolean which indicates if the edge with the given name
+// was cleared in this mutation.
+func (m *UserGroupMutation) EdgeCleared(name string) bool {
+ switch name {
+ case usergroup.EdgeUser:
+ return m.cleareduser
+ case usergroup.EdgeGroup:
+ return m.clearedgroup
+ }
+ return false
+}
+
+// ClearEdge clears the value of the edge with the given name. It returns an error
+// if that edge is not defined in the schema.
+func (m *UserGroupMutation) ClearEdge(name string) error {
+ switch name {
+ case usergroup.EdgeUser:
+ m.ClearUser()
+ return nil
+ case usergroup.EdgeGroup:
+ m.ClearGroup()
+ return nil
+ }
+ return fmt.Errorf("unknown UserGroup unique edge %s", name)
+}
+
+// ResetEdge resets all changes to the edge with the given name in this mutation.
+// It returns an error if the edge is not defined in the schema.
+func (m *UserGroupMutation) ResetEdge(name string) error {
+ switch name {
+ case usergroup.EdgeUser:
+ m.ResetUser()
+ return nil
+ case usergroup.EdgeGroup:
+ m.ResetGroup()
+ return nil
+ }
+ return fmt.Errorf("unknown UserGroup edge %s", name)
+}
diff --git a/backend/internal/data/ent/predicate/predicate.go b/backend/internal/data/ent/predicate/predicate.go
index c5f8e7af..81ba6ac0 100644
--- a/backend/internal/data/ent/predicate/predicate.go
+++ b/backend/internal/data/ent/predicate/predicate.go
@@ -50,3 +50,6 @@ type TemplateField func(*sql.Selector)
// User is the predicate function for user builders.
type User func(*sql.Selector)
+
+// UserGroup is the predicate function for usergroup builders.
+type UserGroup func(*sql.Selector)
diff --git a/backend/internal/data/ent/runtime.go b/backend/internal/data/ent/runtime.go
index b268e9a8..bc9a2b1f 100644
--- a/backend/internal/data/ent/runtime.go
+++ b/backend/internal/data/ent/runtime.go
@@ -769,4 +769,6 @@ func init() {
userDescID := userMixinFields0[0].Descriptor()
// user.DefaultID holds the default value on creation for the id field.
user.DefaultID = userDescID.Default.(func() uuid.UUID)
+ usergroupFields := schema.UserGroup{}.Fields()
+ _ = usergroupFields
}
diff --git a/backend/internal/data/ent/schema/group.go b/backend/internal/data/ent/schema/group.go
index 7fb84c4e..a3b13449 100644
--- a/backend/internal/data/ent/schema/group.go
+++ b/backend/internal/data/ent/schema/group.go
@@ -42,8 +42,10 @@ func (Group) Edges() []ent.Edge {
}
return []ent.Edge{
- // Use edge.From + Ref("groups") to model M:M between users and groups via junction table
- edge.From("users", User.Type).Ref("groups"),
+ // M:M between users and groups; the user_groups join carries per-membership role.
+ edge.From("users", User.Type).
+ Ref("groups").
+ Through("user_groups", UserGroup.Type),
owned("entity_types", EntityType.Type),
owned("entities", Entity.Type),
owned("tags", Tag.Type),
diff --git a/backend/internal/data/ent/schema/user.go b/backend/internal/data/ent/schema/user.go
index 567b6629..541c810b 100644
--- a/backend/internal/data/ent/schema/user.go
+++ b/backend/internal/data/ent/schema/user.go
@@ -41,9 +41,6 @@ func (User) Fields() []ent.Field {
Default(false),
field.Bool("superuser").
Default(false),
- field.Enum("role").
- Default("user").
- Values("user", "owner"),
field.Time("activated_on").
Optional(),
// OIDC identity mapping fields (issuer + subject)
@@ -71,7 +68,8 @@ func (User) Indexes() []ent.Index {
// Edges of the User.
func (User) Edges() []ent.Edge {
return []ent.Edge{
- edge.To("groups", Group.Type),
+ edge.To("groups", Group.Type).
+ Through("user_groups", UserGroup.Type),
edge.To("auth_tokens", AuthTokens.Type).
Annotations(entsql.Annotation{
OnDelete: entsql.Cascade,
diff --git a/backend/internal/data/ent/schema/user_group.go b/backend/internal/data/ent/schema/user_group.go
new file mode 100644
index 00000000..c6817e3d
--- /dev/null
+++ b/backend/internal/data/ent/schema/user_group.go
@@ -0,0 +1,49 @@
+package schema
+
+import (
+ "entgo.io/ent"
+ "entgo.io/ent/dialect/entsql"
+ "entgo.io/ent/schema"
+ "entgo.io/ent/schema/edge"
+ "entgo.io/ent/schema/field"
+ "github.com/google/uuid"
+)
+
+// UserGroup is the through entity for the User<->Group M:M relation. It carries
+// the per-membership role so that "owner" is scoped to a single group rather
+// than being a global flag on the user.
+type UserGroup struct {
+ ent.Schema
+}
+
+func (UserGroup) Annotations() []schema.Annotation {
+ return []schema.Annotation{
+ field.ID("user_id", "group_id"),
+ entsql.Annotation{Table: "user_groups"},
+ }
+}
+
+func (UserGroup) Fields() []ent.Field {
+ return []ent.Field{
+ field.UUID("user_id", uuid.UUID{}),
+ field.UUID("group_id", uuid.UUID{}),
+ field.Enum("role").
+ Values("user", "owner").
+ Default("user"),
+ }
+}
+
+func (UserGroup) Edges() []ent.Edge {
+ return []ent.Edge{
+ edge.To("user", User.Type).
+ Field("user_id").
+ Unique().
+ Required().
+ Annotations(entsql.Annotation{OnDelete: entsql.Cascade}),
+ edge.To("group", Group.Type).
+ Field("group_id").
+ Unique().
+ Required().
+ Annotations(entsql.Annotation{OnDelete: entsql.Cascade}),
+ }
+}
diff --git a/backend/internal/data/ent/tx.go b/backend/internal/data/ent/tx.go
index c9559986..44faa7e0 100644
--- a/backend/internal/data/ent/tx.go
+++ b/backend/internal/data/ent/tx.go
@@ -42,6 +42,8 @@ type Tx struct {
TemplateField *TemplateFieldClient
// User is the client for interacting with the User builders.
User *UserClient
+ // UserGroup is the client for interacting with the UserGroup builders.
+ UserGroup *UserGroupClient
// lazily loaded.
client *Client
@@ -188,6 +190,7 @@ func (tx *Tx) init() {
tx.Tag = NewTagClient(tx.config)
tx.TemplateField = NewTemplateFieldClient(tx.config)
tx.User = NewUserClient(tx.config)
+ tx.UserGroup = NewUserGroupClient(tx.config)
}
// txDriver wraps the given dialect.Tx with a nop dialect.Driver implementation.
diff --git a/backend/internal/data/ent/user.go b/backend/internal/data/ent/user.go
index f78121f0..efd02498 100644
--- a/backend/internal/data/ent/user.go
+++ b/backend/internal/data/ent/user.go
@@ -33,8 +33,6 @@ type User struct {
IsSuperuser bool `json:"is_superuser,omitempty"`
// Superuser holds the value of the "superuser" field.
Superuser bool `json:"superuser,omitempty"`
- // Role holds the value of the "role" field.
- Role user.Role `json:"role,omitempty"`
// ActivatedOn holds the value of the "activated_on" field.
ActivatedOn time.Time `json:"activated_on,omitempty"`
// OidcIssuer holds the value of the "oidc_issuer" field.
@@ -61,9 +59,11 @@ type UserEdges struct {
APIKeys []*APIKey `json:"api_keys,omitempty"`
// Notifiers holds the value of the notifiers edge.
Notifiers []*Notifier `json:"notifiers,omitempty"`
+ // UserGroups holds the value of the user_groups edge.
+ UserGroups []*UserGroup `json:"user_groups,omitempty"`
// loadedTypes holds the information for reporting if a
// type was loaded (or requested) in eager-loading or not.
- loadedTypes [4]bool
+ loadedTypes [5]bool
}
// GroupsOrErr returns the Groups value or an error if the edge
@@ -102,6 +102,15 @@ func (e UserEdges) NotifiersOrErr() ([]*Notifier, error) {
return nil, &NotLoadedError{edge: "notifiers"}
}
+// UserGroupsOrErr returns the UserGroups value or an error if the edge
+// was not loaded in eager-loading.
+func (e UserEdges) UserGroupsOrErr() ([]*UserGroup, error) {
+ if e.loadedTypes[4] {
+ return e.UserGroups, nil
+ }
+ return nil, &NotLoadedError{edge: "user_groups"}
+}
+
// scanValues returns the types for scanning values from sql.Rows.
func (*User) scanValues(columns []string) ([]any, error) {
values := make([]any, len(columns))
@@ -113,7 +122,7 @@ func (*User) scanValues(columns []string) ([]any, error) {
values[i] = new([]byte)
case user.FieldIsSuperuser, user.FieldSuperuser:
values[i] = new(sql.NullBool)
- case user.FieldName, user.FieldEmail, user.FieldPassword, user.FieldRole, user.FieldOidcIssuer, user.FieldOidcSubject:
+ case user.FieldName, user.FieldEmail, user.FieldPassword, user.FieldOidcIssuer, user.FieldOidcSubject:
values[i] = new(sql.NullString)
case user.FieldCreatedAt, user.FieldUpdatedAt, user.FieldActivatedOn:
values[i] = new(sql.NullTime)
@@ -183,12 +192,6 @@ func (_m *User) assignValues(columns []string, values []any) error {
} else if value.Valid {
_m.Superuser = value.Bool
}
- case user.FieldRole:
- if value, ok := values[i].(*sql.NullString); !ok {
- return fmt.Errorf("unexpected type %T for field role", values[i])
- } else if value.Valid {
- _m.Role = user.Role(value.String)
- }
case user.FieldActivatedOn:
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field activated_on", values[i])
@@ -257,6 +260,11 @@ func (_m *User) QueryNotifiers() *NotifierQuery {
return NewUserClient(_m.config).QueryNotifiers(_m)
}
+// QueryUserGroups queries the "user_groups" edge of the User entity.
+func (_m *User) QueryUserGroups() *UserGroupQuery {
+ return NewUserClient(_m.config).QueryUserGroups(_m)
+}
+
// Update returns a builder for updating this User.
// Note that you need to call User.Unwrap() before calling this method if this User
// was returned from a transaction, and the transaction was committed or rolled back.
@@ -300,9 +308,6 @@ func (_m *User) String() string {
builder.WriteString("superuser=")
builder.WriteString(fmt.Sprintf("%v", _m.Superuser))
builder.WriteString(", ")
- builder.WriteString("role=")
- builder.WriteString(fmt.Sprintf("%v", _m.Role))
- builder.WriteString(", ")
builder.WriteString("activated_on=")
builder.WriteString(_m.ActivatedOn.Format(time.ANSIC))
builder.WriteString(", ")
diff --git a/backend/internal/data/ent/user/user.go b/backend/internal/data/ent/user/user.go
index 97a5e716..4f17abb5 100644
--- a/backend/internal/data/ent/user/user.go
+++ b/backend/internal/data/ent/user/user.go
@@ -3,7 +3,6 @@
package user
import (
- "fmt"
"time"
"entgo.io/ent/dialect/sql"
@@ -30,8 +29,6 @@ const (
FieldIsSuperuser = "is_superuser"
// FieldSuperuser holds the string denoting the superuser field in the database.
FieldSuperuser = "superuser"
- // FieldRole holds the string denoting the role field in the database.
- FieldRole = "role"
// FieldActivatedOn holds the string denoting the activated_on field in the database.
FieldActivatedOn = "activated_on"
// FieldOidcIssuer holds the string denoting the oidc_issuer field in the database.
@@ -50,6 +47,8 @@ const (
EdgeAPIKeys = "api_keys"
// EdgeNotifiers holds the string denoting the notifiers edge name in mutations.
EdgeNotifiers = "notifiers"
+ // EdgeUserGroups holds the string denoting the user_groups edge name in mutations.
+ EdgeUserGroups = "user_groups"
// Table holds the table name of the user in the database.
Table = "users"
// GroupsTable is the table that holds the groups relation/edge. The primary key declared below.
@@ -78,6 +77,13 @@ const (
NotifiersInverseTable = "notifiers"
// NotifiersColumn is the table column denoting the notifiers relation/edge.
NotifiersColumn = "user_id"
+ // UserGroupsTable is the table that holds the user_groups relation/edge.
+ UserGroupsTable = "user_groups"
+ // UserGroupsInverseTable is the table name for the UserGroup entity.
+ // It exists in this package in order to avoid circular dependency with the "usergroup" package.
+ UserGroupsInverseTable = "user_groups"
+ // UserGroupsColumn is the table column denoting the user_groups relation/edge.
+ UserGroupsColumn = "user_id"
)
// Columns holds all SQL columns for user fields.
@@ -90,7 +96,6 @@ var Columns = []string{
FieldPassword,
FieldIsSuperuser,
FieldSuperuser,
- FieldRole,
FieldActivatedOn,
FieldOidcIssuer,
FieldOidcSubject,
@@ -135,32 +140,6 @@ var (
DefaultID func() uuid.UUID
)
-// Role defines the type for the "role" enum field.
-type Role string
-
-// RoleUser is the default value of the Role enum.
-const DefaultRole = RoleUser
-
-// Role values.
-const (
- RoleUser Role = "user"
- RoleOwner Role = "owner"
-)
-
-func (r Role) String() string {
- return string(r)
-}
-
-// RoleValidator is a validator for the "role" field enum values. It is called by the builders before save.
-func RoleValidator(r Role) error {
- switch r {
- case RoleUser, RoleOwner:
- return nil
- default:
- return fmt.Errorf("user: invalid enum value for role field: %q", r)
- }
-}
-
// OrderOption defines the ordering options for the User queries.
type OrderOption func(*sql.Selector)
@@ -204,11 +183,6 @@ func BySuperuser(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldSuperuser, opts...).ToFunc()
}
-// ByRole orders the results by the role field.
-func ByRole(opts ...sql.OrderTermOption) OrderOption {
- return sql.OrderByField(FieldRole, opts...).ToFunc()
-}
-
// ByActivatedOn orders the results by the activated_on field.
func ByActivatedOn(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldActivatedOn, opts...).ToFunc()
@@ -284,6 +258,20 @@ func ByNotifiers(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption {
sqlgraph.OrderByNeighborTerms(s, newNotifiersStep(), append([]sql.OrderTerm{term}, terms...)...)
}
}
+
+// ByUserGroupsCount orders the results by user_groups count.
+func ByUserGroupsCount(opts ...sql.OrderTermOption) OrderOption {
+ return func(s *sql.Selector) {
+ sqlgraph.OrderByNeighborsCount(s, newUserGroupsStep(), opts...)
+ }
+}
+
+// ByUserGroups orders the results by user_groups terms.
+func ByUserGroups(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption {
+ return func(s *sql.Selector) {
+ sqlgraph.OrderByNeighborTerms(s, newUserGroupsStep(), append([]sql.OrderTerm{term}, terms...)...)
+ }
+}
func newGroupsStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
@@ -312,3 +300,10 @@ func newNotifiersStep() *sqlgraph.Step {
sqlgraph.Edge(sqlgraph.O2M, false, NotifiersTable, NotifiersColumn),
)
}
+func newUserGroupsStep() *sqlgraph.Step {
+ return sqlgraph.NewStep(
+ sqlgraph.From(Table, FieldID),
+ sqlgraph.To(UserGroupsInverseTable, UserGroupsColumn),
+ sqlgraph.Edge(sqlgraph.O2M, true, UserGroupsTable, UserGroupsColumn),
+ )
+}
diff --git a/backend/internal/data/ent/user/where.go b/backend/internal/data/ent/user/where.go
index 66209ae8..89d24821 100644
--- a/backend/internal/data/ent/user/where.go
+++ b/backend/internal/data/ent/user/where.go
@@ -416,26 +416,6 @@ func SuperuserNEQ(v bool) predicate.User {
return predicate.User(sql.FieldNEQ(FieldSuperuser, v))
}
-// RoleEQ applies the EQ predicate on the "role" field.
-func RoleEQ(v Role) predicate.User {
- return predicate.User(sql.FieldEQ(FieldRole, v))
-}
-
-// RoleNEQ applies the NEQ predicate on the "role" field.
-func RoleNEQ(v Role) predicate.User {
- return predicate.User(sql.FieldNEQ(FieldRole, v))
-}
-
-// RoleIn applies the In predicate on the "role" field.
-func RoleIn(vs ...Role) predicate.User {
- return predicate.User(sql.FieldIn(FieldRole, vs...))
-}
-
-// RoleNotIn applies the NotIn predicate on the "role" field.
-func RoleNotIn(vs ...Role) predicate.User {
- return predicate.User(sql.FieldNotIn(FieldRole, vs...))
-}
-
// ActivatedOnEQ applies the EQ predicate on the "activated_on" field.
func ActivatedOnEQ(v time.Time) predicate.User {
return predicate.User(sql.FieldEQ(FieldActivatedOn, v))
@@ -788,6 +768,29 @@ func HasNotifiersWith(preds ...predicate.Notifier) predicate.User {
})
}
+// HasUserGroups applies the HasEdge predicate on the "user_groups" edge.
+func HasUserGroups() predicate.User {
+ return predicate.User(func(s *sql.Selector) {
+ step := sqlgraph.NewStep(
+ sqlgraph.From(Table, FieldID),
+ sqlgraph.Edge(sqlgraph.O2M, true, UserGroupsTable, UserGroupsColumn),
+ )
+ sqlgraph.HasNeighbors(s, step)
+ })
+}
+
+// HasUserGroupsWith applies the HasEdge predicate on the "user_groups" edge with a given conditions (other predicates).
+func HasUserGroupsWith(preds ...predicate.UserGroup) predicate.User {
+ return predicate.User(func(s *sql.Selector) {
+ step := newUserGroupsStep()
+ 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.User) predicate.User {
return predicate.User(sql.AndPredicates(predicates...))
diff --git a/backend/internal/data/ent/user_create.go b/backend/internal/data/ent/user_create.go
index e108a076..590303ac 100644
--- a/backend/internal/data/ent/user_create.go
+++ b/backend/internal/data/ent/user_create.go
@@ -107,20 +107,6 @@ func (_c *UserCreate) SetNillableSuperuser(v *bool) *UserCreate {
return _c
}
-// SetRole sets the "role" field.
-func (_c *UserCreate) SetRole(v user.Role) *UserCreate {
- _c.mutation.SetRole(v)
- return _c
-}
-
-// SetNillableRole sets the "role" field if the given value is not nil.
-func (_c *UserCreate) SetNillableRole(v *user.Role) *UserCreate {
- if v != nil {
- _c.SetRole(*v)
- }
- return _c
-}
-
// SetActivatedOn sets the "activated_on" field.
func (_c *UserCreate) SetActivatedOn(v time.Time) *UserCreate {
_c.mutation.SetActivatedOn(v)
@@ -308,10 +294,6 @@ func (_c *UserCreate) defaults() {
v := user.DefaultSuperuser
_c.mutation.SetSuperuser(v)
}
- if _, ok := _c.mutation.Role(); !ok {
- v := user.DefaultRole
- _c.mutation.SetRole(v)
- }
if _, ok := _c.mutation.ID(); !ok {
v := user.DefaultID()
_c.mutation.SetID(v)
@@ -353,14 +335,6 @@ func (_c *UserCreate) check() error {
if _, ok := _c.mutation.Superuser(); !ok {
return &ValidationError{Name: "superuser", err: errors.New(`ent: missing required field "User.superuser"`)}
}
- if _, ok := _c.mutation.Role(); !ok {
- return &ValidationError{Name: "role", err: errors.New(`ent: missing required field "User.role"`)}
- }
- if v, ok := _c.mutation.Role(); ok {
- if err := user.RoleValidator(v); err != nil {
- return &ValidationError{Name: "role", err: fmt.Errorf(`ent: validator failed for field "User.role": %w`, err)}
- }
- }
return nil
}
@@ -424,10 +398,6 @@ func (_c *UserCreate) createSpec() (*User, *sqlgraph.CreateSpec) {
_spec.SetField(user.FieldSuperuser, field.TypeBool, value)
_node.Superuser = value
}
- if value, ok := _c.mutation.Role(); ok {
- _spec.SetField(user.FieldRole, field.TypeEnum, value)
- _node.Role = value
- }
if value, ok := _c.mutation.ActivatedOn(); ok {
_spec.SetField(user.FieldActivatedOn, field.TypeTime, value)
_node.ActivatedOn = value
@@ -462,6 +432,10 @@ func (_c *UserCreate) createSpec() (*User, *sqlgraph.CreateSpec) {
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
+ createE := &UserGroupCreate{config: _c.config, mutation: newUserGroupMutation(_c.config, OpCreate)}
+ createE.defaults()
+ _, specE := createE.createSpec()
+ edge.Target.Fields = specE.Fields
_spec.Edges = append(_spec.Edges, edge)
}
if nodes := _c.mutation.AuthTokensIDs(); len(nodes) > 0 {
diff --git a/backend/internal/data/ent/user_query.go b/backend/internal/data/ent/user_query.go
index 12b3a3e7..a20a55a9 100644
--- a/backend/internal/data/ent/user_query.go
+++ b/backend/internal/data/ent/user_query.go
@@ -19,6 +19,7 @@ import (
"github.com/sysadminsmedia/homebox/backend/internal/data/ent/notifier"
"github.com/sysadminsmedia/homebox/backend/internal/data/ent/predicate"
"github.com/sysadminsmedia/homebox/backend/internal/data/ent/user"
+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent/usergroup"
)
// UserQuery is the builder for querying User entities.
@@ -32,6 +33,7 @@ type UserQuery struct {
withAuthTokens *AuthTokensQuery
withAPIKeys *APIKeyQuery
withNotifiers *NotifierQuery
+ withUserGroups *UserGroupQuery
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
@@ -156,6 +158,28 @@ func (_q *UserQuery) QueryNotifiers() *NotifierQuery {
return query
}
+// QueryUserGroups chains the current query on the "user_groups" edge.
+func (_q *UserQuery) QueryUserGroups() *UserGroupQuery {
+ query := (&UserGroupClient{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(user.Table, user.FieldID, selector),
+ sqlgraph.To(usergroup.Table, usergroup.UserColumn),
+ sqlgraph.Edge(sqlgraph.O2M, true, user.UserGroupsTable, user.UserGroupsColumn),
+ )
+ fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step)
+ return fromU, nil
+ }
+ return query
+}
+
// First returns the first User entity from the query.
// Returns a *NotFoundError when no User was found.
func (_q *UserQuery) First(ctx context.Context) (*User, error) {
@@ -352,6 +376,7 @@ func (_q *UserQuery) Clone() *UserQuery {
withAuthTokens: _q.withAuthTokens.Clone(),
withAPIKeys: _q.withAPIKeys.Clone(),
withNotifiers: _q.withNotifiers.Clone(),
+ withUserGroups: _q.withUserGroups.Clone(),
// clone intermediate query.
sql: _q.sql.Clone(),
path: _q.path,
@@ -402,6 +427,17 @@ func (_q *UserQuery) WithNotifiers(opts ...func(*NotifierQuery)) *UserQuery {
return _q
}
+// WithUserGroups tells the query-builder to eager-load the nodes that are connected to
+// the "user_groups" edge. The optional arguments are used to configure the query builder of the edge.
+func (_q *UserQuery) WithUserGroups(opts ...func(*UserGroupQuery)) *UserQuery {
+ query := (&UserGroupClient{config: _q.config}).Query()
+ for _, opt := range opts {
+ opt(query)
+ }
+ _q.withUserGroups = 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.
//
@@ -480,11 +516,12 @@ func (_q *UserQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*User, e
var (
nodes = []*User{}
_spec = _q.querySpec()
- loadedTypes = [4]bool{
+ loadedTypes = [5]bool{
_q.withGroups != nil,
_q.withAuthTokens != nil,
_q.withAPIKeys != nil,
_q.withNotifiers != nil,
+ _q.withUserGroups != nil,
}
)
_spec.ScanValues = func(columns []string) ([]any, error) {
@@ -533,6 +570,13 @@ func (_q *UserQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*User, e
return nil, err
}
}
+ if query := _q.withUserGroups; query != nil {
+ if err := _q.loadUserGroups(ctx, query, nodes,
+ func(n *User) { n.Edges.UserGroups = []*UserGroup{} },
+ func(n *User, e *UserGroup) { n.Edges.UserGroups = append(n.Edges.UserGroups, e) }); err != nil {
+ return nil, err
+ }
+ }
return nodes, nil
}
@@ -688,6 +732,36 @@ func (_q *UserQuery) loadNotifiers(ctx context.Context, query *NotifierQuery, no
}
return nil
}
+func (_q *UserQuery) loadUserGroups(ctx context.Context, query *UserGroupQuery, nodes []*User, init func(*User), assign func(*User, *UserGroup)) error {
+ fks := make([]driver.Value, 0, len(nodes))
+ nodeids := make(map[uuid.UUID]*User)
+ 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(usergroup.FieldUserID)
+ }
+ query.Where(predicate.UserGroup(func(s *sql.Selector) {
+ s.Where(sql.InValues(s.C(user.UserGroupsColumn), fks...))
+ }))
+ neighbors, err := query.All(ctx)
+ if err != nil {
+ return err
+ }
+ for _, n := range neighbors {
+ fk := n.UserID
+ node, ok := nodeids[fk]
+ if !ok {
+ return fmt.Errorf(`unexpected referenced foreign-key "user_id" returned %v for node %v`, fk, n)
+ }
+ assign(node, n)
+ }
+ return nil
+}
func (_q *UserQuery) sqlCount(ctx context.Context) (int, error) {
_spec := _q.querySpec()
diff --git a/backend/internal/data/ent/user_update.go b/backend/internal/data/ent/user_update.go
index 80dcb8bf..2d61e4aa 100644
--- a/backend/internal/data/ent/user_update.go
+++ b/backend/internal/data/ent/user_update.go
@@ -115,20 +115,6 @@ func (_u *UserUpdate) SetNillableSuperuser(v *bool) *UserUpdate {
return _u
}
-// SetRole sets the "role" field.
-func (_u *UserUpdate) SetRole(v user.Role) *UserUpdate {
- _u.mutation.SetRole(v)
- return _u
-}
-
-// SetNillableRole sets the "role" field if the given value is not nil.
-func (_u *UserUpdate) SetNillableRole(v *user.Role) *UserUpdate {
- if v != nil {
- _u.SetRole(*v)
- }
- return _u
-}
-
// SetActivatedOn sets the "activated_on" field.
func (_u *UserUpdate) SetActivatedOn(v time.Time) *UserUpdate {
_u.mutation.SetActivatedOn(v)
@@ -423,11 +409,6 @@ func (_u *UserUpdate) check() error {
return &ValidationError{Name: "password", err: fmt.Errorf(`ent: validator failed for field "User.password": %w`, err)}
}
}
- if v, ok := _u.mutation.Role(); ok {
- if err := user.RoleValidator(v); err != nil {
- return &ValidationError{Name: "role", err: fmt.Errorf(`ent: validator failed for field "User.role": %w`, err)}
- }
- }
return nil
}
@@ -464,9 +445,6 @@ func (_u *UserUpdate) sqlSave(ctx context.Context) (_node int, err error) {
if value, ok := _u.mutation.Superuser(); ok {
_spec.SetField(user.FieldSuperuser, field.TypeBool, value)
}
- if value, ok := _u.mutation.Role(); ok {
- _spec.SetField(user.FieldRole, field.TypeEnum, value)
- }
if value, ok := _u.mutation.ActivatedOn(); ok {
_spec.SetField(user.FieldActivatedOn, field.TypeTime, value)
}
@@ -508,6 +486,10 @@ func (_u *UserUpdate) sqlSave(ctx context.Context) (_node int, err error) {
IDSpec: sqlgraph.NewFieldSpec(group.FieldID, field.TypeUUID),
},
}
+ createE := &UserGroupCreate{config: _u.config, mutation: newUserGroupMutation(_u.config, OpCreate)}
+ createE.defaults()
+ _, specE := createE.createSpec()
+ edge.Target.Fields = specE.Fields
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.RemovedGroupsIDs(); len(nodes) > 0 && !_u.mutation.GroupsCleared() {
@@ -524,6 +506,10 @@ func (_u *UserUpdate) sqlSave(ctx context.Context) (_node int, err error) {
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
+ createE := &UserGroupCreate{config: _u.config, mutation: newUserGroupMutation(_u.config, OpCreate)}
+ createE.defaults()
+ _, specE := createE.createSpec()
+ edge.Target.Fields = specE.Fields
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.GroupsIDs(); len(nodes) > 0 {
@@ -540,6 +526,10 @@ func (_u *UserUpdate) sqlSave(ctx context.Context) (_node int, err error) {
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
+ createE := &UserGroupCreate{config: _u.config, mutation: newUserGroupMutation(_u.config, OpCreate)}
+ createE.defaults()
+ _, specE := createE.createSpec()
+ edge.Target.Fields = specE.Fields
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if _u.mutation.AuthTokensCleared() {
@@ -779,20 +769,6 @@ func (_u *UserUpdateOne) SetNillableSuperuser(v *bool) *UserUpdateOne {
return _u
}
-// SetRole sets the "role" field.
-func (_u *UserUpdateOne) SetRole(v user.Role) *UserUpdateOne {
- _u.mutation.SetRole(v)
- return _u
-}
-
-// SetNillableRole sets the "role" field if the given value is not nil.
-func (_u *UserUpdateOne) SetNillableRole(v *user.Role) *UserUpdateOne {
- if v != nil {
- _u.SetRole(*v)
- }
- return _u
-}
-
// SetActivatedOn sets the "activated_on" field.
func (_u *UserUpdateOne) SetActivatedOn(v time.Time) *UserUpdateOne {
_u.mutation.SetActivatedOn(v)
@@ -1100,11 +1076,6 @@ func (_u *UserUpdateOne) check() error {
return &ValidationError{Name: "password", err: fmt.Errorf(`ent: validator failed for field "User.password": %w`, err)}
}
}
- if v, ok := _u.mutation.Role(); ok {
- if err := user.RoleValidator(v); err != nil {
- return &ValidationError{Name: "role", err: fmt.Errorf(`ent: validator failed for field "User.role": %w`, err)}
- }
- }
return nil
}
@@ -1158,9 +1129,6 @@ func (_u *UserUpdateOne) sqlSave(ctx context.Context) (_node *User, err error) {
if value, ok := _u.mutation.Superuser(); ok {
_spec.SetField(user.FieldSuperuser, field.TypeBool, value)
}
- if value, ok := _u.mutation.Role(); ok {
- _spec.SetField(user.FieldRole, field.TypeEnum, value)
- }
if value, ok := _u.mutation.ActivatedOn(); ok {
_spec.SetField(user.FieldActivatedOn, field.TypeTime, value)
}
@@ -1202,6 +1170,10 @@ func (_u *UserUpdateOne) sqlSave(ctx context.Context) (_node *User, err error) {
IDSpec: sqlgraph.NewFieldSpec(group.FieldID, field.TypeUUID),
},
}
+ createE := &UserGroupCreate{config: _u.config, mutation: newUserGroupMutation(_u.config, OpCreate)}
+ createE.defaults()
+ _, specE := createE.createSpec()
+ edge.Target.Fields = specE.Fields
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.RemovedGroupsIDs(); len(nodes) > 0 && !_u.mutation.GroupsCleared() {
@@ -1218,6 +1190,10 @@ func (_u *UserUpdateOne) sqlSave(ctx context.Context) (_node *User, err error) {
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
+ createE := &UserGroupCreate{config: _u.config, mutation: newUserGroupMutation(_u.config, OpCreate)}
+ createE.defaults()
+ _, specE := createE.createSpec()
+ edge.Target.Fields = specE.Fields
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.GroupsIDs(); len(nodes) > 0 {
@@ -1234,6 +1210,10 @@ func (_u *UserUpdateOne) sqlSave(ctx context.Context) (_node *User, err error) {
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
+ createE := &UserGroupCreate{config: _u.config, mutation: newUserGroupMutation(_u.config, OpCreate)}
+ createE.defaults()
+ _, specE := createE.createSpec()
+ edge.Target.Fields = specE.Fields
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if _u.mutation.AuthTokensCleared() {
diff --git a/backend/internal/data/ent/usergroup.go b/backend/internal/data/ent/usergroup.go
new file mode 100644
index 00000000..427fe4cc
--- /dev/null
+++ b/backend/internal/data/ent/usergroup.go
@@ -0,0 +1,165 @@
+// Code generated by ent, DO NOT EDIT.
+
+package ent
+
+import (
+ "fmt"
+ "strings"
+
+ "entgo.io/ent"
+ "entgo.io/ent/dialect/sql"
+ "github.com/google/uuid"
+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent/group"
+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent/user"
+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent/usergroup"
+)
+
+// UserGroup is the model entity for the UserGroup schema.
+type UserGroup struct {
+ config `json:"-"`
+ // UserID holds the value of the "user_id" field.
+ UserID uuid.UUID `json:"user_id,omitempty"`
+ // GroupID holds the value of the "group_id" field.
+ GroupID uuid.UUID `json:"group_id,omitempty"`
+ // Role holds the value of the "role" field.
+ Role usergroup.Role `json:"role,omitempty"`
+ // Edges holds the relations/edges for other nodes in the graph.
+ // The values are being populated by the UserGroupQuery when eager-loading is set.
+ Edges UserGroupEdges `json:"edges"`
+ selectValues sql.SelectValues
+}
+
+// UserGroupEdges holds the relations/edges for other nodes in the graph.
+type UserGroupEdges struct {
+ // User holds the value of the user edge.
+ User *User `json:"user,omitempty"`
+ // Group holds the value of the group edge.
+ Group *Group `json:"group,omitempty"`
+ // loadedTypes holds the information for reporting if a
+ // type was loaded (or requested) in eager-loading or not.
+ loadedTypes [2]bool
+}
+
+// UserOrErr returns the User value or an error if the edge
+// was not loaded in eager-loading, or loaded but was not found.
+func (e UserGroupEdges) UserOrErr() (*User, error) {
+ if e.User != nil {
+ return e.User, nil
+ } else if e.loadedTypes[0] {
+ return nil, &NotFoundError{label: user.Label}
+ }
+ return nil, &NotLoadedError{edge: "user"}
+}
+
+// GroupOrErr returns the Group value or an error if the edge
+// was not loaded in eager-loading, or loaded but was not found.
+func (e UserGroupEdges) GroupOrErr() (*Group, error) {
+ if e.Group != nil {
+ return e.Group, nil
+ } else if e.loadedTypes[1] {
+ return nil, &NotFoundError{label: group.Label}
+ }
+ return nil, &NotLoadedError{edge: "group"}
+}
+
+// scanValues returns the types for scanning values from sql.Rows.
+func (*UserGroup) scanValues(columns []string) ([]any, error) {
+ values := make([]any, len(columns))
+ for i := range columns {
+ switch columns[i] {
+ case usergroup.FieldRole:
+ values[i] = new(sql.NullString)
+ case usergroup.FieldUserID, usergroup.FieldGroupID:
+ values[i] = new(uuid.UUID)
+ default:
+ values[i] = new(sql.UnknownType)
+ }
+ }
+ return values, nil
+}
+
+// assignValues assigns the values that were returned from sql.Rows (after scanning)
+// to the UserGroup fields.
+func (_m *UserGroup) assignValues(columns []string, values []any) error {
+ if m, n := len(values), len(columns); m < n {
+ return fmt.Errorf("mismatch number of scan values: %d != %d", m, n)
+ }
+ for i := range columns {
+ switch columns[i] {
+ case usergroup.FieldUserID:
+ if value, ok := values[i].(*uuid.UUID); !ok {
+ return fmt.Errorf("unexpected type %T for field user_id", values[i])
+ } else if value != nil {
+ _m.UserID = *value
+ }
+ case usergroup.FieldGroupID:
+ if value, ok := values[i].(*uuid.UUID); !ok {
+ return fmt.Errorf("unexpected type %T for field group_id", values[i])
+ } else if value != nil {
+ _m.GroupID = *value
+ }
+ case usergroup.FieldRole:
+ if value, ok := values[i].(*sql.NullString); !ok {
+ return fmt.Errorf("unexpected type %T for field role", values[i])
+ } else if value.Valid {
+ _m.Role = usergroup.Role(value.String)
+ }
+ default:
+ _m.selectValues.Set(columns[i], values[i])
+ }
+ }
+ return nil
+}
+
+// Value returns the ent.Value that was dynamically selected and assigned to the UserGroup.
+// This includes values selected through modifiers, order, etc.
+func (_m *UserGroup) Value(name string) (ent.Value, error) {
+ return _m.selectValues.Get(name)
+}
+
+// QueryUser queries the "user" edge of the UserGroup entity.
+func (_m *UserGroup) QueryUser() *UserQuery {
+ return NewUserGroupClient(_m.config).QueryUser(_m)
+}
+
+// QueryGroup queries the "group" edge of the UserGroup entity.
+func (_m *UserGroup) QueryGroup() *GroupQuery {
+ return NewUserGroupClient(_m.config).QueryGroup(_m)
+}
+
+// Update returns a builder for updating this UserGroup.
+// Note that you need to call UserGroup.Unwrap() before calling this method if this UserGroup
+// was returned from a transaction, and the transaction was committed or rolled back.
+func (_m *UserGroup) Update() *UserGroupUpdateOne {
+ return NewUserGroupClient(_m.config).UpdateOne(_m)
+}
+
+// Unwrap unwraps the UserGroup entity that was returned from a transaction after it was closed,
+// so that all future queries will be executed through the driver which created the transaction.
+func (_m *UserGroup) Unwrap() *UserGroup {
+ _tx, ok := _m.config.driver.(*txDriver)
+ if !ok {
+ panic("ent: UserGroup is not a transactional entity")
+ }
+ _m.config.driver = _tx.drv
+ return _m
+}
+
+// String implements the fmt.Stringer.
+func (_m *UserGroup) String() string {
+ var builder strings.Builder
+ builder.WriteString("UserGroup(")
+ builder.WriteString("user_id=")
+ builder.WriteString(fmt.Sprintf("%v", _m.UserID))
+ builder.WriteString(", ")
+ builder.WriteString("group_id=")
+ builder.WriteString(fmt.Sprintf("%v", _m.GroupID))
+ builder.WriteString(", ")
+ builder.WriteString("role=")
+ builder.WriteString(fmt.Sprintf("%v", _m.Role))
+ builder.WriteByte(')')
+ return builder.String()
+}
+
+// UserGroups is a parsable slice of UserGroup.
+type UserGroups []*UserGroup
diff --git a/backend/internal/data/ent/usergroup/usergroup.go b/backend/internal/data/ent/usergroup/usergroup.go
new file mode 100644
index 00000000..999215e4
--- /dev/null
+++ b/backend/internal/data/ent/usergroup/usergroup.go
@@ -0,0 +1,134 @@
+// Code generated by ent, DO NOT EDIT.
+
+package usergroup
+
+import (
+ "fmt"
+
+ "entgo.io/ent/dialect/sql"
+ "entgo.io/ent/dialect/sql/sqlgraph"
+)
+
+const (
+ // Label holds the string label denoting the usergroup type in the database.
+ Label = "user_group"
+ // FieldUserID holds the string denoting the user_id field in the database.
+ FieldUserID = "user_id"
+ // FieldGroupID holds the string denoting the group_id field in the database.
+ FieldGroupID = "group_id"
+ // FieldRole holds the string denoting the role field in the database.
+ FieldRole = "role"
+ // EdgeUser holds the string denoting the user edge name in mutations.
+ EdgeUser = "user"
+ // EdgeGroup holds the string denoting the group edge name in mutations.
+ EdgeGroup = "group"
+ // UserFieldID holds the string denoting the ID field of the User.
+ UserFieldID = "id"
+ // GroupFieldID holds the string denoting the ID field of the Group.
+ GroupFieldID = "id"
+ // Table holds the table name of the usergroup in the database.
+ Table = "user_groups"
+ // UserTable is the table that holds the user relation/edge.
+ UserTable = "user_groups"
+ // UserInverseTable is the table name for the User entity.
+ // It exists in this package in order to avoid circular dependency with the "user" package.
+ UserInverseTable = "users"
+ // UserColumn is the table column denoting the user relation/edge.
+ UserColumn = "user_id"
+ // GroupTable is the table that holds the group relation/edge.
+ GroupTable = "user_groups"
+ // GroupInverseTable is the table name for the Group entity.
+ // It exists in this package in order to avoid circular dependency with the "group" package.
+ GroupInverseTable = "groups"
+ // GroupColumn is the table column denoting the group relation/edge.
+ GroupColumn = "group_id"
+)
+
+// Columns holds all SQL columns for usergroup fields.
+var Columns = []string{
+ FieldUserID,
+ FieldGroupID,
+ FieldRole,
+}
+
+// ValidColumn reports if the column name is valid (part of the table columns).
+func ValidColumn(column string) bool {
+ for i := range Columns {
+ if column == Columns[i] {
+ return true
+ }
+ }
+ return false
+}
+
+// Role defines the type for the "role" enum field.
+type Role string
+
+// RoleUser is the default value of the Role enum.
+const DefaultRole = RoleUser
+
+// Role values.
+const (
+ RoleUser Role = "user"
+ RoleOwner Role = "owner"
+)
+
+func (r Role) String() string {
+ return string(r)
+}
+
+// RoleValidator is a validator for the "role" field enum values. It is called by the builders before save.
+func RoleValidator(r Role) error {
+ switch r {
+ case RoleUser, RoleOwner:
+ return nil
+ default:
+ return fmt.Errorf("usergroup: invalid enum value for role field: %q", r)
+ }
+}
+
+// OrderOption defines the ordering options for the UserGroup queries.
+type OrderOption func(*sql.Selector)
+
+// ByUserID orders the results by the user_id field.
+func ByUserID(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldUserID, opts...).ToFunc()
+}
+
+// ByGroupID orders the results by the group_id field.
+func ByGroupID(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldGroupID, opts...).ToFunc()
+}
+
+// ByRole orders the results by the role field.
+func ByRole(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldRole, opts...).ToFunc()
+}
+
+// ByUserField orders the results by user field.
+func ByUserField(field string, opts ...sql.OrderTermOption) OrderOption {
+ return func(s *sql.Selector) {
+ sqlgraph.OrderByNeighborTerms(s, newUserStep(), sql.OrderByField(field, opts...))
+ }
+}
+
+// ByGroupField orders the results by group field.
+func ByGroupField(field string, opts ...sql.OrderTermOption) OrderOption {
+ return func(s *sql.Selector) {
+ sqlgraph.OrderByNeighborTerms(s, newGroupStep(), sql.OrderByField(field, opts...))
+ }
+}
+func newUserStep() *sqlgraph.Step {
+ return sqlgraph.NewStep(
+ sqlgraph.From(Table, UserColumn),
+ sqlgraph.To(UserInverseTable, UserFieldID),
+ sqlgraph.Edge(sqlgraph.M2O, false, UserTable, UserColumn),
+ )
+}
+func newGroupStep() *sqlgraph.Step {
+ return sqlgraph.NewStep(
+ sqlgraph.From(Table, GroupColumn),
+ sqlgraph.To(GroupInverseTable, GroupFieldID),
+ sqlgraph.Edge(sqlgraph.M2O, false, GroupTable, GroupColumn),
+ )
+}
diff --git a/backend/internal/data/ent/usergroup/where.go b/backend/internal/data/ent/usergroup/where.go
new file mode 100644
index 00000000..a16f5391
--- /dev/null
+++ b/backend/internal/data/ent/usergroup/where.go
@@ -0,0 +1,141 @@
+// Code generated by ent, DO NOT EDIT.
+
+package usergroup
+
+import (
+ "entgo.io/ent/dialect/sql"
+ "entgo.io/ent/dialect/sql/sqlgraph"
+ "github.com/google/uuid"
+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent/predicate"
+)
+
+// UserID applies equality check predicate on the "user_id" field. It's identical to UserIDEQ.
+func UserID(v uuid.UUID) predicate.UserGroup {
+ return predicate.UserGroup(sql.FieldEQ(FieldUserID, v))
+}
+
+// GroupID applies equality check predicate on the "group_id" field. It's identical to GroupIDEQ.
+func GroupID(v uuid.UUID) predicate.UserGroup {
+ return predicate.UserGroup(sql.FieldEQ(FieldGroupID, v))
+}
+
+// UserIDEQ applies the EQ predicate on the "user_id" field.
+func UserIDEQ(v uuid.UUID) predicate.UserGroup {
+ return predicate.UserGroup(sql.FieldEQ(FieldUserID, v))
+}
+
+// UserIDNEQ applies the NEQ predicate on the "user_id" field.
+func UserIDNEQ(v uuid.UUID) predicate.UserGroup {
+ return predicate.UserGroup(sql.FieldNEQ(FieldUserID, v))
+}
+
+// UserIDIn applies the In predicate on the "user_id" field.
+func UserIDIn(vs ...uuid.UUID) predicate.UserGroup {
+ return predicate.UserGroup(sql.FieldIn(FieldUserID, vs...))
+}
+
+// UserIDNotIn applies the NotIn predicate on the "user_id" field.
+func UserIDNotIn(vs ...uuid.UUID) predicate.UserGroup {
+ return predicate.UserGroup(sql.FieldNotIn(FieldUserID, vs...))
+}
+
+// GroupIDEQ applies the EQ predicate on the "group_id" field.
+func GroupIDEQ(v uuid.UUID) predicate.UserGroup {
+ return predicate.UserGroup(sql.FieldEQ(FieldGroupID, v))
+}
+
+// GroupIDNEQ applies the NEQ predicate on the "group_id" field.
+func GroupIDNEQ(v uuid.UUID) predicate.UserGroup {
+ return predicate.UserGroup(sql.FieldNEQ(FieldGroupID, v))
+}
+
+// GroupIDIn applies the In predicate on the "group_id" field.
+func GroupIDIn(vs ...uuid.UUID) predicate.UserGroup {
+ return predicate.UserGroup(sql.FieldIn(FieldGroupID, vs...))
+}
+
+// GroupIDNotIn applies the NotIn predicate on the "group_id" field.
+func GroupIDNotIn(vs ...uuid.UUID) predicate.UserGroup {
+ return predicate.UserGroup(sql.FieldNotIn(FieldGroupID, vs...))
+}
+
+// RoleEQ applies the EQ predicate on the "role" field.
+func RoleEQ(v Role) predicate.UserGroup {
+ return predicate.UserGroup(sql.FieldEQ(FieldRole, v))
+}
+
+// RoleNEQ applies the NEQ predicate on the "role" field.
+func RoleNEQ(v Role) predicate.UserGroup {
+ return predicate.UserGroup(sql.FieldNEQ(FieldRole, v))
+}
+
+// RoleIn applies the In predicate on the "role" field.
+func RoleIn(vs ...Role) predicate.UserGroup {
+ return predicate.UserGroup(sql.FieldIn(FieldRole, vs...))
+}
+
+// RoleNotIn applies the NotIn predicate on the "role" field.
+func RoleNotIn(vs ...Role) predicate.UserGroup {
+ return predicate.UserGroup(sql.FieldNotIn(FieldRole, vs...))
+}
+
+// HasUser applies the HasEdge predicate on the "user" edge.
+func HasUser() predicate.UserGroup {
+ return predicate.UserGroup(func(s *sql.Selector) {
+ step := sqlgraph.NewStep(
+ sqlgraph.From(Table, UserColumn),
+ sqlgraph.Edge(sqlgraph.M2O, false, UserTable, UserColumn),
+ )
+ sqlgraph.HasNeighbors(s, step)
+ })
+}
+
+// HasUserWith applies the HasEdge predicate on the "user" edge with a given conditions (other predicates).
+func HasUserWith(preds ...predicate.User) predicate.UserGroup {
+ return predicate.UserGroup(func(s *sql.Selector) {
+ step := newUserStep()
+ sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
+ for _, p := range preds {
+ p(s)
+ }
+ })
+ })
+}
+
+// HasGroup applies the HasEdge predicate on the "group" edge.
+func HasGroup() predicate.UserGroup {
+ return predicate.UserGroup(func(s *sql.Selector) {
+ step := sqlgraph.NewStep(
+ sqlgraph.From(Table, GroupColumn),
+ sqlgraph.Edge(sqlgraph.M2O, false, GroupTable, GroupColumn),
+ )
+ sqlgraph.HasNeighbors(s, step)
+ })
+}
+
+// HasGroupWith applies the HasEdge predicate on the "group" edge with a given conditions (other predicates).
+func HasGroupWith(preds ...predicate.Group) predicate.UserGroup {
+ return predicate.UserGroup(func(s *sql.Selector) {
+ step := newGroupStep()
+ 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.UserGroup) predicate.UserGroup {
+ return predicate.UserGroup(sql.AndPredicates(predicates...))
+}
+
+// Or groups predicates with the OR operator between them.
+func Or(predicates ...predicate.UserGroup) predicate.UserGroup {
+ return predicate.UserGroup(sql.OrPredicates(predicates...))
+}
+
+// Not applies the not operator on the given predicate.
+func Not(p predicate.UserGroup) predicate.UserGroup {
+ return predicate.UserGroup(sql.NotPredicates(p))
+}
diff --git a/backend/internal/data/ent/usergroup_create.go b/backend/internal/data/ent/usergroup_create.go
new file mode 100644
index 00000000..f6654e7c
--- /dev/null
+++ b/backend/internal/data/ent/usergroup_create.go
@@ -0,0 +1,268 @@
+// Code generated by ent, DO NOT EDIT.
+
+package ent
+
+import (
+ "context"
+ "errors"
+ "fmt"
+
+ "entgo.io/ent/dialect/sql/sqlgraph"
+ "entgo.io/ent/schema/field"
+ "github.com/google/uuid"
+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent/group"
+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent/user"
+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent/usergroup"
+)
+
+// UserGroupCreate is the builder for creating a UserGroup entity.
+type UserGroupCreate struct {
+ config
+ mutation *UserGroupMutation
+ hooks []Hook
+}
+
+// SetUserID sets the "user_id" field.
+func (_c *UserGroupCreate) SetUserID(v uuid.UUID) *UserGroupCreate {
+ _c.mutation.SetUserID(v)
+ return _c
+}
+
+// SetGroupID sets the "group_id" field.
+func (_c *UserGroupCreate) SetGroupID(v uuid.UUID) *UserGroupCreate {
+ _c.mutation.SetGroupID(v)
+ return _c
+}
+
+// SetRole sets the "role" field.
+func (_c *UserGroupCreate) SetRole(v usergroup.Role) *UserGroupCreate {
+ _c.mutation.SetRole(v)
+ return _c
+}
+
+// SetNillableRole sets the "role" field if the given value is not nil.
+func (_c *UserGroupCreate) SetNillableRole(v *usergroup.Role) *UserGroupCreate {
+ if v != nil {
+ _c.SetRole(*v)
+ }
+ return _c
+}
+
+// SetUser sets the "user" edge to the User entity.
+func (_c *UserGroupCreate) SetUser(v *User) *UserGroupCreate {
+ return _c.SetUserID(v.ID)
+}
+
+// SetGroup sets the "group" edge to the Group entity.
+func (_c *UserGroupCreate) SetGroup(v *Group) *UserGroupCreate {
+ return _c.SetGroupID(v.ID)
+}
+
+// Mutation returns the UserGroupMutation object of the builder.
+func (_c *UserGroupCreate) Mutation() *UserGroupMutation {
+ return _c.mutation
+}
+
+// Save creates the UserGroup in the database.
+func (_c *UserGroupCreate) Save(ctx context.Context) (*UserGroup, error) {
+ _c.defaults()
+ return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks)
+}
+
+// SaveX calls Save and panics if Save returns an error.
+func (_c *UserGroupCreate) SaveX(ctx context.Context) *UserGroup {
+ v, err := _c.Save(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return v
+}
+
+// Exec executes the query.
+func (_c *UserGroupCreate) Exec(ctx context.Context) error {
+ _, err := _c.Save(ctx)
+ return err
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (_c *UserGroupCreate) ExecX(ctx context.Context) {
+ if err := _c.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
+
+// defaults sets the default values of the builder before save.
+func (_c *UserGroupCreate) defaults() {
+ if _, ok := _c.mutation.Role(); !ok {
+ v := usergroup.DefaultRole
+ _c.mutation.SetRole(v)
+ }
+}
+
+// check runs all checks and user-defined validators on the builder.
+func (_c *UserGroupCreate) check() error {
+ if _, ok := _c.mutation.UserID(); !ok {
+ return &ValidationError{Name: "user_id", err: errors.New(`ent: missing required field "UserGroup.user_id"`)}
+ }
+ if _, ok := _c.mutation.GroupID(); !ok {
+ return &ValidationError{Name: "group_id", err: errors.New(`ent: missing required field "UserGroup.group_id"`)}
+ }
+ if _, ok := _c.mutation.Role(); !ok {
+ return &ValidationError{Name: "role", err: errors.New(`ent: missing required field "UserGroup.role"`)}
+ }
+ if v, ok := _c.mutation.Role(); ok {
+ if err := usergroup.RoleValidator(v); err != nil {
+ return &ValidationError{Name: "role", err: fmt.Errorf(`ent: validator failed for field "UserGroup.role": %w`, err)}
+ }
+ }
+ if len(_c.mutation.UserIDs()) == 0 {
+ return &ValidationError{Name: "user", err: errors.New(`ent: missing required edge "UserGroup.user"`)}
+ }
+ if len(_c.mutation.GroupIDs()) == 0 {
+ return &ValidationError{Name: "group", err: errors.New(`ent: missing required edge "UserGroup.group"`)}
+ }
+ return nil
+}
+
+func (_c *UserGroupCreate) sqlSave(ctx context.Context) (*UserGroup, error) {
+ if err := _c.check(); err != nil {
+ return nil, err
+ }
+ _node, _spec := _c.createSpec()
+ if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil {
+ if sqlgraph.IsConstraintError(err) {
+ err = &ConstraintError{msg: err.Error(), wrap: err}
+ }
+ return nil, err
+ }
+ return _node, nil
+}
+
+func (_c *UserGroupCreate) createSpec() (*UserGroup, *sqlgraph.CreateSpec) {
+ var (
+ _node = &UserGroup{config: _c.config}
+ _spec = sqlgraph.NewCreateSpec(usergroup.Table, nil)
+ )
+ if value, ok := _c.mutation.Role(); ok {
+ _spec.SetField(usergroup.FieldRole, field.TypeEnum, value)
+ _node.Role = value
+ }
+ if nodes := _c.mutation.UserIDs(); len(nodes) > 0 {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.M2O,
+ Inverse: false,
+ Table: usergroup.UserTable,
+ Columns: []string{usergroup.UserColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID),
+ },
+ }
+ for _, k := range nodes {
+ edge.Target.Nodes = append(edge.Target.Nodes, k)
+ }
+ _node.UserID = nodes[0]
+ _spec.Edges = append(_spec.Edges, edge)
+ }
+ if nodes := _c.mutation.GroupIDs(); len(nodes) > 0 {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.M2O,
+ Inverse: false,
+ Table: usergroup.GroupTable,
+ Columns: []string{usergroup.GroupColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(group.FieldID, field.TypeUUID),
+ },
+ }
+ for _, k := range nodes {
+ edge.Target.Nodes = append(edge.Target.Nodes, k)
+ }
+ _node.GroupID = nodes[0]
+ _spec.Edges = append(_spec.Edges, edge)
+ }
+ return _node, _spec
+}
+
+// UserGroupCreateBulk is the builder for creating many UserGroup entities in bulk.
+type UserGroupCreateBulk struct {
+ config
+ err error
+ builders []*UserGroupCreate
+}
+
+// Save creates the UserGroup entities in the database.
+func (_c *UserGroupCreateBulk) Save(ctx context.Context) ([]*UserGroup, error) {
+ if _c.err != nil {
+ return nil, _c.err
+ }
+ specs := make([]*sqlgraph.CreateSpec, len(_c.builders))
+ nodes := make([]*UserGroup, len(_c.builders))
+ mutators := make([]Mutator, len(_c.builders))
+ for i := range _c.builders {
+ func(i int, root context.Context) {
+ builder := _c.builders[i]
+ builder.defaults()
+ var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
+ mutation, ok := m.(*UserGroupMutation)
+ if !ok {
+ return nil, fmt.Errorf("unexpected mutation type %T", m)
+ }
+ if err := builder.check(); err != nil {
+ return nil, err
+ }
+ builder.mutation = mutation
+ var err error
+ nodes[i], specs[i] = builder.createSpec()
+ if i < len(mutators)-1 {
+ _, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation)
+ } else {
+ spec := &sqlgraph.BatchCreateSpec{Nodes: specs}
+ // Invoke the actual operation on the latest mutation in the chain.
+ if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil {
+ if sqlgraph.IsConstraintError(err) {
+ err = &ConstraintError{msg: err.Error(), wrap: err}
+ }
+ }
+ }
+ if err != nil {
+ return nil, err
+ }
+ mutation.done = true
+ return nodes[i], nil
+ })
+ for i := len(builder.hooks) - 1; i >= 0; i-- {
+ mut = builder.hooks[i](mut)
+ }
+ mutators[i] = mut
+ }(i, ctx)
+ }
+ if len(mutators) > 0 {
+ if _, err := mutators[0].Mutate(ctx, _c.builders[0].mutation); err != nil {
+ return nil, err
+ }
+ }
+ return nodes, nil
+}
+
+// SaveX is like Save, but panics if an error occurs.
+func (_c *UserGroupCreateBulk) SaveX(ctx context.Context) []*UserGroup {
+ v, err := _c.Save(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return v
+}
+
+// Exec executes the query.
+func (_c *UserGroupCreateBulk) Exec(ctx context.Context) error {
+ _, err := _c.Save(ctx)
+ return err
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (_c *UserGroupCreateBulk) ExecX(ctx context.Context) {
+ if err := _c.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
diff --git a/backend/internal/data/ent/usergroup_delete.go b/backend/internal/data/ent/usergroup_delete.go
new file mode 100644
index 00000000..dda25abc
--- /dev/null
+++ b/backend/internal/data/ent/usergroup_delete.go
@@ -0,0 +1,87 @@
+// Code generated by ent, DO NOT EDIT.
+
+package ent
+
+import (
+ "context"
+
+ "entgo.io/ent/dialect/sql"
+ "entgo.io/ent/dialect/sql/sqlgraph"
+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent/predicate"
+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent/usergroup"
+)
+
+// UserGroupDelete is the builder for deleting a UserGroup entity.
+type UserGroupDelete struct {
+ config
+ hooks []Hook
+ mutation *UserGroupMutation
+}
+
+// Where appends a list predicates to the UserGroupDelete builder.
+func (_d *UserGroupDelete) Where(ps ...predicate.UserGroup) *UserGroupDelete {
+ _d.mutation.Where(ps...)
+ return _d
+}
+
+// Exec executes the deletion query and returns how many vertices were deleted.
+func (_d *UserGroupDelete) Exec(ctx context.Context) (int, error) {
+ return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks)
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (_d *UserGroupDelete) ExecX(ctx context.Context) int {
+ n, err := _d.Exec(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return n
+}
+
+func (_d *UserGroupDelete) sqlExec(ctx context.Context) (int, error) {
+ _spec := sqlgraph.NewDeleteSpec(usergroup.Table, nil)
+ if ps := _d.mutation.predicates; len(ps) > 0 {
+ _spec.Predicate = func(selector *sql.Selector) {
+ for i := range ps {
+ ps[i](selector)
+ }
+ }
+ }
+ affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec)
+ if err != nil && sqlgraph.IsConstraintError(err) {
+ err = &ConstraintError{msg: err.Error(), wrap: err}
+ }
+ _d.mutation.done = true
+ return affected, err
+}
+
+// UserGroupDeleteOne is the builder for deleting a single UserGroup entity.
+type UserGroupDeleteOne struct {
+ _d *UserGroupDelete
+}
+
+// Where appends a list predicates to the UserGroupDelete builder.
+func (_d *UserGroupDeleteOne) Where(ps ...predicate.UserGroup) *UserGroupDeleteOne {
+ _d._d.mutation.Where(ps...)
+ return _d
+}
+
+// Exec executes the deletion query.
+func (_d *UserGroupDeleteOne) Exec(ctx context.Context) error {
+ n, err := _d._d.Exec(ctx)
+ switch {
+ case err != nil:
+ return err
+ case n == 0:
+ return &NotFoundError{usergroup.Label}
+ default:
+ return nil
+ }
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (_d *UserGroupDeleteOne) ExecX(ctx context.Context) {
+ if err := _d.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
diff --git a/backend/internal/data/ent/usergroup_query.go b/backend/internal/data/ent/usergroup_query.go
new file mode 100644
index 00000000..b73ad4e9
--- /dev/null
+++ b/backend/internal/data/ent/usergroup_query.go
@@ -0,0 +1,604 @@
+// Code generated by ent, DO NOT EDIT.
+
+package ent
+
+import (
+ "context"
+ "fmt"
+ "math"
+
+ "entgo.io/ent"
+ "entgo.io/ent/dialect/sql"
+ "entgo.io/ent/dialect/sql/sqlgraph"
+ "github.com/google/uuid"
+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent/group"
+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent/predicate"
+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent/user"
+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent/usergroup"
+)
+
+// UserGroupQuery is the builder for querying UserGroup entities.
+type UserGroupQuery struct {
+ config
+ ctx *QueryContext
+ order []usergroup.OrderOption
+ inters []Interceptor
+ predicates []predicate.UserGroup
+ withUser *UserQuery
+ withGroup *GroupQuery
+ // intermediate query (i.e. traversal path).
+ sql *sql.Selector
+ path func(context.Context) (*sql.Selector, error)
+}
+
+// Where adds a new predicate for the UserGroupQuery builder.
+func (_q *UserGroupQuery) Where(ps ...predicate.UserGroup) *UserGroupQuery {
+ _q.predicates = append(_q.predicates, ps...)
+ return _q
+}
+
+// Limit the number of records to be returned by this query.
+func (_q *UserGroupQuery) Limit(limit int) *UserGroupQuery {
+ _q.ctx.Limit = &limit
+ return _q
+}
+
+// Offset to start from.
+func (_q *UserGroupQuery) Offset(offset int) *UserGroupQuery {
+ _q.ctx.Offset = &offset
+ return _q
+}
+
+// Unique configures the query builder to filter duplicate records on query.
+// By default, unique is set to true, and can be disabled using this method.
+func (_q *UserGroupQuery) Unique(unique bool) *UserGroupQuery {
+ _q.ctx.Unique = &unique
+ return _q
+}
+
+// Order specifies how the records should be ordered.
+func (_q *UserGroupQuery) Order(o ...usergroup.OrderOption) *UserGroupQuery {
+ _q.order = append(_q.order, o...)
+ return _q
+}
+
+// QueryUser chains the current query on the "user" edge.
+func (_q *UserGroupQuery) QueryUser() *UserQuery {
+ query := (&UserClient{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(usergroup.Table, usergroup.UserColumn, selector),
+ sqlgraph.To(user.Table, user.FieldID),
+ sqlgraph.Edge(sqlgraph.M2O, false, usergroup.UserTable, usergroup.UserColumn),
+ )
+ fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step)
+ return fromU, nil
+ }
+ return query
+}
+
+// QueryGroup chains the current query on the "group" edge.
+func (_q *UserGroupQuery) QueryGroup() *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(usergroup.Table, usergroup.GroupColumn, selector),
+ sqlgraph.To(group.Table, group.FieldID),
+ sqlgraph.Edge(sqlgraph.M2O, false, usergroup.GroupTable, usergroup.GroupColumn),
+ )
+ fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step)
+ return fromU, nil
+ }
+ return query
+}
+
+// First returns the first UserGroup entity from the query.
+// Returns a *NotFoundError when no UserGroup was found.
+func (_q *UserGroupQuery) First(ctx context.Context) (*UserGroup, error) {
+ nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst))
+ if err != nil {
+ return nil, err
+ }
+ if len(nodes) == 0 {
+ return nil, &NotFoundError{usergroup.Label}
+ }
+ return nodes[0], nil
+}
+
+// FirstX is like First, but panics if an error occurs.
+func (_q *UserGroupQuery) FirstX(ctx context.Context) *UserGroup {
+ node, err := _q.First(ctx)
+ if err != nil && !IsNotFound(err) {
+ panic(err)
+ }
+ return node
+}
+
+// Only returns a single UserGroup entity found by the query, ensuring it only returns one.
+// Returns a *NotSingularError when more than one UserGroup entity is found.
+// Returns a *NotFoundError when no UserGroup entities are found.
+func (_q *UserGroupQuery) Only(ctx context.Context) (*UserGroup, error) {
+ nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly))
+ if err != nil {
+ return nil, err
+ }
+ switch len(nodes) {
+ case 1:
+ return nodes[0], nil
+ case 0:
+ return nil, &NotFoundError{usergroup.Label}
+ default:
+ return nil, &NotSingularError{usergroup.Label}
+ }
+}
+
+// OnlyX is like Only, but panics if an error occurs.
+func (_q *UserGroupQuery) OnlyX(ctx context.Context) *UserGroup {
+ node, err := _q.Only(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return node
+}
+
+// All executes the query and returns a list of UserGroups.
+func (_q *UserGroupQuery) All(ctx context.Context) ([]*UserGroup, error) {
+ ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll)
+ if err := _q.prepareQuery(ctx); err != nil {
+ return nil, err
+ }
+ qr := querierAll[[]*UserGroup, *UserGroupQuery]()
+ return withInterceptors[[]*UserGroup](ctx, _q, qr, _q.inters)
+}
+
+// AllX is like All, but panics if an error occurs.
+func (_q *UserGroupQuery) AllX(ctx context.Context) []*UserGroup {
+ nodes, err := _q.All(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return nodes
+}
+
+// Count returns the count of the given query.
+func (_q *UserGroupQuery) Count(ctx context.Context) (int, error) {
+ ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount)
+ if err := _q.prepareQuery(ctx); err != nil {
+ return 0, err
+ }
+ return withInterceptors[int](ctx, _q, querierCount[*UserGroupQuery](), _q.inters)
+}
+
+// CountX is like Count, but panics if an error occurs.
+func (_q *UserGroupQuery) CountX(ctx context.Context) int {
+ count, err := _q.Count(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return count
+}
+
+// Exist returns true if the query has elements in the graph.
+func (_q *UserGroupQuery) Exist(ctx context.Context) (bool, error) {
+ ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist)
+ switch _, err := _q.First(ctx); {
+ case IsNotFound(err):
+ return false, nil
+ case err != nil:
+ return false, fmt.Errorf("ent: check existence: %w", err)
+ default:
+ return true, nil
+ }
+}
+
+// ExistX is like Exist, but panics if an error occurs.
+func (_q *UserGroupQuery) ExistX(ctx context.Context) bool {
+ exist, err := _q.Exist(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return exist
+}
+
+// Clone returns a duplicate of the UserGroupQuery builder, including all associated steps. It can be
+// used to prepare common query builders and use them differently after the clone is made.
+func (_q *UserGroupQuery) Clone() *UserGroupQuery {
+ if _q == nil {
+ return nil
+ }
+ return &UserGroupQuery{
+ config: _q.config,
+ ctx: _q.ctx.Clone(),
+ order: append([]usergroup.OrderOption{}, _q.order...),
+ inters: append([]Interceptor{}, _q.inters...),
+ predicates: append([]predicate.UserGroup{}, _q.predicates...),
+ withUser: _q.withUser.Clone(),
+ withGroup: _q.withGroup.Clone(),
+ // clone intermediate query.
+ sql: _q.sql.Clone(),
+ path: _q.path,
+ }
+}
+
+// WithUser tells the query-builder to eager-load the nodes that are connected to
+// the "user" edge. The optional arguments are used to configure the query builder of the edge.
+func (_q *UserGroupQuery) WithUser(opts ...func(*UserQuery)) *UserGroupQuery {
+ query := (&UserClient{config: _q.config}).Query()
+ for _, opt := range opts {
+ opt(query)
+ }
+ _q.withUser = query
+ return _q
+}
+
+// WithGroup tells the query-builder to eager-load the nodes that are connected to
+// the "group" edge. The optional arguments are used to configure the query builder of the edge.
+func (_q *UserGroupQuery) WithGroup(opts ...func(*GroupQuery)) *UserGroupQuery {
+ query := (&GroupClient{config: _q.config}).Query()
+ for _, opt := range opts {
+ opt(query)
+ }
+ _q.withGroup = 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.
+//
+// Example:
+//
+// var v []struct {
+// UserID uuid.UUID `json:"user_id,omitempty"`
+// Count int `json:"count,omitempty"`
+// }
+//
+// client.UserGroup.Query().
+// GroupBy(usergroup.FieldUserID).
+// Aggregate(ent.Count()).
+// Scan(ctx, &v)
+func (_q *UserGroupQuery) GroupBy(field string, fields ...string) *UserGroupGroupBy {
+ _q.ctx.Fields = append([]string{field}, fields...)
+ grbuild := &UserGroupGroupBy{build: _q}
+ grbuild.flds = &_q.ctx.Fields
+ grbuild.label = usergroup.Label
+ grbuild.scan = grbuild.Scan
+ return grbuild
+}
+
+// Select allows the selection one or more fields/columns for the given query,
+// instead of selecting all fields in the entity.
+//
+// Example:
+//
+// var v []struct {
+// UserID uuid.UUID `json:"user_id,omitempty"`
+// }
+//
+// client.UserGroup.Query().
+// Select(usergroup.FieldUserID).
+// Scan(ctx, &v)
+func (_q *UserGroupQuery) Select(fields ...string) *UserGroupSelect {
+ _q.ctx.Fields = append(_q.ctx.Fields, fields...)
+ sbuild := &UserGroupSelect{UserGroupQuery: _q}
+ sbuild.label = usergroup.Label
+ sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan
+ return sbuild
+}
+
+// Aggregate returns a UserGroupSelect configured with the given aggregations.
+func (_q *UserGroupQuery) Aggregate(fns ...AggregateFunc) *UserGroupSelect {
+ return _q.Select().Aggregate(fns...)
+}
+
+func (_q *UserGroupQuery) prepareQuery(ctx context.Context) error {
+ for _, inter := range _q.inters {
+ if inter == nil {
+ return fmt.Errorf("ent: uninitialized interceptor (forgotten import ent/runtime?)")
+ }
+ if trv, ok := inter.(Traverser); ok {
+ if err := trv.Traverse(ctx, _q); err != nil {
+ return err
+ }
+ }
+ }
+ for _, f := range _q.ctx.Fields {
+ if !usergroup.ValidColumn(f) {
+ return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
+ }
+ }
+ if _q.path != nil {
+ prev, err := _q.path(ctx)
+ if err != nil {
+ return err
+ }
+ _q.sql = prev
+ }
+ return nil
+}
+
+func (_q *UserGroupQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*UserGroup, error) {
+ var (
+ nodes = []*UserGroup{}
+ _spec = _q.querySpec()
+ loadedTypes = [2]bool{
+ _q.withUser != nil,
+ _q.withGroup != nil,
+ }
+ )
+ _spec.ScanValues = func(columns []string) ([]any, error) {
+ return (*UserGroup).scanValues(nil, columns)
+ }
+ _spec.Assign = func(columns []string, values []any) error {
+ node := &UserGroup{config: _q.config}
+ nodes = append(nodes, node)
+ node.Edges.loadedTypes = loadedTypes
+ return node.assignValues(columns, values)
+ }
+ for i := range hooks {
+ hooks[i](ctx, _spec)
+ }
+ if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil {
+ return nil, err
+ }
+ if len(nodes) == 0 {
+ return nodes, nil
+ }
+ if query := _q.withUser; query != nil {
+ if err := _q.loadUser(ctx, query, nodes, nil,
+ func(n *UserGroup, e *User) { n.Edges.User = e }); err != nil {
+ return nil, err
+ }
+ }
+ if query := _q.withGroup; query != nil {
+ if err := _q.loadGroup(ctx, query, nodes, nil,
+ func(n *UserGroup, e *Group) { n.Edges.Group = e }); err != nil {
+ return nil, err
+ }
+ }
+ return nodes, nil
+}
+
+func (_q *UserGroupQuery) loadUser(ctx context.Context, query *UserQuery, nodes []*UserGroup, init func(*UserGroup), assign func(*UserGroup, *User)) error {
+ ids := make([]uuid.UUID, 0, len(nodes))
+ nodeids := make(map[uuid.UUID][]*UserGroup)
+ for i := range nodes {
+ fk := nodes[i].UserID
+ if _, ok := nodeids[fk]; !ok {
+ ids = append(ids, fk)
+ }
+ nodeids[fk] = append(nodeids[fk], nodes[i])
+ }
+ if len(ids) == 0 {
+ return nil
+ }
+ query.Where(user.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 "user_id" returned %v`, n.ID)
+ }
+ for i := range nodes {
+ assign(nodes[i], n)
+ }
+ }
+ return nil
+}
+func (_q *UserGroupQuery) loadGroup(ctx context.Context, query *GroupQuery, nodes []*UserGroup, init func(*UserGroup), assign func(*UserGroup, *Group)) error {
+ ids := make([]uuid.UUID, 0, len(nodes))
+ nodeids := make(map[uuid.UUID][]*UserGroup)
+ for i := range nodes {
+ fk := nodes[i].GroupID
+ if _, ok := nodeids[fk]; !ok {
+ ids = append(ids, fk)
+ }
+ nodeids[fk] = append(nodeids[fk], nodes[i])
+ }
+ if len(ids) == 0 {
+ return nil
+ }
+ query.Where(group.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 "group_id" returned %v`, n.ID)
+ }
+ for i := range nodes {
+ assign(nodes[i], n)
+ }
+ }
+ return nil
+}
+
+func (_q *UserGroupQuery) sqlCount(ctx context.Context) (int, error) {
+ _spec := _q.querySpec()
+ _spec.Unique = false
+ _spec.Node.Columns = nil
+ return sqlgraph.CountNodes(ctx, _q.driver, _spec)
+}
+
+func (_q *UserGroupQuery) querySpec() *sqlgraph.QuerySpec {
+ _spec := sqlgraph.NewQuerySpec(usergroup.Table, usergroup.Columns, nil)
+ _spec.From = _q.sql
+ if unique := _q.ctx.Unique; unique != nil {
+ _spec.Unique = *unique
+ } else if _q.path != nil {
+ _spec.Unique = true
+ }
+ if fields := _q.ctx.Fields; len(fields) > 0 {
+ _spec.Node.Columns = make([]string, 0, len(fields))
+ for i := range fields {
+ _spec.Node.Columns = append(_spec.Node.Columns, fields[i])
+ }
+ if _q.withUser != nil {
+ _spec.Node.AddColumnOnce(usergroup.FieldUserID)
+ }
+ if _q.withGroup != nil {
+ _spec.Node.AddColumnOnce(usergroup.FieldGroupID)
+ }
+ }
+ if ps := _q.predicates; len(ps) > 0 {
+ _spec.Predicate = func(selector *sql.Selector) {
+ for i := range ps {
+ ps[i](selector)
+ }
+ }
+ }
+ if limit := _q.ctx.Limit; limit != nil {
+ _spec.Limit = *limit
+ }
+ if offset := _q.ctx.Offset; offset != nil {
+ _spec.Offset = *offset
+ }
+ if ps := _q.order; len(ps) > 0 {
+ _spec.Order = func(selector *sql.Selector) {
+ for i := range ps {
+ ps[i](selector)
+ }
+ }
+ }
+ return _spec
+}
+
+func (_q *UserGroupQuery) sqlQuery(ctx context.Context) *sql.Selector {
+ builder := sql.Dialect(_q.driver.Dialect())
+ t1 := builder.Table(usergroup.Table)
+ columns := _q.ctx.Fields
+ if len(columns) == 0 {
+ columns = usergroup.Columns
+ }
+ selector := builder.Select(t1.Columns(columns...)...).From(t1)
+ if _q.sql != nil {
+ selector = _q.sql
+ selector.Select(selector.Columns(columns...)...)
+ }
+ if _q.ctx.Unique != nil && *_q.ctx.Unique {
+ selector.Distinct()
+ }
+ for _, p := range _q.predicates {
+ p(selector)
+ }
+ for _, p := range _q.order {
+ p(selector)
+ }
+ if offset := _q.ctx.Offset; offset != nil {
+ // limit is mandatory for offset clause. We start
+ // with default value, and override it below if needed.
+ selector.Offset(*offset).Limit(math.MaxInt32)
+ }
+ if limit := _q.ctx.Limit; limit != nil {
+ selector.Limit(*limit)
+ }
+ return selector
+}
+
+// UserGroupGroupBy is the group-by builder for UserGroup entities.
+type UserGroupGroupBy struct {
+ selector
+ build *UserGroupQuery
+}
+
+// Aggregate adds the given aggregation functions to the group-by query.
+func (_g *UserGroupGroupBy) Aggregate(fns ...AggregateFunc) *UserGroupGroupBy {
+ _g.fns = append(_g.fns, fns...)
+ return _g
+}
+
+// Scan applies the selector query and scans the result into the given value.
+func (_g *UserGroupGroupBy) Scan(ctx context.Context, v any) error {
+ ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy)
+ if err := _g.build.prepareQuery(ctx); err != nil {
+ return err
+ }
+ return scanWithInterceptors[*UserGroupQuery, *UserGroupGroupBy](ctx, _g.build, _g, _g.build.inters, v)
+}
+
+func (_g *UserGroupGroupBy) sqlScan(ctx context.Context, root *UserGroupQuery, v any) error {
+ selector := root.sqlQuery(ctx).Select()
+ aggregation := make([]string, 0, len(_g.fns))
+ for _, fn := range _g.fns {
+ aggregation = append(aggregation, fn(selector))
+ }
+ if len(selector.SelectedColumns()) == 0 {
+ columns := make([]string, 0, len(*_g.flds)+len(_g.fns))
+ for _, f := range *_g.flds {
+ columns = append(columns, selector.C(f))
+ }
+ columns = append(columns, aggregation...)
+ selector.Select(columns...)
+ }
+ selector.GroupBy(selector.Columns(*_g.flds...)...)
+ if err := selector.Err(); err != nil {
+ return err
+ }
+ rows := &sql.Rows{}
+ query, args := selector.Query()
+ if err := _g.build.driver.Query(ctx, query, args, rows); err != nil {
+ return err
+ }
+ defer rows.Close()
+ return sql.ScanSlice(rows, v)
+}
+
+// UserGroupSelect is the builder for selecting fields of UserGroup entities.
+type UserGroupSelect struct {
+ *UserGroupQuery
+ selector
+}
+
+// Aggregate adds the given aggregation functions to the selector query.
+func (_s *UserGroupSelect) Aggregate(fns ...AggregateFunc) *UserGroupSelect {
+ _s.fns = append(_s.fns, fns...)
+ return _s
+}
+
+// Scan applies the selector query and scans the result into the given value.
+func (_s *UserGroupSelect) Scan(ctx context.Context, v any) error {
+ ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect)
+ if err := _s.prepareQuery(ctx); err != nil {
+ return err
+ }
+ return scanWithInterceptors[*UserGroupQuery, *UserGroupSelect](ctx, _s.UserGroupQuery, _s, _s.inters, v)
+}
+
+func (_s *UserGroupSelect) sqlScan(ctx context.Context, root *UserGroupQuery, v any) error {
+ selector := root.sqlQuery(ctx)
+ aggregation := make([]string, 0, len(_s.fns))
+ for _, fn := range _s.fns {
+ aggregation = append(aggregation, fn(selector))
+ }
+ switch n := len(*_s.selector.flds); {
+ case n == 0 && len(aggregation) > 0:
+ selector.Select(aggregation...)
+ case n != 0 && len(aggregation) > 0:
+ selector.AppendSelect(aggregation...)
+ }
+ rows := &sql.Rows{}
+ query, args := selector.Query()
+ if err := _s.driver.Query(ctx, query, args, rows); err != nil {
+ return err
+ }
+ defer rows.Close()
+ return sql.ScanSlice(rows, v)
+}
diff --git a/backend/internal/data/ent/usergroup_update.go b/backend/internal/data/ent/usergroup_update.go
new file mode 100644
index 00000000..3806128b
--- /dev/null
+++ b/backend/internal/data/ent/usergroup_update.go
@@ -0,0 +1,468 @@
+// Code generated by ent, DO NOT EDIT.
+
+package ent
+
+import (
+ "context"
+ "errors"
+ "fmt"
+
+ "entgo.io/ent/dialect/sql"
+ "entgo.io/ent/dialect/sql/sqlgraph"
+ "entgo.io/ent/schema/field"
+ "github.com/google/uuid"
+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent/group"
+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent/predicate"
+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent/user"
+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent/usergroup"
+)
+
+// UserGroupUpdate is the builder for updating UserGroup entities.
+type UserGroupUpdate struct {
+ config
+ hooks []Hook
+ mutation *UserGroupMutation
+}
+
+// Where appends a list predicates to the UserGroupUpdate builder.
+func (_u *UserGroupUpdate) Where(ps ...predicate.UserGroup) *UserGroupUpdate {
+ _u.mutation.Where(ps...)
+ return _u
+}
+
+// SetUserID sets the "user_id" field.
+func (_u *UserGroupUpdate) SetUserID(v uuid.UUID) *UserGroupUpdate {
+ _u.mutation.SetUserID(v)
+ return _u
+}
+
+// SetNillableUserID sets the "user_id" field if the given value is not nil.
+func (_u *UserGroupUpdate) SetNillableUserID(v *uuid.UUID) *UserGroupUpdate {
+ if v != nil {
+ _u.SetUserID(*v)
+ }
+ return _u
+}
+
+// SetGroupID sets the "group_id" field.
+func (_u *UserGroupUpdate) SetGroupID(v uuid.UUID) *UserGroupUpdate {
+ _u.mutation.SetGroupID(v)
+ return _u
+}
+
+// SetNillableGroupID sets the "group_id" field if the given value is not nil.
+func (_u *UserGroupUpdate) SetNillableGroupID(v *uuid.UUID) *UserGroupUpdate {
+ if v != nil {
+ _u.SetGroupID(*v)
+ }
+ return _u
+}
+
+// SetRole sets the "role" field.
+func (_u *UserGroupUpdate) SetRole(v usergroup.Role) *UserGroupUpdate {
+ _u.mutation.SetRole(v)
+ return _u
+}
+
+// SetNillableRole sets the "role" field if the given value is not nil.
+func (_u *UserGroupUpdate) SetNillableRole(v *usergroup.Role) *UserGroupUpdate {
+ if v != nil {
+ _u.SetRole(*v)
+ }
+ return _u
+}
+
+// SetUser sets the "user" edge to the User entity.
+func (_u *UserGroupUpdate) SetUser(v *User) *UserGroupUpdate {
+ return _u.SetUserID(v.ID)
+}
+
+// SetGroup sets the "group" edge to the Group entity.
+func (_u *UserGroupUpdate) SetGroup(v *Group) *UserGroupUpdate {
+ return _u.SetGroupID(v.ID)
+}
+
+// Mutation returns the UserGroupMutation object of the builder.
+func (_u *UserGroupUpdate) Mutation() *UserGroupMutation {
+ return _u.mutation
+}
+
+// ClearUser clears the "user" edge to the User entity.
+func (_u *UserGroupUpdate) ClearUser() *UserGroupUpdate {
+ _u.mutation.ClearUser()
+ return _u
+}
+
+// ClearGroup clears the "group" edge to the Group entity.
+func (_u *UserGroupUpdate) ClearGroup() *UserGroupUpdate {
+ _u.mutation.ClearGroup()
+ return _u
+}
+
+// Save executes the query and returns the number of nodes affected by the update operation.
+func (_u *UserGroupUpdate) Save(ctx context.Context) (int, error) {
+ return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)
+}
+
+// SaveX is like Save, but panics if an error occurs.
+func (_u *UserGroupUpdate) SaveX(ctx context.Context) int {
+ affected, err := _u.Save(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return affected
+}
+
+// Exec executes the query.
+func (_u *UserGroupUpdate) Exec(ctx context.Context) error {
+ _, err := _u.Save(ctx)
+ return err
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (_u *UserGroupUpdate) ExecX(ctx context.Context) {
+ if err := _u.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
+
+// check runs all checks and user-defined validators on the builder.
+func (_u *UserGroupUpdate) check() error {
+ if v, ok := _u.mutation.Role(); ok {
+ if err := usergroup.RoleValidator(v); err != nil {
+ return &ValidationError{Name: "role", err: fmt.Errorf(`ent: validator failed for field "UserGroup.role": %w`, err)}
+ }
+ }
+ if _u.mutation.UserCleared() && len(_u.mutation.UserIDs()) > 0 {
+ return errors.New(`ent: clearing a required unique edge "UserGroup.user"`)
+ }
+ if _u.mutation.GroupCleared() && len(_u.mutation.GroupIDs()) > 0 {
+ return errors.New(`ent: clearing a required unique edge "UserGroup.group"`)
+ }
+ return nil
+}
+
+func (_u *UserGroupUpdate) sqlSave(ctx context.Context) (_node int, err error) {
+ if err := _u.check(); err != nil {
+ return _node, err
+ }
+ _spec := sqlgraph.NewUpdateSpec(usergroup.Table, usergroup.Columns, sqlgraph.NewFieldSpec(usergroup.FieldUserID, field.TypeUUID), sqlgraph.NewFieldSpec(usergroup.FieldGroupID, field.TypeUUID))
+ if ps := _u.mutation.predicates; len(ps) > 0 {
+ _spec.Predicate = func(selector *sql.Selector) {
+ for i := range ps {
+ ps[i](selector)
+ }
+ }
+ }
+ if value, ok := _u.mutation.Role(); ok {
+ _spec.SetField(usergroup.FieldRole, field.TypeEnum, value)
+ }
+ if _u.mutation.UserCleared() {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.M2O,
+ Inverse: false,
+ Table: usergroup.UserTable,
+ Columns: []string{usergroup.UserColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID),
+ },
+ }
+ _spec.Edges.Clear = append(_spec.Edges.Clear, edge)
+ }
+ if nodes := _u.mutation.UserIDs(); len(nodes) > 0 {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.M2O,
+ Inverse: false,
+ Table: usergroup.UserTable,
+ Columns: []string{usergroup.UserColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(user.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.GroupCleared() {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.M2O,
+ Inverse: false,
+ Table: usergroup.GroupTable,
+ Columns: []string{usergroup.GroupColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(group.FieldID, field.TypeUUID),
+ },
+ }
+ _spec.Edges.Clear = append(_spec.Edges.Clear, edge)
+ }
+ if nodes := _u.mutation.GroupIDs(); len(nodes) > 0 {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.M2O,
+ Inverse: false,
+ Table: usergroup.GroupTable,
+ Columns: []string{usergroup.GroupColumn},
+ 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 _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil {
+ if _, ok := err.(*sqlgraph.NotFoundError); ok {
+ err = &NotFoundError{usergroup.Label}
+ } else if sqlgraph.IsConstraintError(err) {
+ err = &ConstraintError{msg: err.Error(), wrap: err}
+ }
+ return 0, err
+ }
+ _u.mutation.done = true
+ return _node, nil
+}
+
+// UserGroupUpdateOne is the builder for updating a single UserGroup entity.
+type UserGroupUpdateOne struct {
+ config
+ fields []string
+ hooks []Hook
+ mutation *UserGroupMutation
+}
+
+// SetUserID sets the "user_id" field.
+func (_u *UserGroupUpdateOne) SetUserID(v uuid.UUID) *UserGroupUpdateOne {
+ _u.mutation.SetUserID(v)
+ return _u
+}
+
+// SetNillableUserID sets the "user_id" field if the given value is not nil.
+func (_u *UserGroupUpdateOne) SetNillableUserID(v *uuid.UUID) *UserGroupUpdateOne {
+ if v != nil {
+ _u.SetUserID(*v)
+ }
+ return _u
+}
+
+// SetGroupID sets the "group_id" field.
+func (_u *UserGroupUpdateOne) SetGroupID(v uuid.UUID) *UserGroupUpdateOne {
+ _u.mutation.SetGroupID(v)
+ return _u
+}
+
+// SetNillableGroupID sets the "group_id" field if the given value is not nil.
+func (_u *UserGroupUpdateOne) SetNillableGroupID(v *uuid.UUID) *UserGroupUpdateOne {
+ if v != nil {
+ _u.SetGroupID(*v)
+ }
+ return _u
+}
+
+// SetRole sets the "role" field.
+func (_u *UserGroupUpdateOne) SetRole(v usergroup.Role) *UserGroupUpdateOne {
+ _u.mutation.SetRole(v)
+ return _u
+}
+
+// SetNillableRole sets the "role" field if the given value is not nil.
+func (_u *UserGroupUpdateOne) SetNillableRole(v *usergroup.Role) *UserGroupUpdateOne {
+ if v != nil {
+ _u.SetRole(*v)
+ }
+ return _u
+}
+
+// SetUser sets the "user" edge to the User entity.
+func (_u *UserGroupUpdateOne) SetUser(v *User) *UserGroupUpdateOne {
+ return _u.SetUserID(v.ID)
+}
+
+// SetGroup sets the "group" edge to the Group entity.
+func (_u *UserGroupUpdateOne) SetGroup(v *Group) *UserGroupUpdateOne {
+ return _u.SetGroupID(v.ID)
+}
+
+// Mutation returns the UserGroupMutation object of the builder.
+func (_u *UserGroupUpdateOne) Mutation() *UserGroupMutation {
+ return _u.mutation
+}
+
+// ClearUser clears the "user" edge to the User entity.
+func (_u *UserGroupUpdateOne) ClearUser() *UserGroupUpdateOne {
+ _u.mutation.ClearUser()
+ return _u
+}
+
+// ClearGroup clears the "group" edge to the Group entity.
+func (_u *UserGroupUpdateOne) ClearGroup() *UserGroupUpdateOne {
+ _u.mutation.ClearGroup()
+ return _u
+}
+
+// Where appends a list predicates to the UserGroupUpdate builder.
+func (_u *UserGroupUpdateOne) Where(ps ...predicate.UserGroup) *UserGroupUpdateOne {
+ _u.mutation.Where(ps...)
+ return _u
+}
+
+// Select allows selecting one or more fields (columns) of the returned entity.
+// The default is selecting all fields defined in the entity schema.
+func (_u *UserGroupUpdateOne) Select(field string, fields ...string) *UserGroupUpdateOne {
+ _u.fields = append([]string{field}, fields...)
+ return _u
+}
+
+// Save executes the query and returns the updated UserGroup entity.
+func (_u *UserGroupUpdateOne) Save(ctx context.Context) (*UserGroup, error) {
+ return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)
+}
+
+// SaveX is like Save, but panics if an error occurs.
+func (_u *UserGroupUpdateOne) SaveX(ctx context.Context) *UserGroup {
+ node, err := _u.Save(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return node
+}
+
+// Exec executes the query on the entity.
+func (_u *UserGroupUpdateOne) Exec(ctx context.Context) error {
+ _, err := _u.Save(ctx)
+ return err
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (_u *UserGroupUpdateOne) ExecX(ctx context.Context) {
+ if err := _u.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
+
+// check runs all checks and user-defined validators on the builder.
+func (_u *UserGroupUpdateOne) check() error {
+ if v, ok := _u.mutation.Role(); ok {
+ if err := usergroup.RoleValidator(v); err != nil {
+ return &ValidationError{Name: "role", err: fmt.Errorf(`ent: validator failed for field "UserGroup.role": %w`, err)}
+ }
+ }
+ if _u.mutation.UserCleared() && len(_u.mutation.UserIDs()) > 0 {
+ return errors.New(`ent: clearing a required unique edge "UserGroup.user"`)
+ }
+ if _u.mutation.GroupCleared() && len(_u.mutation.GroupIDs()) > 0 {
+ return errors.New(`ent: clearing a required unique edge "UserGroup.group"`)
+ }
+ return nil
+}
+
+func (_u *UserGroupUpdateOne) sqlSave(ctx context.Context) (_node *UserGroup, err error) {
+ if err := _u.check(); err != nil {
+ return _node, err
+ }
+ _spec := sqlgraph.NewUpdateSpec(usergroup.Table, usergroup.Columns, sqlgraph.NewFieldSpec(usergroup.FieldUserID, field.TypeUUID), sqlgraph.NewFieldSpec(usergroup.FieldGroupID, field.TypeUUID))
+ if id, ok := _u.mutation.UserID(); !ok {
+ return nil, &ValidationError{Name: "user_id", err: errors.New(`ent: missing "UserGroup.user_id" for update`)}
+ } else {
+ _spec.Node.CompositeID[0].Value = id
+ }
+ if id, ok := _u.mutation.GroupID(); !ok {
+ return nil, &ValidationError{Name: "group_id", err: errors.New(`ent: missing "UserGroup.group_id" for update`)}
+ } else {
+ _spec.Node.CompositeID[1].Value = id
+ }
+ if fields := _u.fields; len(fields) > 0 {
+ _spec.Node.Columns = make([]string, len(fields))
+ for i, f := range fields {
+ if !usergroup.ValidColumn(f) {
+ return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
+ }
+ _spec.Node.Columns[i] = f
+ }
+ }
+ if ps := _u.mutation.predicates; len(ps) > 0 {
+ _spec.Predicate = func(selector *sql.Selector) {
+ for i := range ps {
+ ps[i](selector)
+ }
+ }
+ }
+ if value, ok := _u.mutation.Role(); ok {
+ _spec.SetField(usergroup.FieldRole, field.TypeEnum, value)
+ }
+ if _u.mutation.UserCleared() {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.M2O,
+ Inverse: false,
+ Table: usergroup.UserTable,
+ Columns: []string{usergroup.UserColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID),
+ },
+ }
+ _spec.Edges.Clear = append(_spec.Edges.Clear, edge)
+ }
+ if nodes := _u.mutation.UserIDs(); len(nodes) > 0 {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.M2O,
+ Inverse: false,
+ Table: usergroup.UserTable,
+ Columns: []string{usergroup.UserColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(user.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.GroupCleared() {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.M2O,
+ Inverse: false,
+ Table: usergroup.GroupTable,
+ Columns: []string{usergroup.GroupColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(group.FieldID, field.TypeUUID),
+ },
+ }
+ _spec.Edges.Clear = append(_spec.Edges.Clear, edge)
+ }
+ if nodes := _u.mutation.GroupIDs(); len(nodes) > 0 {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.M2O,
+ Inverse: false,
+ Table: usergroup.GroupTable,
+ Columns: []string{usergroup.GroupColumn},
+ 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)
+ }
+ _node = &UserGroup{config: _u.config}
+ _spec.Assign = _node.assignValues
+ _spec.ScanValues = _node.scanValues
+ if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil {
+ if _, ok := err.(*sqlgraph.NotFoundError); ok {
+ err = &NotFoundError{usergroup.Label}
+ } else if sqlgraph.IsConstraintError(err) {
+ err = &ConstraintError{msg: err.Error(), wrap: err}
+ }
+ return nil, err
+ }
+ _u.mutation.done = true
+ return _node, nil
+}
diff --git a/backend/internal/data/migrations/postgres/20260511000000_per_group_role.sql b/backend/internal/data/migrations/postgres/20260511000000_per_group_role.sql
new file mode 100644
index 00000000..44476d86
--- /dev/null
+++ b/backend/internal/data/migrations/postgres/20260511000000_per_group_role.sql
@@ -0,0 +1,32 @@
+-- +goose Up
+-- Move ownership from a global users.role enum to a per-membership role on
+-- user_groups. Backfill: a user is owner of their default_group_id (the group
+-- they registered with — fixed at registration and not user-mutable) and is a
+-- regular member of every other group they belong to. The prior global
+-- users.role column is removed; it was load-bearing for cross-group wipe and
+-- caused authorization bugs because every self-registered user got 'owner'
+-- regardless of the group being acted on.
+
+ALTER TABLE "user_groups"
+ ADD COLUMN "role" character varying NOT NULL DEFAULT 'user';
+
+UPDATE "user_groups"
+SET "role" = 'owner'
+FROM "users"
+WHERE "user_groups"."user_id" = "users"."id"
+ AND "user_groups"."group_id" = "users"."default_group_id";
+
+ALTER TABLE "users" DROP COLUMN "role";
+
+-- +goose Down
+ALTER TABLE "users"
+ ADD COLUMN "role" character varying NOT NULL DEFAULT 'user';
+
+UPDATE "users"
+SET "role" = 'owner'
+FROM "user_groups"
+WHERE "user_groups"."user_id" = "users"."id"
+ AND "user_groups"."group_id" = "users"."default_group_id"
+ AND "user_groups"."role" = 'owner';
+
+ALTER TABLE "user_groups" DROP COLUMN "role";
diff --git a/backend/internal/data/migrations/sqlite3/20260511000000_per_group_role.sql b/backend/internal/data/migrations/sqlite3/20260511000000_per_group_role.sql
new file mode 100644
index 00000000..e8b8ce38
--- /dev/null
+++ b/backend/internal/data/migrations/sqlite3/20260511000000_per_group_role.sql
@@ -0,0 +1,115 @@
+-- +goose Up
+-- +goose no transaction
+-- Move ownership from a global users.role enum to a per-membership role on
+-- user_groups. Backfill: a user is owner of their default_group_id (the group
+-- they registered with — fixed at registration and not user-mutable) and is a
+-- regular member of every other group they belong to. The prior global
+-- users.role column is removed; it was load-bearing for cross-group wipe and
+-- caused authorization bugs because every self-registered user got 'owner'
+-- regardless of the group being acted on.
+PRAGMA foreign_keys=OFF;
+
+-- 1. Add role to user_groups.
+ALTER TABLE user_groups ADD COLUMN role TEXT NOT NULL DEFAULT 'user';
+
+-- 2. Backfill role=owner where the membership is the user's default group.
+UPDATE user_groups
+SET role = 'owner'
+WHERE EXISTS (
+ SELECT 1 FROM users
+ WHERE users.id = user_groups.user_id
+ AND users.default_group_id = user_groups.group_id
+);
+
+-- 3. Drop users.role via table rebuild (SQLite-safe).
+CREATE TABLE users_new (
+ id UUID NOT NULL,
+ created_at DATETIME NOT NULL,
+ updated_at DATETIME NOT NULL,
+ name TEXT NOT NULL,
+ email TEXT NOT NULL,
+ password TEXT,
+ is_superuser BOOLEAN NOT NULL DEFAULT false,
+ superuser BOOLEAN NOT NULL DEFAULT false,
+ activated_on DATETIME,
+ oidc_issuer TEXT,
+ oidc_subject TEXT,
+ default_group_id UUID,
+ settings JSON DEFAULT '{}',
+ PRIMARY KEY (id),
+ CONSTRAINT users_groups_users_default FOREIGN KEY (default_group_id) REFERENCES groups(id) ON DELETE SET NULL
+);
+
+INSERT INTO users_new (
+ id, created_at, updated_at, name, email, password, is_superuser, superuser,
+ activated_on, oidc_issuer, oidc_subject, default_group_id, settings
+)
+SELECT
+ id, created_at, updated_at, name, email, password, is_superuser, superuser,
+ activated_on, oidc_issuer, oidc_subject, default_group_id, settings
+FROM users;
+
+DROP INDEX IF EXISTS users_email_key;
+DROP INDEX IF EXISTS users_oidc_issuer_subject_key;
+
+DROP TABLE users;
+ALTER TABLE users_new RENAME TO users;
+
+CREATE UNIQUE INDEX IF NOT EXISTS users_email_key ON users(email);
+CREATE UNIQUE INDEX IF NOT EXISTS users_oidc_issuer_subject_key ON users(oidc_issuer, oidc_subject);
+
+PRAGMA foreign_keys=ON;
+
+-- +goose Down
+-- +goose no transaction
+PRAGMA foreign_keys=OFF;
+
+CREATE TABLE users_new (
+ id UUID NOT NULL,
+ created_at DATETIME NOT NULL,
+ updated_at DATETIME NOT NULL,
+ name TEXT NOT NULL,
+ email TEXT NOT NULL,
+ password TEXT,
+ is_superuser BOOLEAN NOT NULL DEFAULT false,
+ superuser BOOLEAN NOT NULL DEFAULT false,
+ role TEXT NOT NULL DEFAULT 'user',
+ activated_on DATETIME,
+ oidc_issuer TEXT,
+ oidc_subject TEXT,
+ default_group_id UUID,
+ settings JSON DEFAULT '{}',
+ PRIMARY KEY (id),
+ CONSTRAINT users_groups_users_default FOREIGN KEY (default_group_id) REFERENCES groups(id) ON DELETE SET NULL
+);
+
+INSERT INTO users_new (
+ id, created_at, updated_at, name, email, password, is_superuser, superuser, role,
+ activated_on, oidc_issuer, oidc_subject, default_group_id, settings
+)
+SELECT
+ u.id, u.created_at, u.updated_at, u.name, u.email, u.password, u.is_superuser, u.superuser,
+ CASE
+ WHEN EXISTS (
+ SELECT 1 FROM user_groups ug
+ WHERE ug.user_id = u.id
+ AND ug.group_id = u.default_group_id
+ AND ug.role = 'owner'
+ ) THEN 'owner'
+ ELSE 'user'
+ END,
+ u.activated_on, u.oidc_issuer, u.oidc_subject, u.default_group_id, u.settings
+FROM users u;
+
+DROP INDEX IF EXISTS users_email_key;
+DROP INDEX IF EXISTS users_oidc_issuer_subject_key;
+
+DROP TABLE users;
+ALTER TABLE users_new RENAME TO users;
+
+CREATE UNIQUE INDEX IF NOT EXISTS users_email_key ON users(email);
+CREATE UNIQUE INDEX IF NOT EXISTS users_oidc_issuer_subject_key ON users(oidc_issuer, oidc_subject);
+
+ALTER TABLE user_groups DROP COLUMN role;
+
+PRAGMA foreign_keys=ON;
diff --git a/backend/internal/data/repo/repo_group.go b/backend/internal/data/repo/repo_group.go
index 3ac49eab..ce30ed7b 100644
--- a/backend/internal/data/repo/repo_group.go
+++ b/backend/internal/data/repo/repo_group.go
@@ -18,6 +18,7 @@ import (
"github.com/sysadminsmedia/homebox/backend/internal/data/ent/notifier"
"github.com/sysadminsmedia/homebox/backend/internal/data/ent/tag"
"github.com/sysadminsmedia/homebox/backend/internal/data/ent/user"
+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent/usergroup"
)
type GroupRepository struct {
@@ -278,14 +279,36 @@ func (r *GroupRepository) StatsGroup(ctx context.Context, gid uuid.UUID) (GroupS
}
func (r *GroupRepository) GroupCreate(ctx context.Context, name string, userID uuid.UUID) (Group, error) {
- createQuery := r.db.Group.Create().SetName(name)
+ if userID == uuid.Nil {
+ return r.groupMapper.MapErr(r.db.Group.Create().SetName(name).Save(ctx))
+ }
- // Only link user if a valid user ID is provided
- if userID != uuid.Nil {
- createQuery = createQuery.AddUserIDs(userID)
+ tx, err := r.db.Tx(ctx)
+ if err != nil {
+ return Group{}, err
}
- return r.groupMapper.MapErr(createQuery.Save(ctx))
+ g, err := tx.Group.Create().SetName(name).Save(ctx)
+ if err != nil {
+ _ = tx.Rollback()
+ return Group{}, err
+ }
+
+ // The user creating a group is its owner. This is the only place a fresh
+ // owner membership comes from outside registration.
+ if _, err := tx.UserGroup.Create().
+ SetUserID(userID).
+ SetGroupID(g.ID).
+ SetRole(usergroup.RoleOwner).
+ Save(ctx); err != nil {
+ _ = tx.Rollback()
+ return Group{}, err
+ }
+
+ if err := tx.Commit(); err != nil {
+ return Group{}, err
+ }
+ return r.groupMapper.Map(g), nil
}
func (r *GroupRepository) GroupUpdate(ctx context.Context, id uuid.UUID, data GroupUpdate) (Group, error) {
@@ -429,8 +452,17 @@ func (r *GroupRepository) IsMember(ctx context.Context, groupID, userID uuid.UUI
Exist(ctx)
}
-func (r *GroupRepository) AddMember(ctx context.Context, groupID, userID uuid.UUID) error {
- return r.db.Group.UpdateOneID(groupID).AddUserIDs(userID).Exec(ctx)
+// IsOwnerOf reports whether userID has role=owner on groupID. This is the
+// authoritative per-group ownership check and the only one authorization
+// code should consult — there is intentionally no global owner flag.
+func (r *GroupRepository) IsOwnerOf(ctx context.Context, userID, groupID uuid.UUID) (bool, error) {
+ return r.db.UserGroup.Query().
+ Where(
+ usergroup.UserID(userID),
+ usergroup.GroupID(groupID),
+ usergroup.RoleEQ(usergroup.RoleOwner),
+ ).
+ Exist(ctx)
}
func (r *GroupRepository) RemoveMember(ctx context.Context, groupID, userID uuid.UUID) error {
@@ -503,9 +535,12 @@ func (r *GroupRepository) InvitationAccept(ctx context.Context, token []byte, us
return Group{}, fmt.Errorf("user already a member of this group")
}
- // 4. Add member
- err = tx.Group.UpdateOneID(invitation.Edges.Group.ID).AddUserIDs(userID).Exec(ctx)
- if err != nil {
+ // 4. Add member with role=user; ownership is reserved for whoever created the group.
+ if _, err := tx.UserGroup.Create().
+ SetUserID(userID).
+ SetGroupID(invitation.Edges.Group.ID).
+ SetRole(usergroup.RoleUser).
+ Save(ctx); err != nil {
if err := tx.Rollback(); err != nil {
log.Warn().Err(err).Msg("failed to rollback transaction")
}
diff --git a/backend/internal/data/repo/repo_maintenance_entry.go b/backend/internal/data/repo/repo_maintenance_entry.go
index b4d71837..26630130 100644
--- a/backend/internal/data/repo/repo_maintenance_entry.go
+++ b/backend/internal/data/repo/repo_maintenance_entry.go
@@ -112,7 +112,18 @@ func (r *MaintenanceEntryRepository) Create(ctx context.Context, itemID uuid.UUI
return mapMaintenanceEntryErr(item, err)
}
-func (r *MaintenanceEntryRepository) Update(ctx context.Context, id uuid.UUID, input MaintenanceEntryUpdate) (MaintenanceEntry, error) {
+func (r *MaintenanceEntryRepository) Update(ctx context.Context, gid uuid.UUID, id uuid.UUID, input MaintenanceEntryUpdate) (MaintenanceEntry, error) {
+ owned, err := r.db.MaintenanceEntry.Query().Where(
+ maintenanceentry.ID(id),
+ maintenanceentry.HasEntityWith(entity.HasGroupWith(group.ID(gid))),
+ ).Exist(ctx)
+ if err != nil {
+ return MaintenanceEntry{}, err
+ }
+ if !owned {
+ return MaintenanceEntry{}, &ent.NotFoundError{}
+ }
+
item, err := r.db.MaintenanceEntry.UpdateOneID(id).
SetDate(input.CompletedDate.Time()).
SetScheduledDate(input.ScheduledDate.Time()).
@@ -169,6 +180,16 @@ func (r *MaintenanceEntryRepository) GetMaintenanceByItemID(ctx context.Context,
return mapEachMaintenanceEntryWithDetails(entries), nil
}
-func (r *MaintenanceEntryRepository) Delete(ctx context.Context, id uuid.UUID) error {
- return r.db.MaintenanceEntry.DeleteOneID(id).Exec(ctx)
+func (r *MaintenanceEntryRepository) Delete(ctx context.Context, gid uuid.UUID, id uuid.UUID) error {
+ deleted, err := r.db.MaintenanceEntry.Delete().Where(
+ maintenanceentry.ID(id),
+ maintenanceentry.HasEntityWith(entity.HasGroupWith(group.ID(gid))),
+ ).Exec(ctx)
+ if err != nil {
+ return err
+ }
+ if deleted == 0 {
+ return &ent.NotFoundError{}
+ }
+ return nil
}
diff --git a/backend/internal/data/repo/repo_maintenance_entry_test.go b/backend/internal/data/repo/repo_maintenance_entry_test.go
index d5b3c041..71302a80 100644
--- a/backend/internal/data/repo/repo_maintenance_entry_test.go
+++ b/backend/internal/data/repo/repo_maintenance_entry_test.go
@@ -76,7 +76,7 @@ func TestMaintenanceEntryRepository_GetLog(t *testing.T) {
assert.Len(t, log, 10)
for _, entry := range log {
- err := tRepos.MaintEntry.Delete(context.Background(), entry.ID)
+ err := tRepos.MaintEntry.Delete(context.Background(), tGroup.ID, entry.ID)
require.NoError(t, err)
}
}
diff --git a/backend/internal/data/repo/repo_notifier.go b/backend/internal/data/repo/repo_notifier.go
index 337122d7..bd2aa770 100644
--- a/backend/internal/data/repo/repo_notifier.go
+++ b/backend/internal/data/repo/repo_notifier.go
@@ -101,6 +101,14 @@ func (r *NotifierRepository) Create(ctx context.Context, groupID, userID uuid.UU
}
func (r *NotifierRepository) Update(ctx context.Context, userID uuid.UUID, id uuid.UUID, input NotifierUpdate) (NotifierOut, error) {
+ owned, err := r.db.Notifier.Query().Where(notifier.ID(id), notifier.UserID(userID)).Exist(ctx)
+ if err != nil {
+ return NotifierOut{}, err
+ }
+ if !owned {
+ return NotifierOut{}, &ent.NotFoundError{}
+ }
+
q := r.db.Notifier.
UpdateOneID(id).
SetName(input.Name).
@@ -110,9 +118,9 @@ func (r *NotifierRepository) Update(ctx context.Context, userID uuid.UUID, id uu
q.SetURL(*input.URL)
}
- notifier, err := q.Save(ctx)
+ updated, err := q.Save(ctx)
- return r.mapper.MapErr(notifier, err)
+ return r.mapper.MapErr(updated, err)
}
func (r *NotifierRepository) Delete(ctx context.Context, userID uuid.UUID, id uuid.UUID) error {
diff --git a/backend/internal/data/repo/repo_users.go b/backend/internal/data/repo/repo_users.go
index f6968d12..6a65cfa0 100644
--- a/backend/internal/data/repo/repo_users.go
+++ b/backend/internal/data/repo/repo_users.go
@@ -8,6 +8,7 @@ import (
"github.com/sysadminsmedia/homebox/backend/internal/data/ent"
"github.com/sysadminsmedia/homebox/backend/internal/data/ent/group"
"github.com/sysadminsmedia/homebox/backend/internal/data/ent/user"
+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent/usergroup"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/trace"
)
@@ -26,7 +27,9 @@ type (
Password *string `json:"password"`
IsSuperuser bool `json:"isSuperUser"`
DefaultGroupID uuid.UUID `json:"defaultGroupID"`
- IsOwner bool `json:"isOwner"`
+ // IsOwner controls the role on the membership row created for
+ // (user, DefaultGroupID). It does not grant any cross-group privilege.
+ IsOwner bool `json:"isOwner"`
}
UserUpdate struct {
@@ -42,16 +45,14 @@ type (
DefaultGroupID uuid.UUID `json:"defaultGroupId"`
GroupIDs []uuid.UUID `json:"groupIds"`
PasswordHash string `json:"-"`
- IsOwner bool `json:"isOwner"`
OidcIssuer *string `json:"oidcIssuer"`
OidcSubject *string `json:"oidcSubject"`
}
UserSummary struct {
- Name string `json:"name"`
- Email string `json:"email"`
- IsOwner bool `json:"isOwner"`
- ID uuid.UUID `json:"id"`
+ Name string `json:"name"`
+ Email string `json:"email"`
+ ID uuid.UUID `json:"id"`
}
)
@@ -72,7 +73,6 @@ func mapUserOut(user *ent.User) UserOut {
return g.ID
}),
PasswordHash: lo.FromPtrOr(user.Password, ""),
- IsOwner: user.Role == "owner",
OidcIssuer: user.OidcIssuer,
OidcSubject: user.OidcSubject,
}
@@ -80,10 +80,9 @@ func mapUserOut(user *ent.User) UserOut {
func mapUserSummary(user *ent.User) UserSummary {
return UserSummary{
- Name: user.Name,
- Email: user.Email,
- IsOwner: user.Role == "owner",
- ID: user.ID,
+ Name: user.Name,
+ Email: user.Email,
+ ID: user.ID,
}
}
@@ -93,7 +92,6 @@ func userSpanAttrs(out UserOut) []attribute.KeyValue {
attribute.String("user.default_group_id", out.DefaultGroupID.String()),
attribute.Int("user.groups.count", len(out.GroupIDs)),
attribute.Bool("user.is_superuser", out.IsSuperuser),
- attribute.Bool("user.is_owner", out.IsOwner),
attribute.Bool("user.has_password_hash", out.PasswordHash != ""),
attribute.Bool("user.has_oidc", out.OidcIssuer != nil && out.OidcSubject != nil),
}
@@ -181,44 +179,80 @@ func (r *UserRepository) GetAll(ctx context.Context) ([]UserOut, error) {
return out, nil
}
-func (r *UserRepository) Create(ctx context.Context, usr UserCreate) (UserOut, error) {
- ctx, span := entityTracer().Start(ctx, "repo.UserRepository.Create",
- trace.WithAttributes(
- attribute.String("user.default_group_id", usr.DefaultGroupID.String()),
- attribute.Bool("user.is_superuser", usr.IsSuperuser),
- attribute.Bool("user.is_owner", usr.IsOwner),
- attribute.Bool("user.has_password", usr.Password != nil),
- ))
- defer span.End()
+// membershipRole returns the per-membership role to assign for a UserCreate.
+func membershipRole(isOwner bool) usergroup.Role {
+ if isOwner {
+ return usergroup.RoleOwner
+ }
+ return usergroup.RoleUser
+}
- role := user.RoleUser
- if usr.IsOwner {
- role = user.RoleOwner
+// createUserWithMembership inserts the user row and the (user, default_group)
+// membership in a single transaction so the user always has exactly one
+// membership row when Create returns.
+func (r *UserRepository) createUserWithMembership(
+ ctx context.Context,
+ usr UserCreate,
+ configure func(*ent.UserCreate) *ent.UserCreate,
+) (uuid.UUID, error) {
+ tx, err := r.db.Tx(ctx)
+ if err != nil {
+ return uuid.Nil, err
}
- createQuery := r.db.User.
+ q := tx.User.
Create().
SetName(usr.Name).
SetEmail(usr.Email).
SetIsSuperuser(usr.IsSuperuser).
- SetDefaultGroupID(usr.DefaultGroupID).
- SetRole(role).
- AddGroupIDs(usr.DefaultGroupID)
+ SetDefaultGroupID(usr.DefaultGroupID)
- // Only set password if provided (non-nil)
if usr.Password != nil {
- createQuery = createQuery.SetPassword(*usr.Password)
+ q = q.SetPassword(*usr.Password)
+ }
+ if configure != nil {
+ q = configure(q)
}
- entUser, err := createQuery.Save(ctx)
+ entUser, err := q.Save(ctx)
+ if err != nil {
+ _ = tx.Rollback()
+ return uuid.Nil, err
+ }
+
+ if _, err := tx.UserGroup.Create().
+ SetUserID(entUser.ID).
+ SetGroupID(usr.DefaultGroupID).
+ SetRole(membershipRole(usr.IsOwner)).
+ Save(ctx); err != nil {
+ _ = tx.Rollback()
+ return uuid.Nil, err
+ }
+
+ if err := tx.Commit(); err != nil {
+ return uuid.Nil, err
+ }
+ return entUser.ID, nil
+}
+
+func (r *UserRepository) Create(ctx context.Context, usr UserCreate) (UserOut, error) {
+ ctx, span := entityTracer().Start(ctx, "repo.UserRepository.Create",
+ trace.WithAttributes(
+ attribute.String("user.default_group_id", usr.DefaultGroupID.String()),
+ attribute.Bool("user.is_superuser", usr.IsSuperuser),
+ attribute.Bool("user.is_owner", usr.IsOwner),
+ attribute.Bool("user.has_password", usr.Password != nil),
+ ))
+ defer span.End()
+
+ id, err := r.createUserWithMembership(ctx, usr, nil)
if err != nil {
recordSpanError(span, err)
return UserOut{}, err
}
+ span.SetAttributes(attribute.String("user.id", id.String()))
- span.SetAttributes(attribute.String("user.id", entUser.ID.String()))
-
- out, err := r.GetOneID(ctx, entUser.ID)
+ out, err := r.GetOneID(ctx, id)
if err != nil {
recordSpanError(span, err)
}
@@ -237,35 +271,16 @@ func (r *UserRepository) CreateWithOIDC(ctx context.Context, usr UserCreate, iss
))
defer span.End()
- role := user.RoleUser
- if usr.IsOwner {
- role = user.RoleOwner
- }
-
- createQuery := r.db.User.
- Create().
- SetName(usr.Name).
- SetEmail(usr.Email).
- SetIsSuperuser(usr.IsSuperuser).
- SetDefaultGroupID(usr.DefaultGroupID).
- SetRole(role).
- SetOidcIssuer(issuer).
- SetOidcSubject(subject).
- AddGroupIDs(usr.DefaultGroupID)
-
- if usr.Password != nil {
- createQuery = createQuery.SetPassword(*usr.Password)
- }
-
- entUser, err := createQuery.Save(ctx)
+ id, err := r.createUserWithMembership(ctx, usr, func(uc *ent.UserCreate) *ent.UserCreate {
+ return uc.SetOidcIssuer(issuer).SetOidcSubject(subject)
+ })
if err != nil {
recordSpanError(span, err)
return UserOut{}, err
}
+ span.SetAttributes(attribute.String("user.id", id.String()))
- span.SetAttributes(attribute.String("user.id", entUser.ID.String()))
-
- out, err := r.GetOneID(ctx, entUser.ID)
+ out, err := r.GetOneID(ctx, id)
if err != nil {
recordSpanError(span, err)
}
diff --git a/frontend/lib/api/classes/group.ts b/frontend/lib/api/classes/group.ts
index ffe5bea3..f543a7e9 100644
--- a/frontend/lib/api/classes/group.ts
+++ b/frontend/lib/api/classes/group.ts
@@ -5,7 +5,6 @@ import type {
GroupAcceptInvitationResponse,
GroupInvitation,
GroupInvitationCreate,
- GroupMemberAdd,
GroupUpdate,
UserSummary,
} from "../types/data-contracts";
@@ -63,22 +62,6 @@ export class GroupApi extends BaseAPI {
});
}
- /**
- * Add a user to the current (or specified) group.
- */
- addMember(data: GroupMemberAdd, groupId?: string) {
- const headers = groupId
- ? {
- "X-Tenant": groupId,
- }
- : undefined;
- return this.http.post<GroupMemberAdd, void>({
- url: route(`/groups/members`),
- headers,
- body: data,
- });
- }
-
/**
* Remove a user from the current (or specified) group.
*/