Add a given role to the given user id

@param int    $userId
@param string $roleName
4206
public function addRoleForUser($userId, $roleName)
    {
        $roleIdExpression = new Expression(
            '(SELECT `id` from `user_roles` WHERE `name` = ?)',
            $roleName
        );

        $query = $this->getSqlObject()
            ->insert()
            ->values([
                'user_id' => $userId,
                'role_id' => $roleIdExpression,
            ]);

        $this->execute($query);
    }
87079
public function createMembership($userId, $roles = [Membership::ROLE_READ], $organization = '')
    {
        if (\is_string($roles)) {
            $roles = [$roles];
        }
        $roles = array_map(function ($role) {
            return strtolower($role);
        }, $roles);
        $contents = $this
            ->call('PUT', implode('/', [self::ORGANIZATION_RESOURCE, $this->getOrganizationName($organization), 'memberships', $userId]), ['json' => [
                'roles' => $roles,
            ]])
            ->getBody()
            ->getContents();

        // get the membership, if it already exists
        if (empty($contents)) {
            return $this->getMembership($userId, $this->getOrganizationName($organization));
        }

        return $this->getSingleMemberShipFromJsonResponse($contents);
    }
1067107
static public function create($groupId, $userId, $role)
    {
        $instance = new self();

        $instance->group_id = (int)$groupId;
        $instance->user_id = (int)$userId;
        $instance->role = (int)$role;

        return $instance;
    }
717137
public synchronized void addUserToRole(String userName, String roleName)
    {
        HashSet userSet = (HashSet)_roles.get(roleName);
        if (userSet==null)
        {
            userSet=new HashSet(11);
            _roles.put(roleName,userSet);
        }
        userSet.add(userName);
    }
556792
public function add($sourceId, $targetId, $roleId)
    {
        $request = (new RequestDescriptor())
            ->setUrl($this->buildUrl(self::IDP_ATTRIBUTIONS_API))
            ->setMethod('POST');

        $request->setBodyParams([
            'data' => json_encode([
                'source_id' => $sourceId,
                'target_id' => $targetId,
                'role_id' => $roleId,
            ])
        ]);

        try {
            $response = json_decode($this->send($request)->getBody(), true);
            return (count($response['added']) > 0 ? reset($response['added']) : null);
        } catch (\Exception $e) {
            $previous = $e->getPrevious();

            if ($previous instanceof BadResponseException) {
                $error = json_decode($previous->getResponse()->getBody(), true);

                throw new UserAttributionException($error['error'], $error['code'], $previous);
            }

            throw new UserAttributionException($e->getMessage(), $e->getCode(), $e->getPrevious());
        }
    }
875756
public function unassignRoleFromUser($userId, $roleId)
    {
        $user = $this->userService->loadUser($userId);
        $role = $this->roleService->loadRole($roleId);

        $this->roleService->unassignRoleFromUser($role, $user);

        $roleAssignments = $this->roleService->getRoleAssignmentsForUser($user);

        return new Values\RoleAssignmentList($roleAssignments, $user->id);
    }
1296202
public function addRoleByName(string $roleName)
    {
        if (!$this->user) {
            throw new UserRequiredException();
        }

        $this->compileUserRoles();

        if ($this->hasRoleWithName($roleName)) {
            return;
        }

        $role = $this->roleProvider->getRoleWithName($roleName);

        if (!$role) {
            throw new InvalidRoleException($roleName);
        }

        $this->user->addRole($role);
        $this->userRoles[] = $roleName;
        $this->userProvider->update($this->user);
    }
1191852
public function addRole(RoleInterface $role)
    {
        $this->roles->add($role);

        if ($role->hasUser($this) === false)
            $role->addUser($this);

        return $this;
    }
860729
def add_user_role(self, user, role_name):
        """"""

        # For SQL: user.roles is list of pointers to Role objects
        if isinstance(self.db_adapter, SQLDbAdapter):
            # user.roles is a list of Role IDs
            # Get or add role
            role = self.db_adapter.find_first_object(self.RoleClass, name=role_name)
            if not role:
                role = self.RoleClass(name=role_name)
                self.db_adapter.add_object(role)
            user.roles.append(role)

        # For others: user.roles is a list of role names
        else:
            # user.roles is a list of role names
            user.roles.append(role_name)
357
public static function add_contact(int $userid, int $contactid) {
        global $DB;

        $messagecontact = new \stdClass();
        $messagecontact->userid = $userid;
        $messagecontact->contactid = $contactid;
        $messagecontact->timecreated = time();
        $messagecontact->id = $DB->insert_record('message_contacts', $messagecontact);

        $eventparams = [
            'objectid' => $messagecontact->id,
            'userid' => $userid,
            'relateduserid' => $contactid,
            'context' => \context_user::instance($userid)
        ];
        $event = \core\event\message_contact_added::create($eventparams);
        $event->add_record_snapshot('message_contacts', $messagecontact);
        $event->trigger();
    }
1025158
public function assign_role_to_user($roleid, $userid) {
        require_capability('moodle/role:assign', $this->context);
        if (!array_key_exists($roleid, $this->get_assignable_roles())) {
            if (defined('AJAX_SCRIPT')) {
                throw new moodle_exception('invalidrole');
            }
            return false;
        }
        return role_assign($roleid, $userid, $this->context->id, '', NULL);
    }
567173
public function assign($userId, $name)
    {
        if ($this->searchRoleRecursive($this->roles, $name)) {
            $exists = $this->db->exists('rbac_user', ['user' => $userId, 'role' => $name]);
            if (!$exists) {
                return $this->db->insert('rbac_user', ['role' => $name, 'user' => $userId]);
            }
        }

        return false;
    }
134461
public function addRole($username, $role)
    {
        $user = $this->findUserByUsernameOrThrowException($username);
        if ($user->hasRole($role)) {
            return false;
        }

        $user->addRole($role);
        $this->userManager->updateUser($user);

        return true;
    }
778366
protected function createRole($roleName)
    {
        // No need to check is_null($role) as create() throwsException
        $role = $this->roleRepository->create($roleName);

        $this->info('Role created successfully');

        return $role;
    }
330104
public void addUser(String username, Role role) {
        if (StringUtils.isNullOrEmpty(username)) {
            throw new IllegalArgumentException("A username must be specified.");
        }

        if (role == null) {
            throw new IllegalArgumentException("A role must be specified.");
        }

        users.add(new User(username, role));
    }
769663
public function addContributors(Site $site, $userIdList)
    {
        $this->mergeUsersWithRole($site, $userIdList, Access::ROLE_CONTRIB);
    }
25529
public function addPolicy($roleId, Request $request)
    {
        $createStruct = $this->inputDispatcher->parse(
            new Message(
                array('Content-Type' => $request->headers->get('Content-Type')),
                $request->getContent()
            )
        );

        try {
            // First try to treat $roleId as a role draft ID.
            $role = $this->roleService->addPolicyByRoleDraft(
                $this->roleService->loadRoleDraft($roleId),
                $createStruct
            );
        } catch (NotFoundException $e) {
            // Then try to treat $roleId as a role ID.
            $role = $this->roleService->addPolicy(
                $this->roleService->loadRole($roleId),
                $createStruct
            );
        } catch (LimitationValidationException $e) {
            throw new BadRequestException($e->getMessage());
        }

        return new Values\CreatedPolicy(
            array(
                'policy' => $this->getLastAddedPolicy($role),
            )
        );
    }