Map roles for user in database

        Args:
            user (User): User to add roles to
            roles ([Role]): List of roles to add

        Returns:
            None
491838
def add_role(user, roles):
        
        def _add_role(role):
            user_role = UserRole()
            user_role.user_id = user.user_id
            user_role.role_id = role.role_id
            db.session.add(user_role)
            db.session.commit()
        [_add_role(role) for role in roles]
1274224
def add_database_user(self, new_username, new_password, permissions=None):
        
        url = "db/{0}/users".format(self._database)

        data = {
            'name': new_username,
            'password': new_password
        }

        if permissions:
            try:
                data['readFrom'], data['writeTo'] = permissions
            except (ValueError, TypeError):
                raise TypeError(
                    "'permissions' must be (readFrom, writeTo) tuple"
                )

        self.request(
            url=url,
            method='POST',
            data=data,
            expected_response_code=200
        )

        return True
1335570
def add_user(
        self,
        username,
        first_name,
        last_name,
        email,
        role,
        password="",
        hashed_password="",
    ):
        
        try:
            user = self.user_model()
            user.first_name = first_name
            user.last_name = last_name
            user.username = username
            user.email = email
            user.active = True
            user.roles.append(role)
            if hashed_password:
                user.password = hashed_password
            else:
                user.password = generate_password_hash(password)
            self.get_session.add(user)
            self.get_session.commit()
            log.info(c.LOGMSG_INF_SEC_ADD_USER.format(username))
            return user
        except Exception as e:
            log.error(c.LOGMSG_ERR_SEC_ADD_USER.format(str(e)))
            self.get_session.rollback()
            return False
130244
def add_roles(self, list_of_roles):
        
        for role in list_of_roles:
            role_node = role.get_node()
            self.node.append(role_node)
385405
def get_user_roles(self, user):
        
        return self.service.get_user_roles(
            user, self.url_prefix, self.auth, self.session, self.session_send_opts)
106928
def update_role(role,**kwargs):
    
    #check_perm(kwargs.get('user_id'), 'edit_role')
    try:
        role_i = db.DBSession.query(Role).filter(Role.id==role.id).one()
        role_i.name = role.name
        role_i.code = role.code
    except NoResultFound:
        raise ResourceNotFoundError("Role (role_id=%s) does not exist"%(role.id))

    for perm in role.permissions:
        _get_perm(perm.id)
        roleperm_i = RolePerm(role_id=role.id,
                              perm_id=perm.id
                              )

        db.DBSession.add(roleperm_i)

    for user in role.users:
        _get_user(user.id)
        roleuser_i = RoleUser(user_id=user.id,
                                         perm_id=perm.id
                                        )

        db.DBSession.add(roleuser_i)

    db.DBSession.flush()
    return role_i
961345
def update_user(resource_root, user):
  
  return call(resource_root.put,
      '%s/%s' % (USERS_PATH, user.name), ApiUser, data=user)
835926
def role_get(user):
    '''
    
    '''
    user_roles = []

    ## read user_attr file (user:qualifier:res1:res2:attr)
    with salt.utils.files.fopen('/etc/user_attr', 'r') as user_attr:
        for role in user_attr:
            role = salt.utils.stringutils.to_unicode(role)
            role = role.strip().strip().split(':')

            # skip comments and non complaint lines
            if len(role) != 5:
                continue

            # skip other users
            if role[0] != user:
                continue

            # parse attr
            attrs = {}
            for attr in role[4].strip().split(';'):
                attr_key, attr_val = attr.strip().split('=')
                if attr_key in ['auths', 'profiles', 'roles']:
                    attrs[attr_key] = attr_val.strip().split(',')
                else:
                    attrs[attr_key] = attr_val
            if 'roles' in attrs:
                user_roles.extend(attrs['roles'])

    return list(set(user_roles))
593676
def write_user(user):
    

    udata = {}

    for f in USER_FIELDS:
        udata[f] = getattr(user, f)

    for p in PERMISSIONS:
        udata[p] = '1' if getattr(user, p) else '0'
    db.hmset('user:{0}'.format(user.uid), udata)
447037
def add_role(role, reason = nil)
      role_ids = role_id_array(role)

      if role_ids.count == 1
        API::Server.add_member_role(@bot.token, @server.id, @user.id, role_ids[0], reason)
      else
        old_role_ids = @roles.map(&:id)
        new_role_ids = (old_role_ids + role_ids).uniq
        API::Server.update_member(@bot.token, @server.id, @user.id, roles: new_role_ids, reason: reason)
      end
    end
113743
def build_user_roles(params)
      @roles.each do |role|
        role = role.tableize.singularize
        klass_name = "Roles::#{role.classify}"
        if (params[:user][:user_roles][role] == "1") &&
           !@user.user_roles.map(&:role_class_name).include?(klass_name)
          @user.user_roles.build(role_class_name: klass_name)
        elsif (params[:user][:user_roles][role] == "0") &&
              @user.user_roles.map(&:role_class_name).include?(klass_name)
          user_role = @user.user_roles.find_by_role_class_name(klass_name)
          user_role.destroy
        end
      end
    end
856187
def change_user_role(self):
        

        # Get chosen role_key from user form.
        role_key = self.input['form']['role_options']
        # Assign chosen switch role key to user's last_login_role_key field
        self.current.user.last_login_role_key = role_key
        self.current.user.save()
        auth = AuthBackend(self.current)
        # According to user's new role, user's session set again.
        auth.set_user(self.current.user)
        # Dashboard is reloaded according to user's new role.
        self.current.output['cmd'] = 'reload'
796632
async def AddUser(self, users):
        '''
        
        '''
        # map input types to rpc msg
        _params = dict()
        msg = dict(type='UserManager',
                   request='AddUser',
                   version=2,
                   params=_params)
        _params['users'] = users
        reply = await self.rpc(msg)
        return reply
1009777
def role_assignment_list(auth=None, **kwargs):
    '''
    
    '''
    cloud = get_operator_cloud(auth)
    kwargs = _clean_kwargs(**kwargs)
    return cloud.list_role_assignments(**kwargs)
512601
def add_role_to_user(user, role):
    
    user = _query_to_user(user)
    role = _query_to_role(role)
    if click.confirm(f'Are you sure you want to add {role!r} to {user!r}?'):
        user.roles.append(role)
        user_manager.save(user, commit=True)
        click.echo(f'Successfully added {role!r} to {user!r}')
    else:
        click.echo('Cancelled.')
686576
def roles(self):
        """"""
        roles = []
        for ur in self.roleusers:
            roles.append(ur.role)
        return set(roles)
5124
def role_add(self, role=None, login=None, envs=[], query='/roles/'):
        
        data = {'login': self.args.login}
        juicer.utils.Log.log_debug(
                "Add Role '%s' to '%s'", role, login)

        for env in self.args.envs:
            if not juicer.utils.role_exists_p(role, self.connectors[env]):
                juicer.utils.Log.log_info("role `%s` doesn't exist in %s... skipping!",
                                          (role, env))
                continue
            elif not juicer.utils.user_exists_p(login, self.connectors[env]):
                juicer.utils.Log.log_info("user `%s` doesn't exist in %s... skipping!",
                                          (login, env))
            else:
                url = "%s%s/users/" % (query, role)
                _r = self.connectors[env].post(url, data)
                if _r.status_code == Constants.PULP_POST_OK:
                    juicer.utils.Log.log_info("added user `%s` to role `%s` in %s",
                                              (login, role, env))
                else:
                    _r.raise_for_status()
        return True