/** * Ensure that upon deletion of roleToUser records, roles update immediately * (do not use an outdated cache entry) */ public function testGetUserRoles() { $userId = $this->user['testUser']['id']; $userRoles = Roles::getUserRoles($userId); // Assert that user has roles $this->assertTrue(sizeof($userRoles) > 0); // Specifically, these (user groups only): $this->assertEquals(array(1, 2), $userRoles); // Test group-inherited user roles; fixture entry "testUser5" is a // member of a group: $userRoles = Roles::getUserRoles($this->user['testUser5']['id']); $this->assertEquals(array(3), $userRoles); // Iterate over and remove records explicitly to raise the afterDelete event $records = RoleToUser::model()->findAllByAttributes(array('userId' => $userId, 'type' => 'user')); foreach ($records as $record) { $record->delete(); } $userRoles = Roles::getUserRoles($userId); // assert that user has no roles $this->assertTrue(sizeof($userRoles) === 0); }
public function actionUpdateRole($id) { $student = Student::model()->findByAttributes(array('id_user' => $id)); if (!$student) { $student = false; } $valid = true; if (isset($_POST['Student'])) { $student->attributes = $_POST['Student']; if ($_POST['Role'][3] == 1) { $valid = $valid && $student->save(); } } if (isset($_POST['Role']) && !empty($_POST['Role']) && $valid) { foreach ($_POST['Role'] as $key => $role) { $arrRol[] = $key; } if (RoleToUser::model()->changeRole($id, $arrRol)) { $this->redirect(array('allusers')); } } $roles = Role::model()->findAll(); $user = User::model()->findByPk($id); $this->render('update', array('user' => $user, 'roles' => $roles, 'student' => $student)); }
public function testAuthenticate() { // This filter should be run before the validModel filter and hence, // it's safe to assume that a response code of 400 when requesting // with an empty model parameter means that authentication succeeded. $urlParam = $this->urlParam; $urlParam['{action}'] = 'create'; // Test with no credentials (but empty array will designate it as a GET // request, so put something in the sending parameters) $param = array('foo' => 1); $ch = $this->getCurlHandle($urlParam, $param); $response = curl_exec($ch); // file_put_contents('api_response.html',$response); $this->assertResponseCodeIs(401, $ch); $this->assertRegExp('/No user credentials provided/', $response); // Test with invalid user: $param = $this->param; $param['user'] = '******'; $ch = $this->getCurlHandle($urlParam, $param); $response = curl_exec($ch); file_put_contents('api_response.html', $response); $this->assertResponseCodeIs(401, $ch, 'Response is not what is expected for there being an invalid user'); $this->assertRegExp('/Invalid user credentials/', $response); // Test user with empty API key $user = $this->users('testUser'); $user->userKey = ''; $user->save(); $param = $this->param; $param['userKey'] = ''; $ch = $this->getCurlHandle($urlParam, $param); $response = curl_exec($ch); // file_put_contents('api_response.html',$response); $this->assertResponseCodeIs(403, $ch); $this->assertRegExp('/cannot use API; userKey not set/', $response); // Test access permissions: $origUrlFormat = $this->_urlFormat; $param = $this->param; $user->userKey = $param['userKey']; $user->save(); $this->_urlFormat = 'api/checkPermissions/action/{action}/username/{username}/api/1'; $urlParam['{username}'] = 'testuser'; $auth = Yii::app()->authManager; $roles = RoleToUser::model()->findAllByAttributes(array('userId' => $this->users('testUser')->id)); foreach (array('Contacts', 'Actions', 'Quotes', 'Opportunities', 'Accounts', 'Products') as $module) { foreach (array('Create', 'Update', 'View', 'Delete') as $action) { // Get response: $urlParam['{action}'] = $module . $action; $ch = $this->getCurlHandle($urlParam, $param); $apiAccess = curl_exec($ch) == 'true'; $access = false; $access = $auth->checkAccess($urlParam['{action}'], $user->id); VERBOSE_MODE && println('Action:'); VERBOSE_MODE && print_r($urlParam); VERBOSE_MODE && println((int) $access); VERBOSE_MODE && println((int) $apiAccess); $this->assertEquals((int) $access, (int) $apiAccess, 'Failed asserting consistency between API-reported permissions and internal app permissions.'); } } $this->_urlFormat = $origUrlFormat; }
protected function afterSave() { parent::afterSave(); if ($this->isNewRecord) { $role = new RoleToUser(); $role->id_user = $this->id_user; $role->id_role = $this->setRole; $role->save(); //$this->mailNewUser(); } if ($this->scenario = 'newPassword') { //$this->mailNewUser(); } }
foreach ($fields as $field) { if ($field->custom == 0) { $nonCustom[$field->fieldName] = $field; } else { $custom[$field->fieldName] = $field; } } $temp = RoleToUser::model()->findAllByAttributes(array('userId' => Yii::app()->user->getId())); $roles = array(); foreach ($temp as $link) { $roles[] = $link->roleId; } /* x2temp */ $groups = GroupToUser::model()->findAllByAttributes(array('userId' => Yii::app()->user->getId())); foreach ($groups as $link) { $tempRole = RoleToUser::model()->findByAttributes(array('userId' => $link->groupId, 'type' => 'group')); $roles[] = $tempRole->roleId; } /* end x2temp */ echo $form->errorSummary($model); ?> <div class="span-15" id="form-box" style="position:relative;overflow:hidden;height:700px;"> <?php foreach ($fields as $field) { ?> <?php if ($field->fieldName != "id") { $size = $field->size; $pieces = explode(":", $size); $width = $pieces[0]; $height = $pieces[1];
/** * Updates a particular model. * If update is successful, the browser will be redirected to the 'view' page. * @param integer $id the ID of the model to be updated */ public function actionUpdate($id) { $model = $this->loadModel($id); $groups = array(); foreach (Groups::model()->findAll() as $group) { $groups[$group->id] = CHtml::encode($group->name); } $selectedGroups = array(); foreach (GroupToUser::model()->findAllByAttributes(array('userId' => $model->id)) as $link) { $selectedGroups[] = $link->groupId; } $roles = array(); foreach (Roles::model()->findAll() as $role) { $roles[$role->id] = CHtml::encode($role->name); } $selectedRoles = array(); foreach (RoleToUser::model()->findAllByAttributes(array('userId' => $model->id)) as $link) { $selectedRoles[] = $link->roleId; } // Uncomment the following line if AJAX validation is needed // $this->performAjaxValidation($model); if (!isset($model->userAlias)) { $model->userAlias = $model->username; } if (isset($_POST['User'])) { $old = $model->attributes; $temp = $model->password; $model->attributes = $_POST['User']; if ($model->password != "") { $model->password = PasswordUtil::createHash($model->password); } else { $model->password = $temp; } if (empty($model->userKey)) { $model->userKey = substr(str_shuffle(str_repeat('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789', 32)), 0, 32); } if ($model->save()) { $profile = $model->profile; if (!empty($profile)) { $profile->emailAddress = $model->emailAddress; $profile->fullName = $model->firstName . ' ' . $model->lastName; $profile->save(); } if ($old['username'] != $model->username) { $fieldRecords = Fields::model()->findAllByAttributes(array('fieldName' => 'assignedTo')); $modelList = array(); foreach ($fieldRecords as $record) { $modelList[$record->modelName] = $record->linkType; } foreach ($modelList as $modelName => $type) { if ($modelName == 'Quotes') { $modelName = "Quote"; } if ($modelName == 'Products') { $modelName = 'Product'; } if (empty($type)) { $list = X2Model::model($modelName)->findAllByAttributes(array('assignedTo' => $old['username'])); foreach ($list as $item) { $item->assignedTo = $model->username; $item->save(); } } else { $list = X2Model::model($modelName)->findAllBySql("SELECT * FROM " . X2Model::model($modelName)->tableName() . " WHERE assignedTo LIKE '%" . $old['username'] . "%'"); foreach ($list as $item) { $assignedTo = explode(", ", $item->assignedTo); $key = array_search($old['username'], $assignedTo); if ($key >= 0) { $assignedTo[$key] = $model->username; } $item->assignedTo = implode(", ", $assignedTo); $item->save(); } } } $profile = Profile::model()->findByAttributes(array('username' => $old['username'])); if (isset($profile)) { $profile->username = $model->username; $profile->save(); } } foreach (RoleToUser::model()->findAllByAttributes(array('userId' => $model->id)) as $link) { $link->delete(); } foreach (GroupToUser::model()->findAllByAttributes(array('userId' => $model->id)) as $link) { $link->delete(); } if (isset($_POST['roles'])) { $roles = $_POST['roles']; foreach ($roles as $role) { $link = new RoleToUser(); $link->roleId = $role; $link->type = "user"; $link->userId = $model->id; $link->save(); } } if (isset($_POST['groups'])) { $groups = $_POST['groups']; foreach ($groups as $group) { $link = new GroupToUser(); $link->groupId = $group; $link->userId = $model->id; $link->username = $model->username; $link->save(); } } $this->redirect(array('view', 'id' => $model->id)); } } $this->render('update', array('model' => $model, 'groups' => $groups, 'roles' => $roles, 'selectedGroups' => $selectedGroups, 'selectedRoles' => $selectedRoles)); }
public static function hasRole($user, $role) { if (is_numeric($role)) { $lookup = RoleToUser::model()->findByAttributes(array('userId' => $user, 'roleId' => $role)); return isset($lookup); } else { $roleRecord = Roles::model()->findByAttributes(array('name' => $role)); if (isset($roleRecord)) { $lookup = RoleToUser::model()->findByAttributes(array('userId' => $user, 'roleId' => $roleRecord->id)); return isset($lookup); } else { return false; } } }
/** * Checks credentials for API access * * @param CFilterChain $filterChain */ public function filterAuthenticate($filterChain) { $haveCred = false; $this->log("Checking user record."); if (Yii::app()->request->requestType == 'POST') { $haveCred = isset($_POST['userKey']) && isset($_POST['user']); $params = $_POST; } else { $haveCred = isset($_GET['userKey']) && isset($_GET['user']); $params = $_GET; } if ($haveCred) { $this->user = User::model()->findByAttributes(array('username' => $params['user'], 'userKey' => $params['userKey'])); if ((bool) $this->user) { Yii::app()->suModel = $this->user; if (!empty($this->user->userKey)) { Yii::app()->params->groups = Groups::getUserGroups($this->user->id); Yii::app()->params->roles = Roles::getUserRoles($this->user->id); // Determine if the API user is admin (so that Yii::app()->params->isAdmin gets set properly): $roles = RoleToUser::model()->findAllByAttributes(array('userId' => $this->user->id)); $access = false; $auth = Yii::app()->authManager; foreach ($roles as $role) { $access = $access || $auth->checkAccess('AdminIndex', $role->roleId); } if ($access) { Yii::app()->params->isAdmin = true; } $filterChain->run(); } else { $this->_sendResponse(403, "User \"{$this->user->username}\" cannot use API; userKey not set."); } } else { $this->log("Authentication failed; invalid user credentials; IP = {$_SERVER['REMOTE_ADDR']}; get or post params = " . CJSON::encode($params) . ''); $this->_sendResponse(401, "Invalid user credentials."); } } else { $this->log('No user credentials provided; IP = ' . $_SERVER['REMOTE_ADDR']); $this->_sendResponse(401, "No user credentials provided."); } }
/** * A catch all page for roles. * * This action renders a page with forms for the creation, editing, and deletion * of roles. It also displays a grid with all user created roles (default * roles are not included and cannot be edited this way). */ public function actionManageRoles() { $dataProvider = new CActiveDataProvider('Roles'); $roles = $dataProvider->getData(); $arr = array(); foreach ($roles as $role) { $arr[$role->name] = $role->name; } $temp = Workflow::model()->findAll(); $workflows = array(); foreach ($temp as $workflow) { $workflows[$workflow->id] = $workflow->name; } $model = new Roles(); $model->timeout = 60; if (isset($_POST['Roles'])) { $model->attributes = $_POST['Roles']; if (!isset($_POST['viewPermissions'])) { $viewPermissions = array(); } else { $viewPermissions = $_POST['viewPermissions']; } if (!isset($_POST['editPermissions'])) { $editPermissions = array(); } else { $editPermissions = $_POST['editPermissions']; } if (isset($_POST['Roles']['users'])) { $users = $model->users; } else { $users = array(); } $model->users = ""; $model->timeout *= 60; if ($model->save()) { foreach ($users as $user) { $role = new RoleToUser(); $role->roleId = $model->id; if (!is_numeric($user)) { $userRecord = User::model()->findByAttributes(array('username' => $user)); $role->userId = $userRecord->id; $role->type = 'user'; } else { $role->userId = $user; $role->type = 'group'; } /* end x2temp */ $role->save(); } $fields = Fields::model()->findAll(); $temp = array(); foreach ($fields as $field) { $temp[] = $field->id; } $both = array_intersect($viewPermissions, $editPermissions); $view = array_diff($viewPermissions, $editPermissions); $neither = array_diff($temp, $viewPermissions); foreach ($both as $field) { $rolePerm = new RoleToPermission(); $rolePerm->roleId = $model->id; $rolePerm->fieldId = $field; $rolePerm->permission = 2; $rolePerm->save(); } foreach ($view as $field) { $rolePerm = new RoleToPermission(); $rolePerm->roleId = $model->id; $rolePerm->fieldId = $field; $rolePerm->permission = 1; $rolePerm->save(); } foreach ($neither as $field) { $rolePerm = new RoleToPermission(); $rolePerm->roleId = $model->id; $rolePerm->fieldId = $field; $rolePerm->permission = 0; $rolePerm->save(); } } else { foreach ($model->getErrors() as $err) { $errors = $err; } $errors = implode(',', $errors); Yii::app()->user->setFlash('error', Yii::t('admin', "Unable to save role: {errors}", array('{errors}' => $errors))); } $this->redirect('manageRoles'); } $this->render('manageRoles', array('dataProvider' => $dataProvider, 'model' => $model, 'roles' => $arr, 'workflows' => $workflows)); }
public function getPost() { return RoleToUser::model()->find(['condition' => "user_id=" . $this->id]); }
/** * Возвращает модель по указанному идентификатору * Если модель не будет найдена - возникнет HTTP-исключение. * * @param integer идентификатор нужной модели * * @return void */ public function loadModel($id) { $model = RoleToUser::model()->findByPk($id); if ($model === null) { throw new CHttpException(404, Yii::t('UserModule.user', 'Запрошенная страница не найдена.')); } return $model; }
/** * Updates a particular model. * If update is successful, the browser will be redirected to the 'view' page. * @param integer $id the ID of the model to be updated */ public function actionUpdate($id) { $model = $this->loadModel($id); $groups = array(); foreach (Groups::model()->findAll() as $group) { $groups[$group->id] = $group->name; } $selectedGroups = array(); foreach (GroupToUser::model()->findAllByAttributes(array('userId' => $model->id)) as $link) { $selectedGroups[] = $link->groupId; } $roles = array(); foreach (Roles::model()->findAll() as $role) { $roles[$role->id] = $role->name; } $selectedRoles = array(); foreach (RoleToUser::model()->findAllByAttributes(array('userId' => $model->id)) as $link) { $selectedRoles[] = $link->roleId; } // Uncomment the following line if AJAX validation is needed // $this->performAjaxValidation($model); if (isset($_POST['User'])) { $temp = $model->password; $model->attributes = $_POST['User']; if ($model->password != "") { $model->password = md5($model->password); } else { $model->password = $temp; } if ($model->save()) { foreach (RoleToUser::model()->findAllByAttributes(array('userId' => $model->id)) as $link) { $link->delete(); } foreach (GroupToUser::model()->findAllByAttributes(array('userId' => $model->id)) as $link) { $link->delete(); } if (isset($_POST['roles'])) { $roles = $_POST['roles']; foreach ($roles as $role) { $link = new RoleToUser(); $link->roleId = $role; $link->userId = $model->id; $link->save(); } } if (isset($_POST['groups'])) { $groups = $_POST['groups']; foreach ($groups as $group) { $link = new GroupToUser(); $link->groupId = $group; $link->userId = $model->id; $link->username = $model->username; $link->save(); } } $this->redirect(array('view', 'id' => $model->id)); } } $this->render('update', array('model' => $model, 'groups' => $groups, 'roles' => $roles, 'selectedGroups' => $selectedGroups, 'selectedRoles' => $selectedRoles)); }
public function actionGetRole() { if (isset($_POST['Roles'])) { $id = $_POST['Roles']['name']; if (is_null($id)) { echo ""; exit; } $role = Roles::model()->findByAttributes(array('name' => $id)); $id = $role->id; $roles = RoleToUser::model()->findAllByAttributes(array('roleId' => $id)); $users = array(); foreach ($roles as $link) { if ($link->type == 'user') { $users[] = User::model()->findByPk($link->userId)->username; } else { $users[] = Groups::model()->findByPk($link->userId)->id; } /* end x2temp */ } $allUsers = User::model()->findAll(); $selected = array(); $unselected = array(); foreach ($users as $user) { $selected[] = $user; } foreach ($allUsers as $user) { $unselected[$user->username] = $user->firstName . " " . $user->lastName; } /* x2temp */ $groups = Groups::model()->findAll(); foreach ($groups as $group) { $unselected[$group->id] = $group->name; } /* end x2temp */ unset($unselected['admin']); echo "<div id='users'><label>Users</label>"; echo CHtml::dropDownList('users[]', $selected, $unselected, array('class' => 'multiselect', 'multiple' => 'multiple', 'size' => 8)); echo "</div>"; $fields = Fields::model()->findAllBySql("SELECT * FROM x2_fields ORDER BY modelName ASC"); $viewSelected = array(); $editSelected = array(); $fieldUnselected = array(); $fieldPerms = RoleToPermission::model()->findAllByAttributes(array('roleId' => $role->id)); foreach ($fieldPerms as $perm) { if ($perm->permission == 2) { $viewSelected[] = $perm->fieldId; $editSelected[] = $perm->fieldId; } else { if ($perm->permission == 1) { $viewSelected[] = $perm->fieldId; } } } foreach ($fields as $field) { $fieldUnselected[$field->id] = $field->modelName . " - " . $field->attributeLabel; } echo "<br /><label>View Permissions</label>"; echo CHtml::dropDownList('viewPermissions[]', $viewSelected, $fieldUnselected, array('class' => 'multiselect', 'multiple' => 'multiple', 'size' => 8)); echo "<br /><label>Edit Permissions</label>"; echo CHtml::dropDownList('editPermissions[]', $editSelected, $fieldUnselected, array('class' => 'multiselect', 'multiple' => 'multiple', 'size' => 8)); } }
public function getPost() { $post = RoleToUser::model()->find(['condition' => "user_id=" . $this->id]); if ($post) { return $post; } else { return "Должность не выбрана"; } }