示例#1
0
 /**
  * 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 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;
 }
示例#3
0
文件: _form.php 项目: dsyman2/X2CRM
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];
示例#4
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));
 }
示例#5
0
 /**
  * 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));
 }
示例#6
0
文件: User.php 项目: dsyman2/X2CRM
 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;
         }
     }
 }
示例#7
0
 /**
  * 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.");
     }
 }
示例#8
0
 /**
  * Echo out a series of inputs for a role editor page.
  *
  * This method is called via AJAX from the "Edit Role" portion of the "Manage Roles"
  * page.  Upon selection of a role in the dropdown on that page, this method
  * finds all relevant information about the role and echoes it back as a form
  * to allow for editing of the role.
  */
 public function actionGetRole()
 {
     if (isset($_POST['Roles'])) {
         $id = $_POST['Roles']['name'];
         $role = Roles::model()->findByAttributes(array('name' => $id));
         if (!$role) {
             echo "";
             exit;
         }
         $id = $role->id;
         $roles = RoleToUser::model()->findAllByAttributes(array('roleId' => $id));
         $users = array();
         foreach ($roles as $link) {
             if ($link->type == 'user') {
                 $user = User::model()->findByPk($link->userId);
                 if (isset($user)) {
                     $users[] = $user->username;
                 }
             } else {
                 $group = Groups::model()->findByPk($link->userId);
                 if (isset($group)) {
                     $users[] = $group->id;
                 }
             }
             /* end x2temp */
         }
         $allUsers = User::model()->findAll('status="1"');
         $selected = array();
         $unselected = array();
         foreach ($users as $user) {
             $selected[] = $user;
         }
         foreach ($allUsers as $user) {
             $unselected[CHtml::encode($user->username)] = CHtml::encode($user->firstName . " " . $user->lastName);
         }
         /* x2temp */
         $groups = Groups::model()->findAll();
         foreach ($groups as $group) {
             $unselected[$group->id] = CHtml::encode($group->name);
         }
         /* end x2temp */
         unset($unselected['admin']);
         $sliderId = 'editTimeoutSlider';
         $textfieldId = 'editTimeout';
         if (isset($_GET['mode']) && in_array($_GET['mode'], array('edit', 'exception'))) {
             // Handle whether this was called from editRole or roleException, they
             // need different IDs to work on the same page.
             $sliderId .= "-" . $_GET['mode'];
             $textfieldId .= "-" . $_GET['mode'];
         }
         $timeoutSet = $role->timeout !== null;
         echo "\n                <div class='row' id='set-session-timeout-row'>\n                <input id='set-session-timeout' type='checkbox' class='left' " . ($timeoutSet ? 'checked="checked"' : '') . ">\n                <label>" . Yii::t('admin', 'Enable Session Timeout') . "</label>\n                </div>\n            ";
         echo "<div id='timeout-row' class='row' " . ($timeoutSet ? '' : "style='display: none;'") . ">";
         echo Yii::t('admin', 'Set role session expiration time (in minutes).');
         echo "<br />";
         $this->widget('zii.widgets.jui.CJuiSlider', array('value' => $role->timeout / 60, 'options' => array('min' => 5, 'max' => 1440, 'step' => 5, 'change' => "js:function(event,ui) {\n                                    \$('#" . $textfieldId . "').val(ui.value);\n                                    \$('#save-button').addClass('highlight');\n                                }", 'slide' => "js:function(event,ui) {\n                                    \$('#" . $textfieldId . "').val(ui.value);\n                                }"), 'htmlOptions' => array('style' => 'width:340px;margin:10px 9px;', 'id' => $sliderId)));
         echo CHtml::activeTextField($role, 'timeout', array('id' => $textfieldId, 'disabled' => $role->timeout !== null ? '' : 'disabled'));
         echo "</div>";
         Yii::app()->clientScript->registerScript('timeoutScript', "\n                \$('#set-session-timeout').change (function () {\n                    if (\$(this).is (':checked')) {\n                        \$('#timeout-row').slideDown ();\n                        \$('#" . $textfieldId . "').removeAttr ('disabled');\n                    } else {\n                        \$('#timeout-row').slideUp ();\n                        \$('#" . $textfieldId . "').attr ('disabled', 'disabled');\n                    }\n                });\n                \$('#" . $textfieldId . "').val( \$('#" . $sliderId . "').slider('value') );\n            ", CClientScript::POS_READY);
         echo "<script>";
         Yii::app()->clientScript->echoScripts();
         echo "</script>";
         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] = X2Model::getModelTitle($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));
     }
 }
示例#9
0
 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));
 }
示例#12
0
 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));
     }
 }
示例#13
0
 public function getPost()
 {
     $post = RoleToUser::model()->find(['condition' => "user_id=" . $this->id]);
     if ($post) {
         return $post;
     } else {
         return "Должность не выбрана";
     }
 }