// Create creates a user when requested using a service account token
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))
}
1183791
func (m *UserManager) Create(email, first, last, clear string) (User, error) {
	return m.create(email, first, last, clear, false)
}
492937
func (s *UserService) CreateUser(ctx context.Context, User *platform.User) error {
	return s.CreateUserFn(ctx, User)
}
1310260
func (m *GormTokenRepository) Create(ctx context.Context, token *Token) error {
	defer goa.MeasureSince([]string{"goa", "db", "token", "create"}, time.Now())

	// If no identifier has been specified for the new token, then generate one
	if token.TokenID == uuid.Nil {
		token.TokenID = uuid.NewV4()
	}

	err := m.db.Create(token).Error
	if err != nil {
		if gormsupport.IsUniqueViolation(err, "token_pkey") {
			return errors.NewDataConflictError(fmt.Sprintf("token with ID %s already exists", token.TokenID))
		}

		log.Error(ctx, map[string]interface{}{
			"token_id": token.TokenID,
			"err":      err,
		}, "unable to create the token")
		return errs.WithStack(err)
	}

	log.Info(ctx, map[string]interface{}{
		"token_id": token.TokenID,
	}, "Token created!")
	return 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)
}
1068676
func (s *ServicesClient) Create(ctx context.Context, orgID, projectID *identity.ID, name string) error {
	if orgID == nil || projectID == nil {
		return errors.New("invalid org or project")
	}

	serviceBody := primitive.Service{
		Name:      name,
		OrgID:     orgID,
		ProjectID: projectID,
	}

	ID, err := identity.NewMutable(&serviceBody)
	if err != nil {
		return err
	}

	service := envelope.Service{
		ID:      &ID,
		Version: 1,
		Body:    &serviceBody,
	}

	return s.client.RoundTrip(ctx, "POST", "/services", nil, service, nil)
}
1179445
func (s *UserService) Create(user *User) (*User, *Response, error) {
	apiEndpoint := "/rest/api/2/user"
	req, err := s.client.NewRequest("POST", apiEndpoint, user)
	if err != nil {
		return nil, nil, err
	}

	resp, err := s.client.Do(req, nil)
	if err != nil {
		return nil, resp, err
	}

	responseUser := new(User)
	defer resp.Body.Close()
	data, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		e := fmt.Errorf("Could not read the returned data")
		return nil, resp, NewJiraError(resp, e)
	}
	err = json.Unmarshal(data, responseUser)
	if err != nil {
		e := fmt.Errorf("Could not unmarshall the data into struct")
		return nil, resp, NewJiraError(resp, e)
	}
	return responseUser, resp, nil
}
632867
func (c *FakeIdentities) Create(identity *user.Identity) (result *user.Identity, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewRootCreateAction(identitiesResource, identity), &user.Identity{})
	if obj == nil {
		return nil, err
	}
	return obj.(*user.Identity), err
}
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
}
279352
func (s *AccountsService) Create(parms map[string]string) (*Account, *Response, error) {
	a := new(Account)
	resp, err := do(s.client, Params{parms: parms, u: "addclient"}, a)
	if err != nil {
		return nil, resp, err
	}
	return a, resp, err
}
115455
func (c *FakeUserIdentityMappings) Create(userIdentityMapping *user.UserIdentityMapping) (result *user.UserIdentityMapping, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewRootCreateAction(useridentitymappingsResource, userIdentityMapping), &user.UserIdentityMapping{})
	if obj == nil {
		return nil, err
	}
	return obj.(*user.UserIdentityMapping), err
}
1334956
func (cs ClientsService) Create(client Client, secret, token string) error {
	_, err := newNetworkClient(cs.config).MakeRequest(network.Request{
		Method:        "POST",
		Path:          "/oauth/clients",
		Authorization: network.NewTokenAuthorization(token),
		Body:          network.NewJSONRequestBody(client.toDocument(secret)),
		AcceptableStatusCodes: []int{http.StatusCreated},
	})
	if err != nil {
		return translateError(err)
	}

	return nil
}
230223
func (c *FakeSubjectAccessReviews) Create(subjectAccessReview *authorization.SubjectAccessReview) (result *authorization.SubjectAccessReviewResponse, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewRootCreateAction(subjectaccessreviewsResource, subjectAccessReview), &authorization.SubjectAccessReviewResponse{})
	if obj == nil {
		return nil, err
	}
	return obj.(*authorization.SubjectAccessReviewResponse), err
}
89341
func (a *AuthorizationsService) Create(params interface{}) (auth *Authorization, result *Result) {
	result = a.client.post(a.URL, params, &auth)
	return
}
1080562
func (s *Server) Create(ctx context.Context, q *SessionCreateRequest) (*SessionResponse, error) {
	if q.Token != "" {
		return nil, status.Errorf(codes.Unauthenticated, "token-based session creation no longer supported. please upgrade argocd cli to v0.7+")
	}
	if q.Username == "" || q.Password == "" {
		return nil, status.Errorf(codes.Unauthenticated, "no credentials supplied")
	}
	err := s.mgr.VerifyUsernamePassword(q.Username, q.Password)
	if err != nil {
		return nil, err
	}
	jwtToken, err := s.mgr.Create(q.Username, 0)
	if err != nil {
		return nil, err
	}
	return &SessionResponse{Token: jwtToken}, nil
}
1089817
func (c *FakeOAuthClientAuthorizations) Create(oAuthClientAuthorization *oauth.OAuthClientAuthorization) (result *oauth.OAuthClientAuthorization, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewRootCreateAction(oauthclientauthorizationsResource, oAuthClientAuthorization), &oauth.OAuthClientAuthorization{})
	if obj == nil {
		return nil, err
	}
	return obj.(*oauth.OAuthClientAuthorization), err
}
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
}