// Create a new userEK and upload it. Add our box to the local box store.
359466
func publishNewUserEK(mctx libkb.MetaContext, merkleRoot libkb.MerkleRoot) (
	metadata keybase1.UserEkMetadata, err error) {
	defer mctx.TraceTimed("publishNewUserEK", func() error { return err })()

	// Sign the statement blob with the latest PUK.
	pukKeyring, err := mctx.G().GetPerUserKeyring(mctx.Ctx())
	if err != nil {
		return metadata, err
	}
	if err := pukKeyring.Sync(mctx); err != nil {
		return metadata, err
	}
	if !pukKeyring.HasAnyKeys() {
		return metadata, fmt.Errorf("A PUK is needed to generate ephemeral keys. Aborting.")
	}
	pukSigning, err := pukKeyring.GetLatestSigningKey(mctx)
	if err != nil {
		return metadata, err
	}

	sig, boxes, newMetadata, myBox, err := prepareNewUserEK(mctx, merkleRoot, pukSigning)
	if err != nil {
		return metadata, err
	}

	if err = postNewUserEK(mctx, sig, boxes); err != nil {
		return metadata, err
	}

	// Cache the new box after we see the post succeeded.
	if myBox == nil {
		mctx.Debug("No box made for own deviceEK")
	} else {
		storage := mctx.G().GetUserEKBoxStorage()
		err = storage.Put(mctx, newMetadata.Generation, *myBox)
	}
	return newMetadata, err
}
589913
func AddUserEKReBoxServerArg(serverArg JSONPayload, arg *keybase1.UserEkReboxArg) {
	if arg == nil {
		return
	}
	serverArg["device_eks"] = map[string]string{string(arg.DeviceID): arg.DeviceEkStatementSig}
	serverArg["user_ek_rebox"] = arg.UserEkBoxMetadata
}
380173
func CreateUser(c *context.APIContext, form api.CreateUserOption) {
	u := &models.User{
		Name:      form.Username,
		FullName:  form.FullName,
		Email:     form.Email,
		Passwd:    form.Password,
		IsActive:  true,
		LoginType: models.LOGIN_PLAIN,
	}

	parseLoginSource(c, u, form.SourceID, form.LoginName)
	if c.Written() {
		return
	}

	if err := models.CreateUser(u); err != nil {
		if models.IsErrUserAlreadyExist(err) ||
			models.IsErrEmailAlreadyUsed(err) ||
			models.IsErrNameReserved(err) ||
			models.IsErrNamePatternNotAllowed(err) {
			c.Error(422, "", err)
		} else {
			c.Error(500, "CreateUser", err)
		}
		return
	}
	log.Trace("Account created by admin (%s): %s", c.User.Name, u.Name)

	// Send email notification.
	if form.SendNotify && setting.MailService != nil {
		mailer.SendRegisterNotifyMail(c.Context.Context, models.NewMailerUser(u))
	}

	c.JSON(201, u.APIFormat())
}
1272220
func CreateUser(u *User) (err error) {
	if err = IsUsableUsername(u.Name); err != nil {
		return err
	}

	isExist, err := IsUserExist(0, u.Name)
	if err != nil {
		return err
	} else if isExist {
		return ErrUserAlreadyExist{u.Name}
	}

	u.Email = strings.ToLower(u.Email)
	isExist, err = IsEmailUsed(u.Email)
	if err != nil {
		return err
	} else if isExist {
		return ErrEmailAlreadyUsed{u.Email}
	}

	u.LowerName = strings.ToLower(u.Name)
	u.AvatarEmail = u.Email
	u.Avatar = tool.HashEmail(u.AvatarEmail)
	if u.Rands, err = GetUserSalt(); err != nil {
		return err
	}
	if u.Salt, err = GetUserSalt(); err != nil {
		return err
	}
	u.EncodePasswd()
	u.MaxRepoCreation = -1

	sess := x.NewSession()
	defer sess.Close()
	if err = sess.Begin(); err != nil {
		return err
	}

	if _, err = sess.Insert(u); err != nil {
		return err
	} else if err = os.MkdirAll(UserPath(u.Name), os.ModePerm); err != nil {
		return err
	}

	return sess.Commit()
}
713449
func (self *CustomerClient) Create(c *CustomerParams) (*Customer, error) {
	customer := Customer{}
	values := url.Values{}
	appendCustomerParamsToValues(c, &values)

	err := query("POST", "/v1/customers", values, &customer)
	return &customer, err
}
379431
func (n *nessusImpl) CreateUser(username, password, userType, permissions, name, email string) (*User, error) {
	if n.verbose {
		log.Println("Creating new user...")
	}
	data := createUserRequest{
		Username:    username,
		Password:    password,
		Permissions: permissions,
		Type:        userType,
	}
	if name != "" {
		data.Name = name
	}
	if email != "" {
		data.Email = email
	}

	resp, err := n.doRequest("POST", "/users", data, []int{http.StatusOK})
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	reply := &User{}
	if err = json.NewDecoder(resp.Body).Decode(&reply); err != nil {
		return nil, err
	}
	return reply, nil
}
1228466
func (vd *volAPI) create(w http.ResponseWriter, r *http.Request) {
	var dcRes api.VolumeCreateResponse
	var dcReq api.VolumeCreateRequest
	method := "create"

	if err := json.NewDecoder(r.Body).Decode(&dcReq); err != nil {
		fmt.Println("returning error here")
		vd.sendError(vd.name, method, w, err.Error(), http.StatusBadRequest)
		return
	}

	// Get context with auth token
	ctx, err := vd.annotateContext(r)
	if err != nil {
		vd.sendError(vd.name, method, w, err.Error(), http.StatusBadRequest)
		return
	}

	// Get gRPC connection
	conn, err := vd.getConn()
	if err != nil {
		vd.sendError(vd.name, method, w, err.Error(), http.StatusInternalServerError)
		return
	}
	spec := dcReq.GetSpec()
	if spec.VolumeLabels == nil {
		spec.VolumeLabels = make(map[string]string)
	}
	for k, v := range dcReq.Locator.GetVolumeLabels() {
		spec.VolumeLabels[k] = v
	}

	volumes := api.NewOpenStorageVolumeClient(conn)
	id, err := volumes.Create(ctx, &api.SdkVolumeCreateRequest{
		Name:   dcReq.Locator.GetName(),
		Labels: dcReq.Locator.GetVolumeLabels(),
		Spec:   dcReq.GetSpec(),
	})

	dcRes.VolumeResponse = &api.VolumeResponse{Error: responseStatus(err)}
	if err == nil {
		dcRes.Id = id.GetVolumeId()
	}

	json.NewEncoder(w).Encode(&dcRes)
}
280811
func (s *UserService) NewCreateUserParams(account string, email string, firstname string, lastname string, password string, username string) *CreateUserParams {
	p := &CreateUserParams{}
	p.p = make(map[string]interface{})
	p.p["account"] = account
	p.p["email"] = email
	p.p["firstname"] = firstname
	p.p["lastname"] = lastname
	p.p["password"] = password
	p.p["username"] = username
	return p
}
187296
func (s *service) Add(reqDTO rest.RequestDTO) (resDTO rest.ResponseDTO, error *servicehelper.Error) {
	entity, Err := createEntityFromDTO(reqDTO, true)
	if Err != nil {
		return rest.ResponseDTO{}, Err
	} else if s.repo.Create(entity) {
		return createDTOFromEntity(entity), error
	}
	return rest.ResponseDTO{}, &servicehelper.Error{
		Detail:  errors.New("user could not be created"),
		Message: "We could not created this account because an account already use this email address",
		Param:   "email",
		Code:    servicehelper.AlreadyExist,
	}
}
447162
func (p *PostService) Create(teamName string, post Post) (*PostResponse, error) {
	postURL := PostURL + "/" + teamName + "/posts"
	var postRes PostResponse
	var postReq PostReq
	postReq.Post = post
	var data []byte
	var err error
	if data, err = json.Marshal(postReq); err != nil {
		return nil, err
	}

	res, err := p.client.post(postURL, "application/json", bytes.NewReader(data), &postRes)
	if err != nil {
		return nil, err
	}

	defer res.Body.Close()

	return &postRes, nil
}
33521
func (s *UserService) CreateUser(p *CreateUserParams) (*CreateUserResponse, error) {
	resp, err := s.cs.newRequest("createUser", p.toURLValues())
	if err != nil {
		return nil, err
	}

	if resp, err = getRawValue(resp); err != nil {
		return nil, err
	}

	var r CreateUserResponse
	if err := json.Unmarshal(resp, &r); err != nil {
		return nil, err
	}

	return &r, nil
}
916185
func (client *Client) CreateUser(user string, password string, origin string) (User, error) {
	userRequest := newUserRequestBody{
		Username: user,
		Password: password,
		Origin:   origin,
		Name: userName{
			FamilyName: user,
			GivenName:  user,
		},
		Emails: []email{
			{
				Value:   user,
				Primary: true,
			},
		},
	}

	bodyBytes, err := json.Marshal(userRequest)
	if err != nil {
		return User{}, err
	}

	request, err := client.newRequest(requestOptions{
		RequestName: internal.PostUserRequest,
		Header: http.Header{
			"Content-Type": {"application/json"},
		},
		Body: bytes.NewBuffer(bodyBytes),
	})
	if err != nil {
		return User{}, err
	}

	var userResponse newUserResponse
	response := Response{
		Result: &userResponse,
	}

	err = client.connection.Make(request, &response)
	if err != nil {
		return User{}, err
	}

	return User(userResponse), nil
}
350868
func NewCreateUser(ctx *middleware.Context, handler CreateUserHandler) *CreateUser {
	return &CreateUser{Context: ctx, Handler: handler}
}
135223
func CreateOrg(c *context.APIContext, form api.CreateOrgOption) {
	org.CreateOrgForUser(c, form, user.GetUserByParams(c))
}
388937
func (u *UserResource) createUser(request *restful.Request, response *restful.Response) {
	usr := User{Id: request.PathParameter("user-id")}
	err := request.ReadEntity(&usr)
	if err == nil {
		u.users[usr.Id] = usr
		response.WriteHeaderAndEntity(http.StatusCreated, usr)
	} else {
		response.AddHeader("Content-Type", "text/plain")
		response.WriteErrorString(http.StatusInternalServerError, err.Error())
	}
}
193367
func (c *UsersController) Create(ctx *app.CreateUsersContext) error {

	isSvcAccount := token.IsSpecificServiceAccount(ctx, token.OnlineRegistration)
	if !isSvcAccount {
		log.Error(ctx, nil, "The account is not an authorized service account allowed to create a new user")
		return jsonapi.JSONErrorResponse(ctx, errors.NewUnauthorizedError("account not authorized to create users."))
	}

	// ----- Ignore users created for Preview environment
	// TODO remove this when we start using our regular user registration flow in staging environment
	preview, err := c.checkPreviewUser(ctx.Payload.Data.Attributes.Email)
	if err != nil {
		log.Error(ctx, map[string]interface{}{"err": err, "email": ctx.Payload.Data.Attributes.Email}, "unable to parse user's email")
		return jsonapi.JSONErrorResponse(ctx, errors.NewInternalError(ctx, err))
	}
	if preview {
		log.Info(ctx, map[string]interface{}{"email": ctx.Payload.Data.Attributes.Email}, "ignoring preview user")
		user := &accountrepo.User{Email: ctx.Payload.Data.Attributes.Email, Cluster: ctx.Payload.Data.Attributes.Cluster}
		identity := &accountrepo.Identity{Username: ctx.Payload.Data.Attributes.Username, ProviderType: accountrepo.DefaultIDP}
		return ctx.OK(ConvertToAppUser(ctx.RequestData, user, identity, true))
	}
	// -----

	userExists, err := c.userExistsInDB(ctx, ctx.Payload.Data.Attributes.Email, ctx.Payload.Data.Attributes.Username)
	if err != nil {
		return jsonapi.JSONErrorResponse(ctx, errors.NewInternalError(ctx, err))
	}
	if userExists {
		// This may happen for manually banned users which are reactivating their account via the registration app
		// We should re-deprovision such user
		idn, err := c.app.UserService().IdentityByUsernameAndEmail(ctx, ctx.Payload.Data.Attributes.Username, ctx.Payload.Data.Attributes.Email)
		if err != nil {
			log.Error(ctx, map[string]interface{}{
				"err":      err,
				"username": ctx.Payload.Data.Attributes.Username,
				"email":    ctx.Payload.Data.Attributes.Email,
			}, "unable to lookup identity by username and email")
			return jsonapi.JSONErrorResponse(ctx, errors.NewInternalError(ctx, err))
		}
		if idn == nil {
			return jsonapi.JSONErrorResponse(ctx, errors.NewVersionConflictError("user with such email or username already exists"))
		}
		if idn.User.Banned {
			err := c.app.UserService().ResetBan(ctx, idn.User)
			if err != nil {
				log.Error(ctx, map[string]interface{}{"err": err, "username": ctx.Payload.Data.Attributes.Username, "email": ctx.Payload.Data.Attributes.Email}, "unable to re-provision user")
				return jsonapi.JSONErrorResponse(ctx, errors.NewInternalError(ctx, err))
			}
		}
		// User/identity already exist. Just return it.
		return ctx.OK(ConvertToAppUser(ctx.RequestData, &idn.User, idn, true))
	}

	// If it's a new user, Auth service generates an Identity ID for the user.
	identityID := uuid.NewV4()
	identity, user, err := c.createUserInDB(ctx, identityID)
	if err != nil {
		log.Error(ctx, map[string]interface{}{
			"err":      err,
			"username": identity.Username,
		}, "failed to create user in DB")

		return jsonapi.JSONErrorResponse(ctx, errors.NewInternalError(ctx, err))
	}

	// we create a identity cluster relationship in cluster management service.
	clusterURL := ctx.Payload.Data.Attributes.Cluster
	err = c.app.ClusterService().LinkIdentityToCluster(ctx.Context, identityID, clusterURL)
	if err != nil {
		log.Error(ctx, map[string]interface{}{
			"err":         err,
			"identity_id": identityID,
			"cluster_url": clusterURL,
		}, "failed to link identity to cluster in cluster service")

		// hard delete user and identity from DB so reg app can repeat provisioning
		if err := c.app.UserService().HardDeleteUser(ctx.Context, *identity); err != nil {
			log.Error(ctx, map[string]interface{}{
				"err":         err,
				"identity_id": identityID,
				"user_id":     user.ID,
			}, "failed to delete user %s with identity %s", user.ID, identityID)
			return jsonapi.JSONErrorResponse(ctx, errs.Wrapf(err, "linking identity to cluster is failed which triggers deletion of user with id %s with identity having id %s and failed", user.ID, identityID))
		}
		return jsonapi.JSONErrorResponse(ctx, errs.Wrapf(err, "failed to link identity with id %s to cluster having url %s", identityID, clusterURL))
	}

	// finally, if all works, we create a user in WIT too.
	err = c.app.WITService().CreateUser(ctx.Context, identity, identityID.String())
	if err != nil {
		log.Error(ctx, map[string]interface{}{
			"err":      err,
			"username": identity.Username,
		}, "failed to create user in WIT")
		// Not a blocker. Log the error and proceed.
	}

	return ctx.OK(ConvertToAppUser(ctx.RequestData, user, identity, true))
}
1310252
func (m *UserManager) CreateSuperuser(email, first, last, clear string) (User, error) {
	return m.create(email, first, last, clear, true)
}