Auto-promote user on sign-up to admin if there are no valid users
This commit is contained in:
@@ -21,6 +21,7 @@ type (
|
||||
FindByID(id uint64) (*types.User, error)
|
||||
FindByIDs(id ...uint64) (types.UserSet, error)
|
||||
Find(filter *types.UserFilter) ([]*types.User, error)
|
||||
Total() uint
|
||||
|
||||
Create(mod *types.User) (*types.User, error)
|
||||
Update(mod *types.User) (*types.User, error)
|
||||
@@ -142,6 +143,12 @@ func (r *user) Find(filter *types.UserFilter) ([]*types.User, error) {
|
||||
return rval, nil
|
||||
}
|
||||
|
||||
func (r user) Total() (count uint) {
|
||||
query := fmt.Sprintf("SELECT COUNT(*) FROM %s WHERE %s", r.users, sqlUserScope)
|
||||
_ = r.db().Select(&count, query)
|
||||
return
|
||||
}
|
||||
|
||||
func (r *user) Create(mod *types.User) (*types.User, error) {
|
||||
mod.ID = factory.Sonyflake.NextID()
|
||||
mod.CreatedAt = time.Now()
|
||||
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
"go.uber.org/zap/zapcore"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
|
||||
"github.com/cortezaproject/corteza-server/internal/permissions"
|
||||
"github.com/cortezaproject/corteza-server/internal/rand"
|
||||
"github.com/cortezaproject/corteza-server/pkg/logger"
|
||||
"github.com/cortezaproject/corteza-server/system/internal/repository"
|
||||
@@ -210,6 +211,7 @@ func (svc auth) External(profile goth.User) (u *types.User, err error) {
|
||||
zap.String("email", u.Email),
|
||||
)
|
||||
|
||||
_ = svc.autoPromote(u)
|
||||
} else if err != nil {
|
||||
return err
|
||||
} else if !u.Valid() {
|
||||
@@ -326,6 +328,8 @@ func (svc auth) InternalSignUp(input *types.User, password string) (u *types.Use
|
||||
return nil, errors.Wrap(err, "could not create user")
|
||||
}
|
||||
|
||||
_ = svc.autoPromote(u)
|
||||
|
||||
if len(password) > 0 {
|
||||
var hash []byte
|
||||
hash, err = svc.hashPassword(password)
|
||||
@@ -808,6 +812,21 @@ func (svc auth) createUserToken(user *types.User, kind string) (token string, er
|
||||
return
|
||||
}
|
||||
|
||||
// Automatically promotes user to administrator if it is the first user in the database
|
||||
func (svc auth) autoPromote(u *types.User) (err error) {
|
||||
if svc.users.Total() == 0 && u.ID > 0 {
|
||||
err = svc.roles.MemberAddByID(permissions.AdminRoleID, u.ID)
|
||||
}
|
||||
|
||||
svc.log(
|
||||
zap.String("email", u.Email),
|
||||
zap.Uint64("userID", u.ID),
|
||||
zap.Error(err),
|
||||
).Info("auto-promoted user to administrator role")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
func (svc auth) LoadRoleMemberships(u *types.User) error {
|
||||
rr, err := svc.roles.FindByMemberID(u.ID)
|
||||
if err != nil {
|
||||
|
||||
Reference in New Issue
Block a user