Admin: Adds setting to disable creating initial admin user (#19505)

Adds a new setting disable_admin_user and when true the default 
admin user will not be created when Grafana starts for the first 
time (or no users exists in the system).

Closes #19038
This commit is contained in:
Shavonn Brown
2019-11-08 05:11:03 -05:00
committed by Marcus Efraimsson
parent 7ebc4a1568
commit 3e5abe7c21
7 changed files with 110 additions and 67 deletions

View File

@@ -1,13 +1,18 @@
package sqlstore
import (
"context"
"fmt"
"time"
"github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/events"
m "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/setting"
)
const mainOrgName = "Main Org."
func init() {
bus.AddHandler("sql", GetOrgById)
bus.AddHandler("sql", CreateOrg)
@@ -214,3 +219,60 @@ func DeleteOrg(cmd *m.DeleteOrgCommand) error {
return nil
})
}
func getOrCreateOrg(sess *DBSession, orgName string) (int64, error) {
var org m.Org
if setting.AutoAssignOrg {
has, err := sess.Where("id=?", setting.AutoAssignOrgId).Get(&org)
if err != nil {
return 0, err
}
if has {
return org.Id, nil
}
if setting.AutoAssignOrgId == 1 {
org.Name = mainOrgName
org.Id = int64(setting.AutoAssignOrgId)
} else {
sqlog.Info("Could not create user: organization id %v does not exist",
setting.AutoAssignOrgId)
return 0, fmt.Errorf("Could not create user: organization id %v does not exist",
setting.AutoAssignOrgId)
}
} else {
org.Name = orgName
}
org.Created = time.Now()
org.Updated = time.Now()
if org.Id != 0 {
if _, err := sess.InsertId(&org); err != nil {
return 0, err
}
} else {
if _, err := sess.InsertOne(&org); err != nil {
return 0, err
}
}
sess.publishAfterCommit(&events.OrgCreated{
Timestamp: org.Created,
Id: org.Id,
Name: org.Name,
})
return org.Id, nil
}
func createDefaultOrg(ctx context.Context) error {
return inTransactionCtx(ctx, func(sess *DBSession) error {
_, err := getOrCreateOrg(sess, mainOrgName)
if err != nil {
return err
}
return nil
})
}