public function authenticate()
 {
     if (isset($this->key)) {
         $record = Users::model()->findByAttributes(array('key' => $this->key));
     } else {
         $record = Users::model()->findByAttributes(array('email' => $this->email));
     }
     $status = false;
     if ($record === null) {
         $this->errorCode = self::ERROR_USERNAME_INVALID;
     } else {
         if (isset($this->password) && $record->password !== md5($this->password)) {
             $this->errorCode = self::ERROR_PASSWORD_INVALID;
         } else {
             $this->_id = $record->id;
             $this->user = $record;
             $this->setState('email', $record->email);
             //            $this->setState('name', $record->username);
             $this->setState('id', $record->id);
             //            $this->setState('key', $record->key);
             $auth = Yii::app()->authManager;
             $data = AuthAssignment::model()->find('userid=:userid', array(':userid' => $record->id));
             $this->setState('role', $data->itemname);
             //echo  Yii::app()->user->role;exit();
             $this->errorCode = self::ERROR_NONE;
             $status = true;
         }
     }
     return $status;
 }
 /**
  * Update permission
  */
 public function actionUpdate($id)
 {
     // Check Access
     checkAccessThrowException('op_permission_update');
     $model = AuthItem::model()->findByPk($id);
     if ($model) {
         if (isset($_POST['AuthItem'])) {
             $old_name = $model->name;
             $model->setAttributes($_POST['AuthItem']);
             if ($model->save()) {
                 // Update parent name and child name in the auth child table
                 AuthItemChild::model()->updateAll(array('parent' => $model->name), 'parent=:name', array(':name' => $old_name));
                 AuthItemChild::model()->updateAll(array('child' => $model->name), 'child=:name', array(':name' => $old_name));
                 AuthAssignment::model()->updateAll(array('bizrule' => $model->bizrule, 'data' => $model->data, 'itemname' => $model->name), 'itemname=:name', array(':name' => $old_name));
                 User::model()->updateAll(array('role' => $model->name), 'role=:name', array(':name' => $old_name));
                 fok(at('Permission Updated!'));
                 // Log Message
                 alog(at("Updated permission: '{name}'.", array('{name}' => $model->name)));
                 $this->redirect(array('index'));
             }
         }
         // Add Breadcrumb
         $this->addBreadCrumb(at('Update Permission'));
         $this->title[] = at('Update Permission');
         $this->render('form', array('model' => $model));
     } else {
         throw new CHttpException(404, at('Sorry, That record was not found.'));
     }
 }
 public function renderAssignedItem($data)
 {
     $string = '';
     $assignedList = AuthAssignment::model()->assignedList($data->id);
     //<span class="label">Regular Label</span>
     foreach ($assignedList as $item) {
         $string .= '<span class="secondary label">' . $item['itemname'] . '</span><span class="label">' . $item['typename'] . '</span><br />';
     }
     return $string;
 }
Beispiel #4
0
 function getRole()
 {
     if ($oUser = $this->getModel()) {
         $oAuthAssignment = AuthAssignment::model()->findByattributes(array('userid' => $oUser->id));
         if ($oAuthAssignment) {
             return $oAuthAssignment->itemname;
         }
     }
     return false;
 }
 public static function updateUserRole($user_id, $role)
 {
     $assignment = AuthAssignment::model()->findByAttributes(array('userid' => $user_id));
     if (!$assignment) {
         $assignment = new AuthAssignment();
         $assignment->userid = $user_id;
     }
     $assignment->itemname = $role;
     $assignment->save();
 }
 public function actionFindUser($group, $term)
 {
     $dataProvider = new CActiveDataProvider('User', array('criteria' => array('select' => array('id', 'email')), 'pagination' => array('pageSize' => 500)));
     $criteria = $dataProvider->getCriteria();
     $criteria->compare('email', $term, true);
     $result = CHtml::listData($dataProvider->getData(), 'id', 'email');
     $members = Yii::app()->db->createCommand()->select('userid')->from(AuthAssignment::model()->tableName())->where('itemname=:group', array(':group' => $group))->queryColumn();
     echo CJSON::encode(array_diff_key($result, array_flip($members)));
     Yii::app()->end();
 }
 protected function loadUser($id = null)
 {
     if ($this->_model === null) {
         if ($id !== null) {
             $this->_model = User::model()->findByPk($id);
             $this->userRoles = AuthAssignment::model()->findAll("userid=:usrId", array(':usrId' => $this->_model->nick));
         }
     }
     return $this->_model;
 }
 /**
  * This is the default 'index' action that is invoked
  * when an action is not explicitly requested by users.
  */
 public function actionIndex()
 {
     if (!$this->allowIp(CHttpRequest::getUserHostAddress())) {
         throw new CHttpException(403, 'Akses ditolak - Anda tidak memiliki izin untuk mengakses halaman ini!');
     }
     if (Yii::app()->user->isGuest) {
         $this->redirect($this->createUrl('/app/login'));
     } else {
         $roles = AuthAssignment::model()->assignedList(Yii::app()->user->id);
         $this->render('index', array('roles' => $roles));
     }
 }
Beispiel #9
0
 /**
  * Authenticates a user.
  * The example implementation makes sure if the username and password
  * are both 'demo'.
  * In practical applications, this should be changed to authenticate
  * against some persistent user identity storage (e.g. database).
  * @return boolean whether authentication succeeds.
  */
 public function authenticate()
 {
     // find user record by email address (username)
     $UserLogin = UserLogin::model()->findByAttributes(array('LoginEmail' => $this->username, 'IsActive' => 1));
     if ($UserLogin === null) {
         $this->errorCode = self::ERROR_USERNAME_INVALID;
     } else {
         if ($UserLogin->UserPassword !== md5($this->password)) {
             $this->errorCode = self::ERROR_PASSWORD_INVALID;
         } else {
             $this->errorCode = self::ERROR_NONE;
             // set user login ID
             $this->userLoginID = $UserLogin->UserLoginID;
             // assign user role in auth manager
             $userRole = UserRole::model()->findByPk($UserLogin->UserRoleID)->RoleType;
             $currentRoles = Yii::app()->authManager->getRoles($this->userLoginID);
             if (!array_key_exists($userRole, $currentRoles)) {
                 // remove old role if role changes
                 if (!empty($currentRoles)) {
                     AuthAssignment::model()->deleteAll('userid = :userid', array('userid' => $this->userLoginID));
                 }
                 Yii::app()->authManager->assign($userRole, $this->userLoginID);
                 Yii::app()->authManager->save();
             }
             // UserProfile
             //$UserProfile = UserProfile::model()->findByAttributes(array('UserLoginID'=>$UserLogin->UserLoginID));
             $UserProfile = UserProfile::model()->with('companies')->findByAttributes(array('UserLoginID' => $UserLogin->UserLoginID));
             //            echo '<pre>';
             //            print_r($UserProfile);
             //            die();
             // create session variables
             $this->setState('fullName', sprintf('%s %s', $UserProfile->FirstName, $UserProfile->LastName));
             // full user name
             $this->setState('companyID', $UserProfile->CompanyID);
             // user email
             $this->setState('userProfileID', $UserProfile->UserProfileID);
             // user email
             $this->setState('email', $UserLogin->LoginEmail);
             // user email
             $this->setState('companyName', $UserProfile->companies->CompanyName);
             // user email
             $this->setState('agreeToTerms', $UserProfile->AgreeToTerms);
             // user email
             $this->setState('isFacilitator', $UserProfile->IsFacilitator);
             // user email
             $this->setState('UserRoleID', $UserLogin->UserRoleID);
             // user email
         }
     }
     return !$this->errorCode;
 }
 public function SaveRole($iduser, $role)
 {
     $transaction = Yii::app()->db->getCurrentTransaction();
     if ($transaction !== null) {
         $transaction = null;
     } else {
         $transaction = Yii::app()->db->beginTransaction();
     }
     try {
         //del all Authorized with userid=$iduser
         AuthAssignment::model()->deleteAll('userid=:iduser', array(':iduser' => $iduser));
         //add role to table auth_item
         $role = strtolower($role);
         if (!Yii::app()->AuthManager->getAuthItem(strtolower($role))) {
             Yii::app()->AuthManager->createRole(strtolower($role));
         }
         //add to table auth_assignment with userid=$iduser
         Yii::app()->authManager->assign(strtolower($role), $iduser);
         if ($role != 'super user') {
             //chỉ thêm các operation khi không phải là super user
             foreach ($this->publicRolesArray[$role] as $Cotroller) {
                 $listAction = Yii::app()->metadata->getActions($Cotroller . 'Controller', 'backend');
                 foreach ($listAction as $action) {
                     $name = strtolower($Cotroller . '.' . $action);
                     //exe: post.create
                     //If the name does not exist, then add it
                     if (!Yii::app()->AuthManager->getAuthItem($name)) {
                         Yii::app()->AuthManager->createOperation($name, $Cotroller . ' ' . $action);
                     }
                     //add to table auth_assignment
                     Yii::app()->AuthManager->assign($name, $iduser);
                     Yii::app()->AuthManager->save();
                 }
             }
         }
         if ($transaction !== null) {
             $transaction->commit();
         }
         return true;
     } catch (Exception $e) {
         if ($transaction !== null) {
             $transaction->rollback();
         }
     }
     return FALSE;
 }
Beispiel #11
0
 /**
  * Загрузка данных из бд и распределение их по спискам
  */
 private function getData()
 {
     $userAssign = CHtml::listData(AuthAssignment::model()->findAllByAttributes(['userid' => $this->user->id]), 'itemname', 'userid');
     $authItems = AuthItem::model()->findAll(['order' => 'type DESC, description ASC']);
     foreach ((array) $authItems as $item) {
         $this->itemsGroupedByTypes[$item->type][$item->name] = $item;
         $this->itemsList[$item->name] = $item;
         // если проверять каждый элемент, то генерируется огромное количество запросов, но получается правильное дерево с отмеченными дочерними элементами
         // созможно стоит при сохранении ролей что-то придумать
         $this->permissionList[$item->name] = isset($userAssign[$item->name]);
         //Yii::app()->authManager->checkAccess($item->name, $this->user->id);
     }
     $authItemsChild = AuthItemChild::model()->findAll();
     foreach ((array) $authItemsChild as $item) {
         $this->hierarchy[$item->parent][] = $item->child;
         $this->wereChildren[] = $item->child;
     }
 }
 /**
  * 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);
     // Uncomment the following line if AJAX validation is needed
     // $this->performAjaxValidation($model);
     if (isset($_POST['User'])) {
         $model->attributes = $_POST['User'];
         if ($model->save()) {
             $authAsign = AuthAssignment::model()->findByAttributes(array('userid' => $model->nick));
             $authAsign->itemname = $model->role;
             if ($authAsign->save()) {
                 $this->audit->logAudit(Yii::app()->user->id, new DateTime(), Constants::AUDITORIA_OBJETO_USUARIO, Constants::AUDITORIA_OPERACION_MODIFICACION, $model->nick);
                 $this->render('/site/successfullOperation', array('header' => 'Usuario modificado con &eacute;xito', 'message' => 'Haga click en volver para regresar a la gestión de usuarios', 'returnUrl' => Yii::app()->createUrl('user/admin'), 'viewUrl' => Yii::app()->createUrl("user/view", array("id" => $model->nick))));
                 return;
             }
         }
     }
     $this->render('update', array('model' => $model));
 }
 public function run($args)
 {
     $companies = Company::model()->findAll('frozen=:p', array(':p' => '0'));
     foreach ($companies as $company) {
         Company::setActive($company);
         Yii::app()->language = Company::getLanguage();
         User::model()->refreshMetaData();
         AuthAssignment::model()->refreshMetaData();
         ProfileField::model()->refreshMetaData();
         Profile::model()->refreshMetaData();
         Zakaz::model()->refreshMetaData();
         ZakazParts::model()->refreshMetaData();
         Events::model()->refreshMetaData();
         Templates::model()->refreshMetaData();
         Emails::model()->refreshMetaData();
         self::executor();
         self::manager();
         self::send_deffered_emails();
     }
 }
Beispiel #14
0
 /**
  * This is the default 'index' action that is invoked
  * when an action is not explicitly requested by users.
  */
 public function actionIndex()
 {
     $this->layout = '//layouts/box';
     $homeShowNpls = true;
     $rekapAds = null;
     if ($homeShowNpls) {
         $tabelRekapAds = Yii::app()->db->schema->getTable('rekap_ads');
         if (!is_null($tabelRekapAds)) {
             $rekapAds = new RekapAds('search');
             $rekapAds->unsetAttributes();
             /* Tampilkan yang sisa hari < 7 hari */
             $rekapAds->setAttribute('sisa_hari', '< 7');
         }
     }
     if (Yii::app()->user->isGuest) {
         $this->redirect($this->createUrl('/app/login'));
     } else {
         $roles = AuthAssignment::model()->assignedList(Yii::app()->user->id);
         $this->render('index', array('roles' => $roles, 'rekapAds' => $rekapAds));
     }
 }
 public function actionAssign($id = null)
 {
     $user = User::model()->findByPk((int) $id);
     if (!$user) {
         $this->redirect(['userList']);
     }
     if (Yii::app()->getRequest()->isPostRequest) {
         /* получение названий ролей, которые есть в базе */
         $existingRoles = Yii::app()->db->createCommand('SELECT name FROM {{user_user_auth_item}}')->queryColumn();
         $transaction = Yii::app()->db->beginTransaction();
         try {
             AuthAssignment::model()->deleteAll('userid = :userid', [':userid' => (int) $user->id]);
             // убираем дубликаты и несуществующие роли
             $roles = array_intersect(array_unique((array) Yii::app()->getRequest()->getPost('AuthItem')), $existingRoles);
             foreach ($roles as $op) {
                 $model = new AuthAssignment();
                 $model->setAttributes(['userid' => $user->id, 'itemname' => $op]);
                 if (!$model->save()) {
                     throw new CDbException(Yii::t('RbacModule.rbac', 'There is an error occurred when saving data!'));
                 }
             }
             $transaction->commit();
             Yii::app()->getUser()->setFlash(yupe\widgets\YFlashMessages::SUCCESS_MESSAGE, Yii::t('RbacModule.rbac', 'Data was updated!'));
             /*сброс кэша меню*/
             Yii::app()->getCache()->delete('YAdminPanel::' . $id . '::' . Yii::app()->getLanguage());
             /*сброс кеша прав*/
             Yii::app()->getCache()->delete(Yii::app()->getUser()->rbacCacheNameSpace . $id);
             $this->redirect(['assign', 'id' => $user->id]);
         } catch (Exception $e) {
             Yii::app()->getUser()->setFlash(yupe\widgets\YFlashMessages::ERROR_MESSAGE, $e->getMessage());
             $transaction->rollback();
         }
     }
     $rbacTree = new RbacTree($user);
     $tree = $rbacTree->getTreeRoles();
     $this->render('assign', ['tree' => $tree, 'model' => $user]);
 }
 public function actionNewgroup()
 {
     $this->module->registerConfig($this->getAction()->getId());
     $cs = $this->module->getClientScript();
     $cs->registerScriptFile($this->module->getAssetsUrl() . '/js/compose.js');
     $cs->registerScriptFile($this->module->getAssetsUrl() . '/js/jquery.combobox.contacts.js');
     $js = '$(".mailbox-compose").yiiMailboxCompose(' . $this->module->getOptions() . ");";
     $cs->registerScript('mailbox-js', $js, CClientScript::POS_READY);
     if (!$this->module->authManager && (!$this->module->sendMsgs || $this->module->readOnly && !$this->module->isAdmin())) {
         $this->redirect(array('message/inbox'));
     }
     if (isset($_POST['Mailbox']['to']) and $_POST['Mailbox']['to'] != NULL) {
         $users = AuthAssignment::model()->findAllByAttributes(array('itemname' => $_POST['Mailbox']['to']));
         if ($users != NULL) {
             foreach ($users as $user) {
                 $t = time();
                 $conv = new Mailbox();
                 $conv->subject = $_POST['Mailbox']['subject'] ? $_POST['Mailbox']['subject'] : $this->module->defaultSubject;
                 $conv->to = $user->userid;
                 $conv->initiator_id = $this->module->getUserId();
                 $conv->interlocutor_id = $user->userid;
                 if ($conv->interlocutor_id && $conv->initiator_id == $conv->interlocutor_id) {
                     $conv->addError('to', "Can't send message to self!");
                 }
                 if (!$this->module->isAdmin() && $conv->interlocutor_id == $this->module->newsUserId) {
                     $conv->addError('to', "User not found?");
                 }
                 // check user-to-user perms
                 if (!$conv->hasErrors() && !$this->module->userToUser && !$this->module->isAdmin()) {
                     if (!$this->module->isAdmin($conv->to)) {
                         $conv->addError('to', "Invalid user!");
                     }
                 }
                 $conv->modified = $t;
                 $conv->bm_read = Mailbox::INITIATOR_FLAG;
                 if ($this->module->isAdmin()) {
                     $msg = new Message('admin');
                 } else {
                     $msg = new Message('user');
                 }
                 $msg->text = $_POST['Message']['text'];
                 $validate = $conv->validate(array('text'), false);
                 // html purify
                 $msg->created = $t;
                 $msg->sender_id = $conv->initiator_id;
                 $msg->recipient_id = $conv->interlocutor_id;
                 if ($this->module->checksums) {
                     $msg->crc64 = Message::crc64($msg->text);
                     // 64bit INT
                 } else {
                     $msg->crc64 = 0;
                 }
                 // Validate
                 $validate = $conv->validate(null, false);
                 // don't clear errors
                 $validate = $msg->validate() && $validate;
                 if ($validate) {
                     $conv->save();
                     $msg->conversation_id = $conv->conversation_id;
                     $msg->save();
                 }
                 Yii::app()->user->setFlash('success', "Message has been sent!");
             }
             $this->redirect(array('message/inbox'));
         } else {
             Yii::app()->user->setFlash('error', "Error sending message!");
             Yii::app()->user->setFlash('success', "Check Sent Mail");
         }
     } else {
         $conv = new Mailbox();
         if (isset($_GET['id'])) {
             $conv->to = $this->module->getUserName($_GET['id']);
         } elseif (isset($_GET['to'])) {
             $conv->to = $_GET['to'];
         } else {
             $conv->to = '';
         }
         $msg = new Message();
     }
     $this->render('composetogroup', array('conv' => $conv, 'msg' => $msg));
 }
 /**
  * Deletes a particular model.
  * If deletion is successful, the browser will be redirected to the 'index' page.
  */
 public function actionDelete()
 {
     if (Yii::app()->request->isPostRequest) {
         // we only allow deletion via POST request
         $model = $this->loadModel();
         $profile = Profile::model()->findByPk($model->id);
         $AuthAssignment = AuthAssignment::model()->findByAttributes(array('userid' => $model->id));
         if ($AuthAssignment) {
             $AuthAssignment->delete();
         }
         if ($profile) {
             $profile->delete();
         }
         $model->delete();
         // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
         if (!isset($_POST['ajax'])) {
             $this->redirect(array('/user/admin'));
         }
     } else {
         throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
     }
 }
 public function actionAssign($id)
 {
     $user = Users::model()->findByPk((int) $id);
     if (!$user) {
         throw new CHttpException(404);
     }
     $items = AuthItem::model()->findAll(array('order' => 'type DESC'));
     $itemsData = CHtml::listData(AuthItemChild::model()->findAll(), 'child', 'parent');
     if (Yii::app()->request->isPostRequest && count($_POST)) {
         $itemsArray = CHtml::listData($items, 'name', 'description');
         $transaction = Yii::app()->db->beginTransaction();
         try {
             if (count($_POST)) {
                 AuthAssignment::model()->deleteAll('userid = :userid', array(':userid' => (int) $user->id));
                 foreach ($_POST as $op => $val) {
                     if (!isset($itemsArray[$op])) {
                         continue;
                     }
                     $model = new AuthAssignment();
                     $model->setAttributes(array('userid' => $user->id, 'itemname' => $op));
                     if (!$model->save()) {
                         throw new CDbException('При сохранении произошла ошибка!');
                     }
                 }
             }
             $transaction->commit();
             Yii::app()->user->setFlash('notice', 'Данные обновлены!');
             $this->redirect(array('assign', 'id' => $user->id));
         } catch (Exception $e) {
             Yii::app()->user->setFlash('error', $e->getMessage());
             $transaction->rollback();
         }
     }
     //построить дерево
     $tree = array();
     foreach ($items as $item) {
         if ($item->type === AuthItem::TYPE_ROLE && !isset($tree[$item->name])) {
             $tree[$item->name] = array('text' => CHtml::checkBox($item->name, Yii::app()->user->checkAccess($item->name, $user->id), array('name' => 'operations', 'class' => 'root')) . $item->description . " ({$item->getType()})");
         }
         if ($item->type === AuthItem::TYPE_TASK) {
             // проверить есть ли для нее родитель
             if (isset($itemsData[$item->name]) && $itemsData[$item->name]) {
                 $tree[$itemsData[$item->name]]['children'][$item->name] = array('text' => CHtml::checkBox($item->name, Yii::app()->user->checkAccess($item->name, $user->id), array('name' => 'operations', 'class' => 'root')) . $item->description . " ({$item->getType()})");
             } else {
                 $tree[$item->name] = array('text' => CHtml::checkBox($item->name, Yii::app()->user->checkAccess($item->name, $user->id), array('name' => 'operations')) . $item->description . " ({$item->getType()})");
             }
         }
         if ($item->type == AuthItem::TYPE_OPERATION) {
             if (isset($itemsData[$item->name]) && $itemsData[$item->name]) {
                 // задача по своей сути
                 $parent = $itemsData[$item->name];
                 if (isset($itemsData[$parent]) && $itemsData[$parent]) {
                     $tree[$itemsData[$parent]]['children'][$itemsData[$item->name]]['children'][$item->name] = array('text' => CHtml::checkBox($item->name, Yii::app()->user->checkAccess($item->name, $user->id), array('name' => 'operations')) . $item->description . " ({$item->getType()})");
                 } else {
                     $tree[$itemsData[$item->name]]['children'][$item->name] = array('text' => CHtml::checkBox($item->name, Yii::app()->user->checkAccess($item->name, $user->id), array('name' => 'operations')) . $item->description . " ({$item->getType()})");
                 }
             } else {
                 $tree[$item->name] = array('text' => CHtml::checkBox($item->name, Yii::app()->user->checkAccess($item->name, $user->id), array('name' => 'operations')) . $item->description . " ({$item->getType()})");
             }
         }
     }
     $this->render('assign', array('tree' => $tree, 'model' => $user));
 }
Beispiel #19
0
 public function afterDelete()
 {
     AuthAssignment::model()->deleteAll('userid=' . $this->id);
     return parent::afterDelete();
 }
	/**
	 * Manages all models.
	 */
	public function actionTransferemployee()
	{
		$model=new EmployeeTransaction('transferemployee');
		$info=new EmployeeInfo;
		$user =new User;
		$photo =new EmployeePhotos;
		$address=new EmployeeAddress;
		$lang=new LanguagesKnown;
		$ass_comp = new assignCompanyUserTable;
		$auth_assign = new AuthAssignment;

		$this->performAjaxValidation(array($info,$model,$user));
		if(!empty($_POST['user_id1']))
		{
			$model->attributes=$_POST['EmployeeTransaction'];
			$info->attributes=$_POST['EmployeeInfo'];
			
		
			$trans_id = $_POST['user_id1'];
			$old_model = EmployeeTransaction::model()->resetScope()->findByPk($trans_id);
			$old_info = EmployeeInfo::model()->findByPk($old_model->employee_transaction_employee_id);
			$old_info->transfer_left_remarks= $_POST['EmployeeTransaction']['transfer_left_remarks'];
			$old_info->employee_left_transfer_date = new CDbExpression('NOW()');
			$old_info->save(false);

			$old_model->employee_status = 1;
			$old_model->save();


			$user = User::model()->findByPk($old_model->employee_transaction_user_id);
			
			$user->user_created_by =  Yii::app()->user->id;
			$user->user_creation_date = new CDbExpression('NOW()');
			$user->user_organization_id = $_POST['EmployeeTransaction']['employee_transaction_organization_id'];
			
			if($user->save())
			{
			$org_data = Organization::model()->findByPk($_POST['EmployeeTransaction']['employee_transaction_organization_id']);
			$org_name = $org_data->organization_name;
			$org_arr = explode(' ',$org_name);
			$bizrule = 'return Yii::app()->user->getState("org_id")=='.$_POST['EmployeeTransaction']['employee_transaction_organization_id'].";";
			$var_data = serialize($_POST['EmployeeTransaction']['employee_transaction_organization_id']);
			$suffix_lab = '';
			foreach($org_arr as $list)
				$suffix_lab .= $list[0];


			$auth_assign->itemname = 'Employee of '.$suffix_lab;
			$check = AuthAssignment::model()->findByAttributes(array('itemname'=>$auth_assign->itemname,'userid' => $user->user_id,'data' =>$var_data));
			if(empty($check)){
			$auth_assign->userid = $user->user_id;
			$auth_assign->bizrule = $bizrule;
			$auth_assign->data = $var_data;
			
			$auth_assign->save();
			}

			$ass_comp->assign_user_id = $user->user_id;
			$ass_comp->assign_role_id = 3;
			$ass_comp->assign_org_id = $_POST['EmployeeTransaction']['employee_transaction_organization_id'];
			$ass_comp->assign_created_by = Yii::app()->user->id;
			$ass_comp->assign_creation_date = new CDbExpression('NOW()');
			$ass_comp->save();

			$info = $old_info;
			$info->employee_joining_date = new CDbExpression('NOW()');
			$info->employee_type = $_POST['EmployeeInfo']['employee_type'];
			$info->employee_attendance_card_id = '';
			$info->employee_created_by =  Yii::app()->user->id;
			$info->employee_creation_date = new CDbExpression('NOW()');
			$info->employee_left_transfer_date = NULL;
			$info->employee_id = null;
			$info->setIsNewRecord(true);
			$info->save(false);
			
			$model = $old_model;
			$model->employee_transaction_id = null;
			$model->setIsNewRecord(true);
			$model->employee_transaction_user_id = $user->user_id;
			$model->employee_transaction_employee_id = $info->employee_id;
			$model->employee_transaction_shift_id = $_POST['EmployeeTransaction']['employee_transaction_shift_id'];
			$model->employee_transaction_designation_id = $_POST['EmployeeTransaction']['employee_transaction_designation_id']; 
			$model->employee_transaction_department_id = $_POST['EmployeeTransaction']['employee_transaction_department_id'];
			$model->employee_transaction_organization_id = $_POST['EmployeeTransaction']['employee_transaction_organization_id'];
			$model->employee_status = 0;
			$model->save(false);
			EmployeeInfo::model()->updateByPk($model->employee_transaction_employee_id, array('employee_info_transaction_id'=>$model->employee_transaction_id));
			Yii::app()->user->setFlash('success',"Transfer of ".$info->employee_first_name.' to '.$org_name.' successfully.!');
			$this->redirect(array('employeeTransaction/admin'));	
			}
			
		}
		$this->render('transfer_employee',array(
			'model'=>$model,'info'=>$info,'user'=>$user,
		));

	}
Beispiel #21
0
 public function actionDeleteMember($id)
 {
     if (!Yii::app()->user->checkAccess('Admin')) {
         throw new CHttpException(403, 'You are not authorized to perform this action.');
     }
     $member = Member::model()->findByPk($id);
     $account = Account::model()->find(array('condition' => 'id=' . $member->account_id));
     $auth = AuthAssignment::model()->find(array('condition' => 'userid=' . $member->account_id));
     if ($member->delete() && $account->delete() && $auth->delete()) {
         $this->redirect(array('member'));
     }
 }
Beispiel #22
0
 /**
  * @desc eject assignment or edit assignment data
  */
 public function actionEdit()
 {
     $colUsername = Yii::app()->controller->module->columnUsername;
     $colUserid = Yii::app()->controller->module->columnUserid;
     $this->checkAccess('RbacAssignmentViewer', true);
     if (isset($_GET['userid'])) {
         if (in_array($_GET['userid'], $this->protectedUsers)) {
             $this->messageWarnings[] = "Warning! User is protected by Controller";
         }
         if ($this->editUser = User::model()->findByAttributes(array($colUserid => $_GET['userid']))) {
             $this->assignments = AuthAssignment::model()->findAllByAttributes(array('userid' => $this->editUser->{$colUserid}));
             $this->_getSearchFields();
             $this->doRender('edit', array('user' => $this->editUser, 'assignments' => $this->assignments, 'getVars' => $this->getGetVars()));
         } else {
             throw new CHttpException("Selected User " . CHtml::encode($_GET['username']) . " does not exist");
         }
     } elseif (isset($_POST['userid']) && isset($_POST['assignments']) && is_array($_POST['assignments'])) {
         $this->checkAccess('RbacAssignmentEditor', true);
         if (in_array($_POST['userid'], $this->protectedUsers)) {
             $this->messageErrors[] = "Sorry, User is protected by Controller";
             $this->actionIndex();
         }
         if ($this->editUser = User::model()->findByAttributes(array($colUserid => $_POST['userid']))) {
             foreach ($_POST['assignments'] as $itemName => $values) {
                 $modelAssign = AuthAssignment::model()->findByAttributes(array('itemname' => $itemName, 'userid' => $this->editUser->{$colUserid}));
                 $modelAssign->attributes = array('bizrule' => $values['bizrule'], 'data' => $values['data']);
                 if ($modelAssign->validate()) {
                     $modelAssign->save();
                     $this->messageSuccess[] = "Assignment {$itemName} successfull updated.";
                 }
             }
             $this->_getSearchFields();
             $this->doRender('edit', array('user' => $this->editUser, 'assignments' => $this->assignments = AuthAssignment::model()->findAllByAttributes(array('userid' => $this->editUser->{$colUserid})), 'getVars' => $this->getGetVars()));
             Yii::app()->end();
         } else {
             throw new CHttpException("User " . CHtml::encode($_POST['username']) . " does not exist");
         }
     } else {
         throw new CHttpException("Not enougth Data for Edit Assignments found");
     }
 }
 protected function getAssigned($name)
 {
     return AuthAssignment::model()->findAll('itemname=:name', array(':name' => $name), array('order' => 'userid'));
 }
Beispiel #24
0
 /**
  * 
  * @desc 
  * @param unknown_type $model
  * @param unknown_type $attributes
  * @param unknown_type $oldName
  */
 private function _updateItem($attributes, $oldName)
 {
     if (in_array($oldName, $this->protectedItems) || in_array($attributes['name'], $this->protectedItems)) {
         $this->messageErrors[] = "Sorry, Item is protected by Controller";
         $this->actionIndex();
     }
     if (!($item = AuthItem::model()->findByAttributes(array('name' => $oldName)))) {
         $this->messageErrors[] = "Edit Error: Update Item does not exist";
         $this->actionIndex();
     }
     if ($attributes['type'] == 0 && $item->type > 0) {
         if (count(AuthItemChild::model()->findAllByAttributes(array('parent' => $oldName)))) {
             $this->messageErrors[] = "Type <i>Action</i> can't have Childs.<br/>Please eject Childs from <i>{$oldName}</i> before switch type to <i>Operation</i>";
             $this->editItem = $item;
             $this->actionIndex();
         }
     }
     if ($attributes['name'] != $oldName) {
         if (AuthItem::model()->findByAttributes(array('name' => $attributes['name']))) {
             $this->messageErrors[] = "Create Error: New Item <i>{$_POST['editItem']['name']}</i> already exists";
             //
             return;
         }
         $item->attributes = $attributes;
         $item->save();
         // update RBAC-Tree AuthItemChild bindings in parent
         $newName = $attributes['name'];
         $treeItems = AuthItemChild::model()->findAllByAttributes(array('parent' => $oldName));
         foreach ($treeItems as $treeItem) {
             $treeItem->parent = $newName;
             $treeItem->save();
         }
         // update RBAC-Tree AuthItemChild bindings in child
         $treeItems = AuthItemChild::model()->findAllByAttributes(array('child' => $oldName));
         foreach ($treeItems as $treeItem) {
             $treeItem->child = $newName;
             $treeItem->save();
         }
         // update AuthAssignment bindings in itemname
         $assignments = AuthAssignment::model()->findAllByAttributes(array('itemname' => $oldName));
         foreach ($assignments as $assignment) {
             $assignment->itemname = $newName;
             $assignment->save();
         }
     } else {
         // simple update if primary key is same
         $item->attributes = $attributes;
         $item->save();
     }
     $this->messageSuccess[] = "Item " . (!isset($newName) ? $oldName : $newName) . " successfull updated.";
 }
Beispiel #25
0
 /**
  * Delete information of the User with Afer Delete
  */
 protected function afterDelete()
 {
     parent::afterDelete();
     AuthAssignment::model()->deleteAll('userid = :uid', array(':uid' => $this->user_id));
 }
Beispiel #26
0
    public function getRole()
    {
        $assigment = AuthAssignment::model()->findByAttributes(array(
            'userid' => $this->id
        ));

        if (!$assigment) {
            $assigment = new AuthAssignment();
            $assigment->itemname = AuthItem::ROLE_DEFAULT;
            $assigment->userid = $this->id;
            $assigment->save();
        }

        return $assigment->role;
    }
 public function afterDelete($event)
 {
     $owner = $this->getOwner();
     $auth = Yii::app()->authManager;
     AuthAssignment::model()->deleteAll('userid=:userid', array(':userid' => $owner->getPrimaryKey()));
 }
 /**
  * Returns the data model based on the primary key given in the GET variable.
  * If the data model is not found, an HTTP exception will be raised.
  * @param integer the ID of the model to be loaded
  */
 public function loadModel($id)
 {
     $model = AuthAssignment::model()->findByPk($id);
     if ($model === null) {
         throw new CHttpException(404, 'The requested page does not exist.');
     }
     return $model;
 }
Beispiel #29
0
 /**
  * 
  * @desc check if User is assigned to an AuthItem
  * @param string $username from table user.username
  * @param string $itemname from table authAssignment.itemname
  * @return boolean
  */
 public function userIsAssigned($username, $itemname)
 {
     return AuthAssignment::model()->findByAttributes(array('unserid' => $username, 'itemname' => $itemname)) !== null ? true : false;
 }
 /**
  * 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)
 {
     $transaction = Yii::app()->db->beginTransaction();
     try {
         $model = $this->loadModel($id);
         if (isset($_POST['User'])) {
             $model->attributes = $_POST['User'];
             if ($model->save()) {
                 $authAsign = AuthAssignment::model()->findByAttributes(array('userid' => $model->nick));
                 $authAsign->itemname = $model->role;
                 if ($authAsign->save()) {
                     $this->audit->logAudit(Yii::app()->user->id, new DateTime(), AppConstants::AUDIT_OBJECT_USER, AppConstants::AUDIT_OPERATION_EDIT, $model->nick);
                     $this->render('/site/successfullOperation', array('header' => 'Usuario modificado con &eacute;xito', 'message' => 'Haga click en volver para regresar a la gestión de usuarios', 'returnUrl' => Yii::app()->createUrl('user/admin'), 'viewUrl' => Yii::app()->createUrl("user/view", array("id" => $model->nick))));
                     $transaction->commit();
                     return;
                 } else {
                     $transaction->rollback();
                 }
             }
         }
         $this->render('update', array('model' => $model));
     } catch (Exception $exc) {
         Yii::log($exc->getMessage(), DBLog::LOG_LEVEL_ERROR);
         $transaction->rollback();
     }
 }