// Creates a role
348169
func (s *RoleService) CreateRole(p *CreateRoleParams) (*CreateRoleResponse, error) {
	resp, err := s.cs.newRequest("createRole", p.toURLValues())
	if err != nil {
		return nil, err
	}

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

	return &r, nil
}
375418
func (b *backend) pathRoleCreateUpdate(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
	roleName := data.Get("role_name").(string)
	if roleName == "" {
		return logical.ErrorResponse("missing role_name"), nil
	}

	lock := b.roleLock(roleName)
	lock.Lock()
	defer lock.Unlock()

	// Check if the role already exists
	role, err := b.roleEntry(ctx, req.Storage, roleName)
	if err != nil {
		return nil, err
	}

	// Create a new entry object if this is a CreateOperation
	switch {
	case role == nil && req.Operation == logical.CreateOperation:
		hmacKey, err := uuid.GenerateUUID()
		if err != nil {
			return nil, errwrap.Wrapf("failed to create role_id: {{err}}", err)
		}
		role = &roleStorageEntry{
			name:              strings.ToLower(roleName),
			HMACKey:           hmacKey,
			LowerCaseRoleName: true,
		}
	case role == nil:
		return logical.ErrorResponse(fmt.Sprintf("role name %q doesn't exist", roleName)), logical.ErrUnsupportedPath
	}

	localSecretIDsRaw, ok := data.GetOk("local_secret_ids")
	if ok {
		switch {
		case req.Operation == logical.CreateOperation:
			localSecretIDs := localSecretIDsRaw.(bool)
			if localSecretIDs {
				role.SecretIDPrefix = secretIDLocalPrefix
			}
		default:
			return logical.ErrorResponse("local_secret_ids can only be modified during role creation"), nil
		}
	}

	previousRoleID := role.RoleID
	if roleIDRaw, ok := data.GetOk("role_id"); ok {
		role.RoleID = roleIDRaw.(string)
	} else if req.Operation == logical.CreateOperation {
		roleID, err := uuid.GenerateUUID()
		if err != nil {
			return nil, errwrap.Wrapf("failed to generate role_id: {{err}}", err)
		}
		role.RoleID = roleID
	}
	if role.RoleID == "" {
		return logical.ErrorResponse("invalid role_id supplied, or failed to generate a role_id"), nil
	}

	if bindSecretIDRaw, ok := data.GetOk("bind_secret_id"); ok {
		role.BindSecretID = bindSecretIDRaw.(bool)
	} else if req.Operation == logical.CreateOperation {
		role.BindSecretID = data.Get("bind_secret_id").(bool)
	}

	if boundCIDRListRaw, ok := data.GetFirst("secret_id_bound_cidrs", "bound_cidr_list"); ok {
		role.SecretIDBoundCIDRs = boundCIDRListRaw.([]string)
	}

	if len(role.SecretIDBoundCIDRs) != 0 {
		valid, err := cidrutil.ValidateCIDRListSlice(role.SecretIDBoundCIDRs)
		if err != nil {
			return nil, errwrap.Wrapf("failed to validate CIDR blocks: {{err}}", err)
		}
		if !valid {
			return logical.ErrorResponse("invalid CIDR blocks"), nil
		}
	}

	if boundCIDRListRaw, ok := data.GetOk("token_bound_cidrs"); ok {
		role.TokenBoundCIDRs = boundCIDRListRaw.([]string)
	}

	if len(role.TokenBoundCIDRs) != 0 {
		valid, err := cidrutil.ValidateCIDRListSlice(role.TokenBoundCIDRs)
		if err != nil {
			return nil, errwrap.Wrapf("failed to validate CIDR blocks: {{err}}", err)
		}
		if !valid {
			return logical.ErrorResponse("invalid CIDR blocks"), nil
		}
	}

	if policiesRaw, ok := data.GetOk("policies"); ok {
		role.Policies = policyutil.ParsePolicies(policiesRaw)
	} else if req.Operation == logical.CreateOperation {
		role.Policies = policyutil.ParsePolicies(data.Get("policies"))
	}

	periodRaw, ok := data.GetOk("period")
	if ok {
		role.Period = time.Second * time.Duration(periodRaw.(int))
	} else if req.Operation == logical.CreateOperation {
		role.Period = time.Second * time.Duration(data.Get("period").(int))
	}
	if role.Period > b.System().MaxLeaseTTL() {
		return logical.ErrorResponse(fmt.Sprintf("period of %q is greater than the backend's maximum lease TTL of %q", role.Period.String(), b.System().MaxLeaseTTL().String())), nil
	}

	if secretIDNumUsesRaw, ok := data.GetOk("secret_id_num_uses"); ok {
		role.SecretIDNumUses = secretIDNumUsesRaw.(int)
	} else if req.Operation == logical.CreateOperation {
		role.SecretIDNumUses = data.Get("secret_id_num_uses").(int)
	}
	if role.SecretIDNumUses < 0 {
		return logical.ErrorResponse("secret_id_num_uses cannot be negative"), nil
	}

	if secretIDTTLRaw, ok := data.GetOk("secret_id_ttl"); ok {
		role.SecretIDTTL = time.Second * time.Duration(secretIDTTLRaw.(int))
	} else if req.Operation == logical.CreateOperation {
		role.SecretIDTTL = time.Second * time.Duration(data.Get("secret_id_ttl").(int))
	}

	if tokenNumUsesRaw, ok := data.GetOk("token_num_uses"); ok {
		role.TokenNumUses = tokenNumUsesRaw.(int)
	} else if req.Operation == logical.CreateOperation {
		role.TokenNumUses = data.Get("token_num_uses").(int)
	}
	if role.TokenNumUses < 0 {
		return logical.ErrorResponse("token_num_uses cannot be negative"), nil
	}

	if tokenTTLRaw, ok := data.GetOk("token_ttl"); ok {
		role.TokenTTL = time.Second * time.Duration(tokenTTLRaw.(int))
	} else if req.Operation == logical.CreateOperation {
		role.TokenTTL = time.Second * time.Duration(data.Get("token_ttl").(int))
	}

	if tokenMaxTTLRaw, ok := data.GetOk("token_max_ttl"); ok {
		role.TokenMaxTTL = time.Second * time.Duration(tokenMaxTTLRaw.(int))
	} else if req.Operation == logical.CreateOperation {
		role.TokenMaxTTL = time.Second * time.Duration(data.Get("token_max_ttl").(int))
	}

	tokenType := role.TokenType
	if tokenTypeRaw, ok := data.GetOk("token_type"); ok {
		tokenType = tokenTypeRaw.(string)
		switch tokenType {
		case "":
			tokenType = "default"
		case "service", "batch", "default":
		default:
			return logical.ErrorResponse(fmt.Sprintf("invalid 'token_type' value %q", tokenType)), nil
		}
	} else if req.Operation == logical.CreateOperation {
		tokenType = data.Get("token_type").(string)
	}
	role.TokenType = tokenType

	if role.TokenType == "batch" {
		if role.Period != 0 {
			return logical.ErrorResponse("'token_type' cannot be 'batch' when role is set to generate periodic tokens"), nil
		}
		if role.TokenNumUses != 0 {
			return logical.ErrorResponse("'token_type' cannot be 'batch' when role is set to generate tokens with limited use count"), nil
		}
	}

	// Check that the TokenTTL value provided is less than the TokenMaxTTL.
	// Sanitizing the TTL and MaxTTL is not required now and can be performed
	// at credential issue time.
	if role.TokenMaxTTL > time.Duration(0) && role.TokenTTL > role.TokenMaxTTL {
		return logical.ErrorResponse("token_ttl should not be greater than token_max_ttl"), nil
	}

	var resp *logical.Response
	if role.TokenMaxTTL > b.System().MaxLeaseTTL() {
		resp = &logical.Response{}
		resp.AddWarning("token_max_ttl is greater than the backend mount's maximum TTL value; issued tokens' max TTL value will be truncated")
	}

	// Store the entry.
	return resp, b.setRoleEntry(ctx, req.Storage, role.name, role, previousRoleID)
}
893018
func (db *Database) AddRole(role string, isAdmin bool) error {
	sec, err := db.GetSecurity()
	if err != nil {
		return err
	}
	roles := func() *[]string {
		if isAdmin {
			return &sec.Admins.Roles
		} else {
			return &sec.Members.Roles
		}
	}
	//Make sure the role isn't already there (couchdb will let you add it twice :/ )
	for _, r := range *roles() {
		if r == role {
			//already there, just return
			return nil
		}
	}
	rolesarr := roles()
	*rolesarr = append(*rolesarr, role)
	return db.SaveSecurity(*sec)
}
730682
func (r *SdkRoleManager) Create(
	ctx context.Context,
	req *api.SdkRoleCreateRequest,
) (*api.SdkRoleCreateResponse, error) {
	if req.GetRole() == nil {
		return nil, status.Error(codes.InvalidArgument, "Must supply a role")
	} else if len(req.GetRole().GetName()) == 0 {
		return nil, status.Error(codes.InvalidArgument, "Must supply a name for the role")
	} else if err := r.validateRole(req.GetRole()); err != nil {
		return nil, err
	}

	// Determine if there is collision with default roles
	if _, ok := defaultRoles[req.GetRole().GetName()]; ok {
		return nil, status.Errorf(
			codes.InvalidArgument,
			"Name %s already used by system role", req.GetRole().GetName())
	}

	// Save value in kvdb
	_, err := r.kv.Create(prefixWithName(req.GetRole().GetName()), req.GetRole(), 0)
	if err == kvdb.ErrExist {
		// Idempotency check.
		// Check that the new rules are the same.
		oldrole, err := r.Inspect(ctx, &api.SdkRoleInspectRequest{
			Name: req.GetRole().GetName(),
		})
		if err != nil {
			return nil, err
		}
		if !reflect.DeepEqual(oldrole.GetRole(), req.GetRole()) {
			return nil, status.Error(
				codes.AlreadyExists,
				"Existing role differs from requested role")
		}
	} else if err != nil {
		return nil, status.Errorf(codes.Internal, "Failed to save role: %v", err)
	}

	return &api.SdkRoleCreateResponse{
		Role: req.GetRole(),
	}, nil
}
478983
func SaveRole(directory, filename, section string, roleUUID string) error {
	kfile := directory + filename

	config, err := ini.Load(kfile)

	if err != nil {
		os.Mkdir(directory, 0755)
		config = ini.Empty()
		config.NewSection(section)
	}

	config.Section(section).NewKey("role_uuid", roleUUID)
	return config.SaveTo(kfile)
}
627157
func (m *GormIdentityRoleRepository) Create(ctx context.Context, u *IdentityRole) error {
	defer goa.MeasureSince([]string{"goa", "db", "identity_role", "create"}, time.Now())
	if u.IdentityRoleID == uuid.Nil {
		u.IdentityRoleID = uuid.NewV4()
	}
	err := m.db.Create(u).Error
	if err != nil {
		log.Error(ctx, map[string]interface{}{
			"identity_role_id": u.IdentityRoleID,
			"err":              err,
		}, "unable to create the identity role")
		if gormsupport.IsUniqueViolation(err, "uq_identity_role_identity_role_resource") {
			return errs.WithStack(errors.NewDataConflictError(err.Error()))
		}
		if gormsupport.IsForeignKeyViolation(err, "identity_role_identity_id_fkey") {
			return errs.WithStack(errors.NewNotFoundError("identity", u.IdentityID.String()))
		}
		if gormsupport.IsForeignKeyViolation(err, "identity_role_resource_id_fkey") {
			return errs.WithStack(errors.NewNotFoundError("resource", u.ResourceID))
		}
		if gormsupport.IsForeignKeyViolation(err, "identity_role_role_id_fkey") {
			return errs.WithStack(errors.NewNotFoundError("role", u.RoleID.String()))
		}
		return errs.WithStack(err)
	}

	err = m.FlagPrivilegeCacheStaleForIdentityRoleChange(ctx, u.IdentityID, u.ResourceID)
	if err != nil {
		log.Error(ctx, map[string]interface{}{
			"identity_role_id": u.IdentityRoleID,
			"err":              err,
		}, "error notifying privilege cache when creating identity role")
	}

	log.Debug(ctx, map[string]interface{}{
		"identity_role_id": u.IdentityRoleID,
	}, "Identity Role created!")
	return nil
}
921444
func CreateClusterRole(
	clientset kubernetes.Interface,
	clusterRoleName string,
	rules []rbacv1.PolicyRule,
) error {
	clusterRole := rbacv1.ClusterRole{
		TypeMeta: metav1.TypeMeta{
			APIVersion: "rbac.authorization.k8s.io/v1",
			Kind:       "ClusterRole",
		},
		ObjectMeta: metav1.ObjectMeta{
			Name: clusterRoleName,
		},
		Rules: rules,
	}
	crclient := clientset.RbacV1().ClusterRoles()
	_, err := crclient.Create(&clusterRole)
	if err != nil {
		if !apierr.IsAlreadyExists(err) {
			return fmt.Errorf("Failed to create ClusterRole %q: %v", clusterRoleName, err)
		}
		_, err = crclient.Update(&clusterRole)
		if err != nil {
			return fmt.Errorf("Failed to update ClusterRole %q: %v", clusterRoleName, err)
		}
		log.Infof("ClusterRole %q updated", clusterRoleName)
	} else {
		log.Infof("ClusterRole %q created", clusterRoleName)
	}
	return nil
}
225734
func (c *FakeClusterRoles) Create(clusterRole *v1alpha1.ClusterRole) (result *v1alpha1.ClusterRole, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewRootCreateAction(clusterrolesResource, clusterRole), &v1alpha1.ClusterRole{})
	if obj == nil {
		return nil, err
	}
	return obj.(*v1alpha1.ClusterRole), err
}
1372180
func (e *RoleService) Create(role *Role) (data *RoleCreateResult, err error) {
	// err = e.client.magicRequestDecoder("POST", "roles", role, &data)
	body, err := JSONReader(role)
	if err != nil {
		return
	}

	// BUG(fujiN): This is now both a *response* decoder and handles upload.. gettin smelly
	err = e.client.magicRequestDecoder(
		"POST",
		"roles",
		body,
		&data,
	)

	return
}
104029
func CreateOrUpdateRoleBinding(client clientset.Interface, roleBinding *rbac.RoleBinding) error {
	if _, err := client.RbacV1().RoleBindings(roleBinding.ObjectMeta.Namespace).Create(roleBinding); err != nil {
		if !apierrors.IsAlreadyExists(err) {
			return errors.Wrap(err, "unable to create RBAC rolebinding")
		}

		if _, err := client.RbacV1().RoleBindings(roleBinding.ObjectMeta.Namespace).Update(roleBinding); err != nil {
			return errors.Wrap(err, "unable to update RBAC rolebinding")
		}
	}
	return nil
}
422616
func (s *RoleService) NewCreateRolePermissionParams(permission string, roleid string, rule string) *CreateRolePermissionParams {
	p := &CreateRolePermissionParams{}
	p.p = make(map[string]interface{})
	p.p["permission"] = permission
	p.p["roleid"] = roleid
	p.p["rule"] = rule
	return p
}
561400
func (trust *NotarySigner) Create(role data.RoleName, gun data.GUN, algorithm string) (data.PublicKey, error) {
	publicKey, err := trust.kmClient.CreateKey(context.Background(),
		&pb.CreateKeyRequest{Algorithm: algorithm, Role: role.String(), Gun: gun.String()})
	if err != nil {
		return nil, err
	}
	public := data.NewPublicKey(publicKey.KeyInfo.Algorithm.Algorithm, publicKey.PublicKey)
	return public, nil
}
1017316
func (m *MetaClient) Role(ctx context.Context, name string) (*Role, error) {
	roles, err := m.Roles(ctx, &name)
	if err != nil {
		return nil, err
	}
	for _, role := range roles.Roles {
		return &role, nil
	}
	return nil, fmt.Errorf("no role found")
}
809878
func NewRoleList(roles []string) []RoleName {
	var roleNames []RoleName
	for _, role := range roles {
		roleNames = append(roleNames, RoleName(role))
	}
	return roleNames
}
841729
func (a *Auth) UsersWithRole(role string) (users []User) {
	for _, user := range a.robot.Users.All() {
		if a.HasRole(user.ID, role) {
			users = append(users, user)
		}
	}
	return
}
836110
func (s *RoleService) NewListRolesParams() *ListRolesParams {
	p := &ListRolesParams{}
	p.p = make(map[string]interface{})
	return p
}
525731
func (a *AuthWithRoles) UpsertRole(role services.Role) error {
	if err := a.action(defaults.Namespace, services.KindRole, services.VerbCreate); err != nil {
		return trace.Wrap(err)
	}
	if err := a.action(defaults.Namespace, services.KindRole, services.VerbUpdate); err != nil {
		return trace.Wrap(err)
	}
	return a.authServer.UpsertRole(role)
}