Adds a role for a user on a tenant.
513608
def add_tenant_user_role(request, project=None, user=None, role=None,
                         group=None, domain=None):
    """"""
    manager = keystoneclient(request, admin=True).roles
    if VERSIONS.active < 3:
        manager.add_user_role(user, role, project)
    else:
        manager.grant(role, user=user, project=project,
                      group=group, domain=domain)
899484
def with_tenant(tenant,&blk)
      orig = self.current_tenant
      begin
        self.current_tenant = tenant
        return blk.call(tenant)
      ensure
        self.current_tenant = orig
      end
    end
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]
138852
def add_role_to_user(self, user, role):
        
        user, role = self._prepare_role_modify_args(user, role)
        result = self.UserRole.select().where(
            self.UserRole.user == user.id,
            self.UserRole.role == role.id,
        )
        if result.count():
            return False
        else:
            self.put(self.UserRole.create(user=user.id, role=role.id))
            return True
1242207
def grant_role(self, principal, role, obj=None):
        """"""
        assert principal
        principal = unwrap(principal)
        session = object_session(obj) if obj is not None else db.session
        manager = self._current_user_manager(session=session)
        args = {
            "role": role,
            "object": obj,
            "anonymous": False,
            "user": None,
            "group": None,
        }

        if principal is AnonymousRole or (
            hasattr(principal, "is_anonymous") and principal.is_anonymous
        ):
            args["anonymous"] = True
        elif isinstance(principal, User):
            args["user"] = principal
        else:
            args["group"] = principal

        query = session.query(RoleAssignment)
        if query.filter_by(**args).limit(1).count():
            # role already granted, nothing to do
            return

        # same as above but in current, not yet flushed objects in session. We
        # cannot call flush() in grant_role() since this method may be called a
        # great number of times in the same transaction, and sqlalchemy limits
        # to 100 flushes before triggering a warning
        for ra in (
            o
            for models in (session.new, session.dirty)
            for o in models
            if isinstance(o, RoleAssignment)
        ):
            if all(getattr(ra, attr) == val for attr, val in args.items()):
                return

        ra = RoleAssignment(**args)
        session.add(ra)
        audit = SecurityAudit(manager=manager, op=SecurityAudit.GRANT, **args)
        if obj is not None:
            audit.object_id = obj.id
            audit.object_type = obj.entity_type
            object_name = ""
            for attr_name in ("name", "path", "__path_before_delete"):
                if hasattr(obj, attr_name):
                    object_name = getattr(obj, attr_name)
            audit.object_name = object_name

        session.add(audit)
        self._needs_flush()

        if hasattr(principal, "__roles_cache__"):
            del principal.__roles_cache__
785166
def update_role(u_name, newprivilege):
        '''
        
        '''
        entry = TabMember.update(
            role=newprivilege
        ).where(TabMember.user_name == u_name)
        try:
            entry.execute()
            return True
        except:
            return False
568763
def add_permission_role(self, role, perm_view):
        
        if perm_view not in role.permissions:
            try:
                role.permissions.append(perm_view)
                role.save()
                log.info(
                    c.LOGMSG_INF_SEC_ADD_PERMROLE.format(str(perm_view), role.name)
                )
            except Exception as e:
                log.error(c.LOGMSG_ERR_SEC_ADD_PERMROLE.format(str(e)))
968286
def set_user_role(new_user_id, role_id, **kwargs):
    
    #check_perm(kwargs.get('user_id'), 'edit_role')
    try:
        _get_user(new_user_id)
        role_i = _get_role(role_id)
        roleuser_i = RoleUser(user_id=new_user_id, role_id=role_id)
        role_i.roleusers.append(roleuser_i)
        db.DBSession.flush()
    except Exception as e: # Will occur if the foreign keys do not exist
        log.exception(e)
        raise ResourceNotFoundError("User or Role does not exist")

    return role_i
1035514
def add_permission_role(self, role, perm_view):
        
        if perm_view not in role.permissions:
            try:
                role.permissions.append(perm_view)
                self.get_session.merge(role)
                self.get_session.commit()
                log.info(
                    c.LOGMSG_INF_SEC_ADD_PERMROLE.format(str(perm_view), role.name)
                )
            except Exception as e:
                log.error(c.LOGMSG_ERR_SEC_ADD_PERMROLE.format(str(e)))
                self.get_session.rollback()
215827
public function addProperty($property, $editable, Role $role)
    {
        $propertyEntity = new ProfileProperty();
        $propertyEntity->setProperty($property);
        $propertyEntity->setIsEditable($editable);
        $propertyEntity->setRole($role);
        $this->om->persist($propertyEntity);
        $this->om->flush();
    }
1127422
def add_role_to_user(self, user, role):
        
        user, role = self._prepare_role_modify_args(user, role)
        if role not in user.roles:
            user.roles.append(role)
            self.put(user)
            return True
        return False
1063649
def update_tenant(self, tenant, name=None, description=None, enabled=True):
        
        tenant_id = utils.get_id(tenant)
        data = {"tenant": {
                "enabled": enabled,
                }}
        if name:
            data["tenant"]["name"] = name
        if description:
            data["tenant"]["description"] = description
        resp, resp_body = self.method_put("tenants/%s" % tenant_id, data=data)
        return Tenant(self, resp_body)
1299478
def roles_for_user(request, user, project=None, domain=None):
    """"""
    manager = keystoneclient(request, admin=True).roles
    if VERSIONS.active < 3:
        return manager.roles_for_user(user, project)
    else:
        return manager.list(user=user, domain=domain, project=project)
1090294
public function Add() {
      $this->Permission('Garden.Users.Add');
      
      // Page setup
      $this->AddJsFile('user.js');
      $this->Title(T('Add User'));
      $this->AddSideMenu('dashboard/user');
      
      $RoleModel = new RoleModel();
      $AllRoles = $RoleModel->GetArray();
      
      // By default, people with access here can freely assign all roles
      $this->RoleData = $AllRoles;
      
      $UserModel = new UserModel();
      $this->User = FALSE;

      // Set the model on the form.
      $this->Form->SetModel($UserModel);
      
      try {
         // These are all the 'effective' roles for this add action. This list can
         // be trimmed down from the real list to allow subsets of roles to be edited.
         $this->EventArguments['RoleData'] = &$this->RoleData;

         $this->FireEvent("BeforeUserAdd");

         if ($this->Form->AuthenticatedPostBack()) {

            // These are the new roles the creating user wishes to apply to the target
            // user, adjusted for his ability to affect those roles
            $RequestedRoles = $this->Form->GetFormValue('RoleID');

            if (!is_array($RequestedRoles)) $RequestedRoles = array();
            $RequestedRoles = array_flip($RequestedRoles);
            $UserNewRoles = array_intersect_key($this->RoleData, $RequestedRoles);

            // Put the data back into the forum object as if the user had submitted 
            // this themselves
            $this->Form->SetFormValue('RoleID', array_keys($UserNewRoles));

            $NewUserID = $this->Form->Save(array('SaveRoles' => TRUE, 'NoConfirmEmail' => TRUE));
            if ($NewUserID !== FALSE) {
               $Password = $this->Form->GetValue('Password', '');
               $UserModel->SendWelcomeEmail($NewUserID, $Password, 'Add');
               $this->InformMessage(T('The user has been created successfully'));
               $this->RedirectUrl = Url('dashboard/user');
            }

            $this->UserRoleData = $UserNewRoles;
         } else {
            // Set the default roles.
            $this->UserRoleData = C('Garden.Registration.DefaultRoles', array());
         }

      } catch (Exception $Ex) {
         $this->Form->AddError($Ex);
      }
      $this->Render();
   }
94707
def add_user(self, user_name, role='user'):
        
        role_uri = self._get_role_uri(role=role)
        return self.api.put(path=role_uri, data={'username': user_name})
1017555
protected function addAssignmentsToSu() : void
    {
        $roleSu = $this->authManager->getRole(Rbac::R_SU);
        $this->addRolesToSU($roleSu);
        $this->addPermissionsToSU($roleSu);
    }
388653
def post(self):
        """"""
        self.reqparse.add_argument('username', type=str, required=True)
        self.reqparse.add_argument('authSystem', type=str, required=True)
        self.reqparse.add_argument('password', type=str, required=False, default=None)
        self.reqparse.add_argument('roles', type=str, action='append', default=[])
        args = self.reqparse.parse_args()
        auditlog(event='user.create', actor=session['user'].username, data=args)

        user = db.User.find_one(
            User.username == args['username'],
            User.auth_system == args['authSystem']
        )
        roles = []
        if user:
            return self.make_response('User already exists', HTTP.BAD_REQUEST)

        if args['authSystem'] not in current_app.available_auth_systems:
            return self.make_response(
                'The {} auth system does not allow local edits'.format(args['authSystem']),
                HTTP.BAD_REQUEST
            )

        if current_app.available_auth_systems[args['authSystem']].readonly:
            return self.make_response(
                'You cannot create users for the {} auth system as it is handled externally'.format(args['authSystem']),
                HTTP.BAD_REQUEST
            )

        for roleName in args['roles']:
            role = db.Role.find_one(Role.name == roleName)

            if not role:
                return self.make_response('No such role {}'.format(roleName), HTTP.BAD_REQUEST)

            if roleName == ROLE_ADMIN and ROLE_ADMIN not in session['user'].roles:
                self.log.error('User {} tried to grant admin privileges to {}'.format(
                    session['user'].username,
                    args['username']
                ))

                return self.make_response('You do not have permission to grant admin privileges', HTTP.FORBIDDEN)

            roles.append(role)

        authSys = current_app.available_auth_systems[args['authSystem']]
        password = args['password'] or generate_password()

        user = User()
        user.username = args['username']
        user.password = hash_password(password)
        user.auth_system = authSys.name
        db.session.add(user)
        db.session.commit()
        db.session.refresh(user)
        User.add_role(user, roles)

        return self.make_response({
            'message': 'User {}/{} has been created'.format(user.auth_system, user.username),
            'user': user,
            'password': password if not args['password'] else None
        })