From dd8d2a677d28c6e1ea2f4bb0bf5eee43cc7b1707 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=F0=9F=90=99PiperYxzzy?= Date: Sun, 1 May 2022 12:48:40 +0200 Subject: [PATCH] Added better Tenanting * Removed Tenanting from base objects as some models may be tenantless * Admins are naturally not restricted by tenants * Users *ARE* the tenants (for now) so they don't require a tenant ID either * User-owned models should all include the Tenanted model as their base * Created .Create and .Save methods attached to base model --- models/base.go | 12 +++--------- models/tenanted.go | 21 +++++++++++++++++++++ models/user.go | 3 +-- 3 files changed, 25 insertions(+), 11 deletions(-) create mode 100644 models/tenanted.go diff --git a/models/base.go b/models/base.go index db1bb92..4fcd7b2 100644 --- a/models/base.go +++ b/models/base.go @@ -1,7 +1,6 @@ package models import ( - "errors" "time" "github.com/google/uuid" @@ -9,11 +8,10 @@ import ( ) type Base struct { - Uid uuid.UUID `gorm:"type:uuid;primary_key;"` - Created time.Time + Uid uuid.UUID `gorm:"type:uuid;primary_key;<-:create"` + Created time.Time `gorm:"<-:create"` Updated time.Time - Deleted time.Time `sql:"index"` - Tenant uuid.UUID `sql:"index"` + Deleted time.Time `gorm:"index"` } func (b *Base) BeforeCreate(scope *gorm.DB) error { @@ -23,10 +21,6 @@ func (b *Base) BeforeCreate(scope *gorm.DB) error { } func (b *Base) BeforeSave(scope *gorm.DB) error { - if b.Tenant == uuid.Nil { - return errors.New("cannot save an untenanted object") - } - b.Updated = time.Now() return nil } diff --git a/models/tenanted.go b/models/tenanted.go new file mode 100644 index 0000000..a8309ba --- /dev/null +++ b/models/tenanted.go @@ -0,0 +1,21 @@ +package models + +import ( + "errors" + + "github.com/google/uuid" + + "gorm.io/gorm" +) + +type Tenanted struct { + Base + Tenant uuid.UUID `gorm:"index;<-:create"` +} + +func (t *Tenanted) BeforeCreate(scope *gorm.DB) error { + if t.Tenant == uuid.Nil { + return errors.New("cannot save an untenanted object") + } + return nil +} diff --git a/models/user.go b/models/user.go index 9bb6081..6d920be 100644 --- a/models/user.go +++ b/models/user.go @@ -11,7 +11,7 @@ import ( type User struct { Auth - Email string `gorm:"unique" sql:"index"` + Email string `gorm:"unique;index"` } const userJwtDuration = time.Hour * 24 @@ -24,7 +24,6 @@ func (u *User) GetJwt() (string, int) { "iat": time.Now().Unix(), "exp": time.Now().Add(userJwtDuration).Unix(), "role": "user", - "tid": u.Tenant.String(), }) jstr, err := j.SignedString(UserHmac)