// Create corresponds to the POST /users endpoint.
//
// Create a new user
772013
func (c *UsersClient) Create(ctx context.Context, createUser *CreateUser) (*User, error) {
	p := "/users"

	req, err := c.backend.NewRequest(http.MethodPost, p, nil, createUser)
	if err != nil {
		return nil, err
	}

	var resp User
	_, err = c.backend.Do(ctx, req, &resp, func(code int) error {
		return &Error{}
	})
	if err != nil {
		return nil, err
	}

	return &resp, nil
}
892433
func (auth *Auth) CreateUser(ctx context.Context, user *User) (string, error) {
	var err error
	var userID string

	if len(user.UserID) == 0 {
		userID, err = auth.createUserAutoID(ctx, user)
	} else {
		userID = user.UserID
		err = auth.createUserCustomID(ctx, user)
	}
	if err != nil {
		return "", err
	}
	return userID, nil
}
926227
func (s *userService) Create(userPassword string, user datamodels.User) (datamodels.User, error) {
	if user.ID > 0 || userPassword == "" || user.Firstname == "" || user.Username == "" {
		return datamodels.User{}, errors.New("unable to create this user")
	}

	hashed, err := datamodels.GeneratePassword(userPassword)
	if err != nil {
		return datamodels.User{}, err
	}
	user.HashedPassword = hashed

	return s.repo.InsertOrUpdate(user)
}
1018192
func (endpoint *HostComputeEndpoint) Create() (*HostComputeEndpoint, error) {
	logrus.Debugf("hcn::HostComputeEndpoint::Create id=%s", endpoint.Id)

	if endpoint.HostComputeNamespace != "" {
		return nil, errors.New("endpoint create error, endpoint json HostComputeNamespace is read only and should not be set")
	}

	jsonString, err := json.Marshal(endpoint)
	if err != nil {
		return nil, err
	}

	logrus.Debugf("hcn::HostComputeEndpoint::Create JSON: %s", jsonString)
	endpoint, hcnErr := createEndpoint(endpoint.HostComputeNetwork, string(jsonString))
	if hcnErr != nil {
		return nil, hcnErr
	}
	return endpoint, nil
}
510896
func (r *REST) Create(ctx context.Context, obj runtime.Object, _ rest.ValidateObjectFunc, options *metav1.CreateOptions) (runtime.Object, error) {
	resourceAccessReview, ok := obj.(*authorizationapi.ResourceAccessReview)
	if !ok {
		return nil, kapierrors.NewBadRequest(fmt.Sprintf("not a resourceAccessReview: %#v", obj))
	}
	if errs := authorizationvalidation.ValidateResourceAccessReview(resourceAccessReview); len(errs) > 0 {
		return nil, kapierrors.NewInvalid(authorization.Kind(resourceAccessReview.Kind), "", errs)
	}

	user, ok := apirequest.UserFrom(ctx)
	if !ok {
		return nil, kapierrors.NewInternalError(errors.New("missing user on request"))
	}

	// if a namespace is present on the request, then the namespace on the on the RAR is overwritten.
	// This is to support backwards compatibility.  To have gotten here in this state, it means that
	// the authorizer decided that a user could run an RAR against this namespace
	if namespace := apirequest.NamespaceValue(ctx); len(namespace) > 0 {
		resourceAccessReview.Action.Namespace = namespace

	} else if err := r.isAllowed(user, resourceAccessReview); err != nil {
		// this check is mutually exclusive to the condition above.  localSAR and localRAR both clear the namespace before delegating their calls
		// We only need to check if the RAR is allowed **again** if the authorizer didn't already approve the request for a legacy call.
		return nil, err
	}

	attributes := util.ToDefaultAuthorizationAttributes(nil, resourceAccessReview.Action.Namespace, resourceAccessReview.Action)
	subjects, err := r.subjectLocator.AllowedSubjects(attributes)
	users, groups := authorizationutil.RBACSubjectsToUsersAndGroups(subjects, attributes.GetNamespace())

	response := &authorizationapi.ResourceAccessReviewResponse{
		Namespace: resourceAccessReview.Action.Namespace,
		Users:     sets.NewString(users...),
		Groups:    sets.NewString(groups...),
	}
	if err != nil {
		response.EvaluationError = err.Error()
	}

	return response, nil
}
1183791
func (m *UserManager) Create(email, first, last, clear string) (User, error) {
	return m.create(email, first, last, clear, false)
}
279287
func (el *EndpointsLock) Create(ler LeaderElectionRecord) error {
	recordBytes, err := json.Marshal(ler)
	if err != nil {
		return err
	}
	el.e, err = el.Client.Endpoints(el.EndpointsMeta.Namespace).Create(&v1.Endpoints{
		ObjectMeta: metav1.ObjectMeta{
			Name:      el.EndpointsMeta.Name,
			Namespace: el.EndpointsMeta.Namespace,
			Annotations: map[string]string{
				LeaderElectionRecordAnnotationKey: string(recordBytes),
			},
		},
	})
	return err
}
607987
func (s *Service) CreateUser(ctx context.Context, u *influxdb.User) error {
	return s.kv.Update(ctx, func(tx Tx) error {
		return s.createUser(ctx, tx, u)
	})
}
350868
func NewCreateUser(ctx *middleware.Context, handler CreateUserHandler) *CreateUser {
	return &CreateUser{Context: ctx, Handler: handler}
}
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))
}
700067
func (r *REST) Create(ctx context.Context, obj runtime.Object, _ rest.ValidateObjectFunc, options *metav1.CreateOptions) (runtime.Object, error) {
	subjectAccessReview, ok := obj.(*authorizationapi.SubjectAccessReview)
	if !ok {
		return nil, kapierrors.NewBadRequest(fmt.Sprintf("not a subjectAccessReview: %#v", obj))
	}
	if errs := authorizationvalidation.ValidateSubjectAccessReview(subjectAccessReview); len(errs) > 0 {
		return nil, kapierrors.NewInvalid(authorization.Kind(subjectAccessReview.Kind), "", errs)
	}

	requestingUser, ok := apirequest.UserFrom(ctx)
	if !ok {
		return nil, kapierrors.NewInternalError(errors.New("missing user on request"))
	}

	// if a namespace is present on the request, then the namespace on the on the SAR is overwritten.
	// This is to support backwards compatibility.  To have gotten here in this state, it means that
	// the authorizer decided that a user could run an SAR against this namespace
	if namespace := apirequest.NamespaceValue(ctx); len(namespace) > 0 {
		subjectAccessReview.Action.Namespace = namespace

	} else if err := r.isAllowed(requestingUser, subjectAccessReview); err != nil {
		// this check is mutually exclusive to the condition above.  localSAR and localRAR both clear the namespace before delegating their calls
		// We only need to check if the SAR is allowed **again** if the authorizer didn't already approve the request for a legacy call.
		return nil, err
	}

	var userToCheck *user.DefaultInfo
	if (len(subjectAccessReview.User) == 0) && (len(subjectAccessReview.Groups) == 0) {
		// if no user or group was specified, use the info from the context
		ctxUser, exists := apirequest.UserFrom(ctx)
		if !exists {
			return nil, kapierrors.NewBadRequest("user missing from context")
		}
		// make a copy, we don't want to risk changing the original
		newExtra := map[string][]string{}
		for k, v := range ctxUser.GetExtra() {
			if v == nil {
				newExtra[k] = nil
				continue
			}
			newSlice := make([]string, len(v))
			copy(newSlice, v)
			newExtra[k] = newSlice
		}

		userToCheck = &user.DefaultInfo{
			Name:   ctxUser.GetName(),
			Groups: ctxUser.GetGroups(),
			UID:    ctxUser.GetUID(),
			Extra:  newExtra,
		}

	} else {
		userToCheck = &user.DefaultInfo{
			Name:   subjectAccessReview.User,
			Groups: subjectAccessReview.Groups.List(),
			Extra:  map[string][]string{},
		}
	}

	switch {
	case subjectAccessReview.Scopes == nil:
		// leave the scopes alone.  on a self-sar, this means "use incoming request", on regular-sar it means, "use no scope restrictions"
	case len(subjectAccessReview.Scopes) == 0:
		// this always means "use no scope restrictions", so delete them
		delete(userToCheck.Extra, authorizationapi.ScopesKey)

	case len(subjectAccessReview.Scopes) > 0:
		// this always means, "use these scope restrictions", so force the value
		userToCheck.Extra[authorizationapi.ScopesKey] = subjectAccessReview.Scopes
	}

	attributes := util.ToDefaultAuthorizationAttributes(userToCheck, subjectAccessReview.Action.Namespace, subjectAccessReview.Action)
	authorized, reason, err := r.authorizer.Authorize(attributes)
	response := &authorizationapi.SubjectAccessReviewResponse{
		Namespace: subjectAccessReview.Action.Namespace,
		Allowed:   authorized == kauthorizer.DecisionAllow,
		Reason:    reason,
	}
	if err != nil {
		response.EvaluationError = err.Error()
	}

	return response, nil
}
1361142
func (c *Client) EndpointCreate(ep *models.EndpointChangeRequest) error {
	id := pkgEndpointID.NewCiliumID(ep.ID)
	params := endpoint.NewPutEndpointIDParams().WithID(id).WithEndpoint(ep).WithTimeout(api.ClientTimeout)
	_, err := c.Endpoint.PutEndpointID(params)
	return Hint(err)
}
1145545
func (c *identities) Create(identity *user.Identity) (result *user.Identity, err error) {
	result = &user.Identity{}
	err = c.client.Post().
		Resource("identities").
		Body(identity).
		Do().
		Into(result)
	return
}
1138491
func (c *middlewares) Create(middleware *v1alpha1.Middleware) (result *v1alpha1.Middleware, err error) {
	result = &v1alpha1.Middleware{}
	err = c.client.Post().
		Namespace(c.ns).
		Resource("middlewares").
		Body(middleware).
		Do().
		Into(result)
	return
}
21616
func (e *ApiClientService) Create(clientName string, admin bool) (data *ApiClientCreateResult, err error) {
	post := ApiNewClient{
		Name:  clientName,
		Admin: admin,
	}
	body, err := JSONReader(post)
	if err != nil {
		return
	}

	err = e.client.magicRequestDecoder("POST", "clients", body, &data)
	return
}
1071521
func (u *UsersClient) Create(ctx context.Context, userObj *envelope.User,
	signup apitypes.Signup) (envelope.UserInf, error) {

	v := &url.Values{}
	if signup.InviteCode != "" {
		v.Set("code", signup.InviteCode)
	}
	if signup.OrgInvite && signup.OrgName != "" {
		v.Set("org", signup.OrgName)
	}
	if signup.Email != "" {
		v.Set("email", signup.Email)
	}

	e := envelope.Unsigned{}
	err := u.client.RoundTrip(ctx, "POST", "/users", v, &userObj, &e)
	if err != nil {
		return nil, err
	}

	return envelope.ConvertUser(&e)
}
1120089
func (c *FakeEndpoints) Create(endpoints *corev1.Endpoints) (result *corev1.Endpoints, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewCreateAction(endpointsResource, c.ns, endpoints), &corev1.Endpoints{})

	if obj == nil {
		return nil, err
	}
	return obj.(*corev1.Endpoints), err
}