2016-09-26 18:48:55 +00:00
|
|
|
package service
|
2016-08-28 03:59:17 +00:00
|
|
|
|
|
|
|
import (
|
2017-03-15 15:55:30 +00:00
|
|
|
"context"
|
2016-08-28 03:59:17 +00:00
|
|
|
|
2021-08-20 15:27:41 +00:00
|
|
|
"github.com/fleetdm/fleet/v4/server"
|
|
|
|
|
2021-11-22 14:13:26 +00:00
|
|
|
"github.com/fleetdm/fleet/v4/server/contexts/ctxerr"
|
2021-06-26 04:46:51 +00:00
|
|
|
"github.com/fleetdm/fleet/v4/server/fleet"
|
|
|
|
"github.com/fleetdm/fleet/v4/server/ptr"
|
2016-08-28 03:59:17 +00:00
|
|
|
)
|
|
|
|
|
2021-06-06 22:07:29 +00:00
|
|
|
func (svc *Service) CreateInitialUser(ctx context.Context, p fleet.UserPayload) (*fleet.User, error) {
|
2021-06-03 23:24:15 +00:00
|
|
|
// skipauth: Only the initial user creation should be allowed to skip
|
|
|
|
// authorization (because there is not yet a user context to check against).
|
|
|
|
svc.authz.SkipAuthorization(ctx)
|
|
|
|
|
|
|
|
setupRequired, err := svc.SetupRequired(ctx)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
if !setupRequired {
|
2021-11-22 14:13:26 +00:00
|
|
|
return nil, ctxerr.New(ctx, "a user already exists")
|
2021-06-03 23:24:15 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Initial user should be global admin with no explicit teams
|
2021-06-06 22:07:29 +00:00
|
|
|
p.GlobalRole = ptr.String(fleet.RoleAdmin)
|
2021-06-03 23:24:15 +00:00
|
|
|
p.Teams = nil
|
|
|
|
|
2021-09-14 12:11:07 +00:00
|
|
|
return svc.newUser(ctx, p)
|
2016-11-09 17:19:07 +00:00
|
|
|
}
|
|
|
|
|
2021-09-14 12:11:07 +00:00
|
|
|
func (svc *Service) newUser(ctx context.Context, p fleet.UserPayload) (*fleet.User, error) {
|
2017-05-10 16:26:05 +00:00
|
|
|
var ssoEnabled bool
|
|
|
|
// if user is SSO generate a fake password
|
2020-11-05 01:06:55 +00:00
|
|
|
if (p.SSOInvite != nil && *p.SSOInvite) || (p.SSOEnabled != nil && *p.SSOEnabled) {
|
2021-07-19 18:08:41 +00:00
|
|
|
fakePassword, err := server.GenerateRandomText(14)
|
2017-05-10 16:26:05 +00:00
|
|
|
if err != nil {
|
2021-11-22 14:13:26 +00:00
|
|
|
return nil, ctxerr.Wrap(ctx, err, "generate stand-in password")
|
2017-05-10 16:26:05 +00:00
|
|
|
}
|
|
|
|
p.Password = &fakePassword
|
|
|
|
ssoEnabled = true
|
|
|
|
}
|
2016-11-09 17:19:07 +00:00
|
|
|
user, err := p.User(svc.config.Auth.SaltKeySize, svc.config.Auth.BcryptCost)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2017-05-10 16:26:05 +00:00
|
|
|
user.SSOEnabled = ssoEnabled
|
2021-09-14 12:11:07 +00:00
|
|
|
user, err = svc.ds.NewUser(ctx, user)
|
2016-09-29 02:44:05 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2016-08-28 03:59:17 +00:00
|
|
|
return user, nil
|
|
|
|
}
|
|
|
|
|
2021-06-06 22:07:29 +00:00
|
|
|
func (svc *Service) UserUnauthorized(ctx context.Context, id uint) (*fleet.User, error) {
|
2021-06-03 23:24:15 +00:00
|
|
|
// Explicitly no authorization check. Should only be used by middleware.
|
2021-09-14 12:11:07 +00:00
|
|
|
return svc.ds.UserByID(ctx, id)
|
2016-08-29 00:29:56 +00:00
|
|
|
}
|