/**
  * Creates a new model.
  * If creation is successful, the browser will be redirected to the 'view' page.
  */
 public function actionCreate()
 {
     $model = new Registration();
     // Uncomment the following line if AJAX validation is needed
     // $this->performAjaxValidation($model);
     if (isset($_POST['Registration'])) {
         $model->attributes = $_POST['Registration'];
         if ($model->save()) {
             $user = new User();
             $auth_assign = new AuthAssignment();
             $user->user_organization_email_id = $model->email;
             $my_string = $this->rand_string(7);
             $user->user_password = md5($my_string . $my_string);
             $user->user_type = 'admin';
             $user->user_created_by = 1;
             $user->user_creation_date = new CDbExpression('NOW()');
             $user->user_organization_id = 1;
             if ($user->save()) {
                 $auth_assign->itemname = 'SuperAdmin';
                 $auth_assign->userid = $user->user_id;
                 $auth_assign->save(false);
                 $request_url = 'http://www.rudrasoftech.com/register-script.php?first_name=' . $model->first_name . '&last_name=' . $model->last_name . '&email=' . $model->email . '&country_code=' . $model->country_code . '&mobile=' . $model->mobile . '&pass='******'site/createOrg'));
         }
     }
     $this->render('create', array('model' => $model));
 }
 /**
  * Creates a new model.
  * If creation is successful, the browser will be redirected to the 'view' page.
  */
 public function actionCreate()
 {
     $model = new EmployeeTransaction();
     $info = new EmployeeInfo();
     $user = new User();
     $photo = new EmployeePhotos();
     $address = new EmployeeAddress();
     $lang = new LanguagesKnown();
     $auth_assign = new AuthAssignment();
     // Uncomment the following line if AJAX validation is needed
     $this->performAjaxValidation(array($info, $model, $user));
     if (!empty($_POST['EmployeeTransaction']) || !empty($_POST['EmployeeInfo'])) {
         $model->attributes = $_POST['EmployeeTransaction'];
         $info->attributes = $_POST['EmployeeInfo'];
         $user->attributes = $_POST['User'];
         $doa = $info->employee_joining_date;
         $dateofadmission = date("Y-m-d", strtotime($doa));
         $info->employee_joining_date = $dateofadmission;
         /** fix the attendece id card length */
         $cardid_length = strlen((string) $info->employee_attendance_card_id);
         $cardid = $info->employee_attendance_card_id;
         $digit = 0;
         $diff = 10 - $cardid_length;
         for ($i = 1; $i <= $diff; $i++) {
             $cardid = $digit . $cardid;
         }
         $info->employee_attendance_card_id = $cardid;
         $info->employee_private_email = strtolower($user->user_organization_email_id);
         $info->employee_created_by = Yii::app()->user->id;
         $info->employee_creation_date = new CDbExpression('NOW()');
         $user->user_organization_email_id = $info->employee_private_email;
         $user->user_password = md5($info->employee_private_email . $info->employee_private_email);
         $user->user_created_by = Yii::app()->user->id;
         $user->user_creation_date = new CDbExpression('NOW()');
         //$user->user_organization_id = Yii::app()->user->getState('org_id');
         $user->user_type = "employee";
         if ($info->save(false)) {
             $user->save(false);
             $address->save(false);
             $lang->save(false);
             $photo->employee_photos_path = "no-images";
             $photo->save(false);
         }
         $model->employee_transaction_employee_id = $info->employee_id;
         $model->employee_transaction_user_id = $user->user_id;
         $model->employee_transaction_emp_photos_id = $photo->employee_photos_id;
         $model->employee_transaction_emp_address_id = $address->employee_address_id;
         $model->employee_transaction_languages_known_id = $lang->languages_known_id;
         $model->employee_transaction_organization_id = Yii::app()->user->getState('org_id');
         $model->employee_status = 0;
         $model->save(false);
         // not false because it hasn't been validated
         $auth_assign->itemname = 'Employee';
         $auth_assign->userid = $user->user_id;
         $auth_assign->save();
         $this->redirect(array('update', 'id' => $model->employee_transaction_id));
     } else {
         $this->render('create', array('model' => $model, 'info' => $info, 'user' => $user));
     }
 }
 public function authenticate($uloginModel = null, $role = 'Customer')
 {
     $criteria = new CDbCriteria();
     $criteria->condition = 'identity=:identity AND network=:network';
     $criteria->params = array(':identity' => $uloginModel->identity, ':network' => $uloginModel->network);
     $user = User::model()->find($criteria);
     if (null == $user) {
         $criteria = new CDbCriteria();
         $criteria->condition = 'email=:email';
         $criteria->params = array(':email' => $uloginModel->email);
         $user = User::model()->find($criteria);
         if (null == $user) {
             $user = new User();
         }
         $user->scenario = 'social_network';
         $user->identity = $uloginModel->identity;
         $user->network = $uloginModel->network;
         $user->email = $uloginModel->email;
         $user->full_name = $uloginModel->full_name;
         $user->status = 1;
         $user->save();
         $AuthAssignment = new AuthAssignment();
         $AuthAssignment->attributes = array('itemname' => $role, 'userid' => $user->id);
         $AuthAssignment->save();
     }
     $this->id = $user->id;
     $this->name = $user->full_name;
     $this->isAuthenticated = true;
     return true;
 }
 public function actionUbah($userid)
 {
     $model = new AuthAssignment('search');
     $model->unsetAttributes();
     $model->setAttribute('userid', '=' . $userid);
     $user = User::model()->findByPk($userid);
     $this->render('ubah', array('user' => $user, 'model' => $model, 'authItem' => AuthItem::model()->listNotAssignedItem($userid)));
 }
Esempio n. 5
0
 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();
 }
 /**
  * Creates a new model.
  * If creation is successful, the browser will be redirected to the 'view' page.
  */
 public function actionCreate()
 {
     $model = new StudentTransaction();
     $info = new StudentInfo();
     $user = new User();
     $photo = new StudentPhotos();
     $address = new StudentAddress();
     $lang = new LanguagesKnown();
     $auth_assign = new AuthAssignment();
     // Uncomment the following line if AJAX validation is needed
     $this->performAjaxValidation(array($info, $model, $user));
     if (!empty($_POST['StudentTransaction']) || !empty($_POST['StudentInfo'])) {
         //print_r($_POST['StudentTransaction']); exit;
         $model->attributes = $_POST['StudentTransaction'];
         $info->attributes = $_POST['StudentInfo'];
         $user->attributes = $_POST['User'];
         $info->student_created_by = Yii::app()->user->id;
         $info->student_creation_date = new CDbExpression('NOW()');
         $info->student_email_id_1 = strtolower($user->user_organization_email_id);
         $info->student_adm_date = date('Y-m-d', strtotime($_POST['StudentInfo']['student_adm_date']));
         $user->user_organization_email_id = strtolower($info->student_email_id_1);
         $user->user_password = md5($info->student_email_id_1 . $info->student_email_id_1);
         $user->user_created_by = Yii::app()->user->id;
         $user->user_creation_date = new CDbExpression('NOW()');
         $user->user_organization_id = Yii::app()->user->getState('org_id');
         $user->user_type = "student";
         if ($info->save(false)) {
             $user->save(false);
             $address->save(false);
             $lang->save(false);
             $photo->student_photos_path = "no-images";
             $photo->save();
         }
         if (empty($model->student_transaction_batch_id)) {
             $model->student_transaction_batch_id = 0;
         }
         $model->student_transaction_languages_known_id = $lang->languages_known_id;
         $model->student_transaction_student_id = $info->student_id;
         $model->student_transaction_user_id = $user->user_id;
         $model->student_transaction_student_address_id = $address->student_address_id;
         $model->student_transaction_student_photos_id = $photo->student_photos_id;
         $model->student_transaction_organization_id = Yii::app()->user->getState('org_id');
         $model->save();
         $auth_assign->itemname = 'Student';
         $auth_assign->userid = $user->user_id;
         $auth_assign->save();
         StudentInfo::model()->updateByPk($model->student_transaction_student_id, array('student_info_transaction_id' => $model->student_transaction_id));
         $this->redirect(array('admin'));
     } else {
         $this->render('create', array('model' => $model, 'info' => $info, 'user' => $user));
     }
 }
 /**
  * Registration user
  */
 public function actionRegistration()
 {
     $model = new RegistrationForm();
     if (isset($_GET['role']) && $_GET['role'] == 'Customer') {
         $role = 'Customer';
     } elseif (isset($_GET['role']) && $_GET['role'] == 'Author') {
         $role = 'Author';
     } elseif (isset($_GET['role']) && $_GET['role'] == 'Manager') {
         $role = 'Manager';
     } else {
         $role = 'Customer';
     }
     if (isset($_POST['ajax']) && $_POST['ajax'] === 'simple-registration-form') {
         echo UActiveForm::validate($model);
         Yii::app()->end();
     }
     if (Yii::app()->user->id && (!Yii::app()->user->hasFlash('reg_success') && !Yii::app()->user->hasFlash('reg_failed'))) {
         $this->redirect(Yii::app()->controller->module->profileUrl);
     } else {
         if (isset($_POST['RegistrationForm'])) {
             $model->attributes = $_POST['RegistrationForm'];
             if ($model->validate()) {
                 $soucePassword = $this->generate_password(8);
                 $model->password = UserModule::encrypting($soucePassword);
                 $model->superuser = 0;
                 $model->status = 1;
                 $model->username = $model->email;
                 if ($model->save()) {
                     $AuthAssignment = new AuthAssignment();
                     $AuthAssignment->attributes = array('itemname' => $role, 'userid' => $model->id);
                     $AuthAssignment->save();
                     $login_url = '<a href="' . $this->createAbsoluteUrl('/user/login') . '">' . Yii::app()->name . '</a>';
                     UserModule::sendMail($model->email, UserModule::t("You registered from {site_name}", array('{site_name}' => Yii::app()->name)), UserModule::t("You have registred from {login_url}<br /><br />Your password: {pass}", array('{login_url}' => $login_url, '{pass}' => $soucePassword)));
                     $identity = new UserIdentity($model->username, $soucePassword);
                     $identity->authenticate();
                     Yii::app()->user->login($identity, 0);
                     //$this->redirect(Yii::app()->controller->module->returnUrl);
                     Yii::app()->user->setFlash('reg_success', UserModule::t("Thank you for your registration. Password has been sent to your e-mail. Please check your e-mail ({{login}}) before start.", ['{{login}}' => $model->email]));
                     $this->refresh();
                 } else {
                     Yii::app()->user->setFlash('reg_failed', UserModule::t("Sorry, something wrong... :("));
                     $this->refresh();
                 }
             }
         }
         Yii::app()->theme = 'client';
         $this->render('/user/registration', array('model' => $model, 'role' => $role));
     }
 }
 public function actionCreateOrg()
 {
     $org = Organization::model()->count();
     if ($org == 0) {
         $this->layout = 'installation_layout';
         $model = new Organization();
         $user = new User();
         $auth_assign = new AuthAssignment();
         // Uncomment the following line if AJAX validation is needed
         $this->performAjaxValidation($model);
         if (isset($_POST['Organization']['organization_name']) && !empty($_POST['Organization']['phone']) && !empty($_POST['Organization']['email'])) {
             $country_model = new Country();
             $country_model->name = $_POST['Organization']['country'];
             $country_model->save();
             $state_model = new State();
             $state_model->state_name = $_POST['Organization']['state'];
             $state_model->country_id = $country_model->id;
             $state_model->save();
             $city_model = new City();
             $city_model->city_name = $_POST['Organization']['city'];
             $city_model->country_id = $country_model->id;
             $city_model->state_id = $state_model->state_id;
             $city_model->save();
             $model->attributes = $_POST['Organization'];
             $model->organization_created_by = 1;
             $model->organization_creation_date = new CDbExpression('NOW()');
             $model->city = $city_model->city_id;
             $model->state = $state_model->state_id;
             $model->country = $country_model->id;
             if ($model->save(false)) {
                 $user->user_organization_email_id = $model->email;
                 $user->user_password = md5($model->email . $model->email);
                 $user->user_type = 'admin';
                 $user->user_created_by = 1;
                 $user->user_creation_date = new CDbExpression('NOW()');
                 $user->user_organization_id = $model->organization_id;
                 $user->save();
                 $auth_assign->itemname = 'SuperAdmin';
                 $auth_assign->userid = $user->user_id;
                 $auth_assign->save(false);
                 $this->redirect(array('redirectLogin'));
             }
         }
         $this->render('create_org', array('model' => $model));
     } else {
         Yii::app()->user->logout();
         $this->redirect(array('login'));
     }
 }
Esempio n. 9
0
 public function createUser(RegistrationForm $form)
 {
     $transaction = Yii::app()->getDb()->beginTransaction();
     try {
         $user = new User();
         $password = rand(1000000, 9999999);
         $Company = new Company();
         if ($form->organization_name) {
             $Company->name = $form->organization_name;
         }
         $Company->create = new CDbExpression('NOW()');
         $Company->save();
         $user->email = $form->email;
         $user->contact_phone = $form->phone;
         $user->contact_phone_prefix = $form->prefphone;
         $user->company_id = $Company->id;
         $user->status = User::STATUS_ACTIVE;
         //Сделать автопроверку выписки
         $user->setAttribute('hash', $this->hasher->hashPassword($password));
         if ($user->save() && ($token = $this->tokenStorage->createAccountActivationToken($user)) !== false) {
             $user->sendCRMRegistration();
             User::savePost($user);
             \Yii::import('application.modules.rbac.models.*');
             $model = new AuthAssignment();
             //$model->setAttributes(['userid' => $user->id,'itemname' => 'standart']); //Назаначаем роль владельца компании без инн
             //                $model->setAttributes(['userid' => $user->id,'itemname' => 'own_wo_inn']); //Назаначаем роль владельца компании без инн
             $model->setAttributes(['userid' => $user->id, 'itemname' => 'owner']);
             //Назаначаем роль владельца компании без инн
             if (!$model->save()) {
                 throw new CDbException(Yii::t('UserModule.rbac', 'There is an error occurred when saving data!'));
             }
             Yii::app()->eventManager->fire(UserEvents::SUCCESS_REGISTRATION, new UserRegistrationEvent($form, $user, $token, $password));
             Yii::log(Yii::t('UserModule.user', 'Account {nick_name} was created', ['{nick_name}' => $user->email]), CLogger::LEVEL_INFO, UserModule::$logCategory);
             $transaction->commit();
             $LoginForm = new LoginForm();
             $LoginForm->email = $user->email;
             $LoginForm->password = $password;
             Yii::app()->authenticationManager->login($LoginForm, Yii::app()->getUser(), Yii::app()->getRequest());
             return $user;
         }
         throw new CException(Yii::t('UserModule.user', 'Error creating account!'));
     } catch (Exception $e) {
         Yii::log(Yii::t('UserModule.user', 'Error {error} account creating!', ['{error}' => $e->__toString()]), CLogger::LEVEL_INFO, UserModule::$logCategory);
         $transaction->rollback();
         Yii::app()->eventManager->fire(UserEvents::FAILURE_REGISTRATION, new UserRegistrationEvent($form, $user));
         return false;
     }
 }
 /**
  * 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 actionCreateUser()
 {
     $this->layout = 'select_company_main';
     $model = new User();
     $ass_comp = new assignCompanyUserTable();
     //$model->setScenario('create');
     $auth_assign = new AuthAssignment();
     // Uncomment the following line if AJAX validation is needed
     $this->performAjaxValidation($model);
     if (isset($_POST['User'])) {
         $model->attributes = $_POST['User'];
         $model->user_password = md5($model->user_password . $model->user_password);
         $model->user_type = 'admin';
         $model->user_created_by = 1;
         $model->user_creation_date = new CDbExpression('NOW()');
         $model->user_organization_id = $_REQUEST['id'];
         if ($model->save()) {
             $ass_comp->assign_user_id = $model->user_id;
             $ass_comp->assign_org_id = $_REQUEST['id'];
             $ass_comp->assign_created_by = $model->user_id;
             $ass_comp->assign_creation_date = new CDbExpression('NOW()');
             $ass_comp->save();
             $auth_assign->itemname = 'SuperAdmin';
             $auth_assign->userid = $model->user_id;
             $auth_assign->save(false);
             $this->redirect(array('site/redirectLogin'));
         }
     }
     $this->render('create_user', array('model' => $model));
 }
Esempio n. 12
0
 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;
 }
 public function safeUp()
 {
     /* Всем администраторам назначается роль admin */
     $adminRole = new AuthItem();
     $adminRole->name = AuthItem::ROLE_ADMIN;
     $adminRole->description = Yii::t('RbacModule.rbac', 'Admin');
     $adminRole->type = AuthItem::TYPE_ROLE;
     $adminRole->save();
     $admins = User::model()->findAllByAttributes(['access_level' => User::ACCESS_LEVEL_ADMIN]);
     foreach ($admins as $admin) {
         $assign = new AuthAssignment();
         $assign->itemname = $adminRole->name;
         $assign->userid = $admin->id;
         $assign->save();
     }
 }
Esempio n. 14
0
 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;
 }
 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();
 }
Esempio n. 16
0
 function getRole()
 {
     if ($oUser = $this->getModel()) {
         $oAuthAssignment = AuthAssignment::model()->findByattributes(array('userid' => $oUser->id));
         if ($oAuthAssignment) {
             return $oAuthAssignment->itemname;
         }
     }
     return false;
 }
Esempio n. 17
0
 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;
 }
Esempio n. 18
0
 /**
  * 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));
     }
 }
Esempio n. 19
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;
 }
Esempio n. 20
0
 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 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;
 }
Esempio n. 22
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();
     }
 }
Esempio n. 25
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));
     }
 }
Esempio n. 26
0
 public function actionUpdate($id)
 {
     $model = $this->loadModel($id);
     $model->password_c = $model->password;
     $model->scenario = 'Update';
     $old_password = $model->password;
     $form = new Form('users.UserForm', $model);
     unset($form->elements['captcha']);
     $this->performAjaxValidation($model);
     if ($form->submitted('submit')) {
         $model = $form->model;
         if ($model->validate()) {
             if ($_POST['User']['password'] != $old_password) {
                 $model->password = md5($model->password);
             }
             $model->save(false);
             AuthAssignment::updateUserRole($model->id, $_POST['User']['role']);
             //                Implex::refreshXLS(get_class($model));
             $this->redirect(array('view', 'id' => $model->id));
         }
     }
     $this->render('update', array('form' => $form));
 }
Esempio n. 27
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;
 }
Esempio n. 28
0
 /**
  * Delete information of the User with Afer Delete
  */
 protected function afterDelete()
 {
     parent::afterDelete();
     AuthAssignment::model()->deleteAll('userid = :uid', array(':uid' => $this->user_id));
 }
 /**
  * Creates a new model.
  * If creation is successful, the browser will be redirected to the 'view' page.
  */
 public function actionCreate()
 {
     $this->pagename = "Register " . $this->pagename;
     $model = new Users('createUser');
     $transaction = $model->getDbConnection()->beginTransaction();
     // Uncomment the following line if AJAX validation is needed
     // $this->performAjaxValidation($model);
     if (isset($_POST['Users'])) {
         $model->attributes = $_POST['Users'];
         $oldpassword = $model->password;
         $user = Users::model()->find('email=:email and status=0', array(':email' => $model->email));
         if ($user) {
             $model = $user;
         }
         $model->password = $oldpassword;
         $model->password_repeat = $oldpassword;
         $model->status = 1;
         $model->password = md5(trim($model->password));
         $model->key = $model->password;
         $model->password_repeat = $model->password;
         //try {
         if ($model->save()) {
             if (!$user) {
                 $authmodel = new AuthAssignment();
                 $authmodel->itemname = 'manager';
                 $authmodel->userid = $model->id;
             }
             if ($user || $authmodel->save()) {
                 $transaction->commit();
                 $identity = new UserIdentity($model->email, $model->password);
                 $identity->authenticate();
                 Yii::app()->user->login($identity, 0);
                 if (Yii::app()->user->IsGuest) {
                     $this->redirect(Yii::app()->baseUrl . '/site/login');
                 }
                 $this->redirect(Yii::app()->baseUrl . '/appointments/index');
                 //$this->redirect(array('view', 'id' => $model->id));
             } else {
                 $transaction->rollback();
                 $model->password = $oldpassword;
                 $model->password_repeat = $oldpassword;
             }
         }
         //                } catch (Exception $e) {
         //                    $transaction->rollback();
         //                    $model->password=$oldpassword;
         //                    $model->password_repeat=$oldpassword;
         //                }
         //}
     }
     $this->render('create', array('model' => $model));
 }
 public function afterDelete($event)
 {
     $owner = $this->getOwner();
     $auth = Yii::app()->authManager;
     AuthAssignment::model()->deleteAll('userid=:userid', array(':userid' => $owner->getPrimaryKey()));
 }