feat: support bind user to tenants

This commit is contained in:
Rogee
2024-12-12 19:26:48 +08:00
parent 259b334711
commit 8a1477e991
7 changed files with 113 additions and 2 deletions

View File

@@ -0,0 +1,39 @@
package tenant
import (
"context"
"backend/modules/users"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
)
// @provider
type Bind struct {
userSvc *users.Service
log *log.Entry `inject:"false"`
}
// Prepare
func (d *Bind) Prepare() error {
d.log = log.WithField("module", "tenants.bind")
return nil
}
func (d *Bind) RunE(slug string, userID int64) error {
d.log.Infof("bind tenant %s with user %d", slug, userID)
tenant, err := d.userSvc.GetTenantBySlug(context.Background(), slug)
if err != nil {
return errors.Wrapf(err, "get tenant: %s", slug)
}
err = d.userSvc.SetTenantBindUserID(context.Background(), tenant.ID, userID)
if err != nil {
return errors.Wrapf(err, "bind tenant: %s with user %d", tenant.ID, userID)
}
d.log.Infof("bind tenant success: %s(%d) with user %d", slug, tenant.ID, userID)
return nil
}

View File

@@ -8,6 +8,20 @@ import (
)
func Provide(opts ...opt.Option) error {
if err := container.Container.Provide(func(
userSvc *users.Service,
) (*Bind, error) {
obj := &Bind{
userSvc: userSvc,
}
if err := obj.Prepare(); err != nil {
return nil, err
}
return obj, nil
}); err != nil {
return err
}
if err := container.Container.Provide(func(
userSvc *users.Service,
) (*Create, error) {

View File

@@ -396,3 +396,20 @@ func (svc *Service) GetTenantUserBalance(ctx context.Context, tenantID, userID i
}
return result.Balance, nil
}
// SetTenantBindUserID
func (svc *Service) SetTenantBindUserID(ctx context.Context, tenantID, adminUserID int64) error {
log := svc.log.WithField("method", "SetTenantBindUserID")
tbl := table.Tenants
stmt := tbl.
UPDATE(tbl.BindUserID).
SET(Int64(adminUserID)).
WHERE(tbl.ID.EQ(Int64(tenantID)))
log.Debug(stmt.DebugSql())
if _, err := stmt.ExecContext(ctx, db.FromContext(ctx, svc.db)); err != nil {
return errors.Wrap(err, "failed to set tenant admin user id")
}
return nil
}