public function send() { if ($this->_model && $this->_model->objects()->changeActivationKey()) { $app = Mindy::app(); $recoverUrl = $app->urlManager->reverse('user:recover_activate', ['key' => $this->_model->activation_key]); return $app->mail->fromCode('user.recover', $this->_model->email, ['data' => $this->_model, 'username' => $this->_model->username, 'site' => $app->getModule('Sites')->getSite(), 'activation_url' => $app->request->http->absoluteUrl($recoverUrl)]); } return false; }
public function actionChangePassword($pk) { $model = User::objects()->get(['pk' => $pk]); if ($model === null) { $this->error(404); } $form = new ChangePasswordForm(['model' => $model]); $request = $this->getRequest(); if ($request->getIsPost()) { if ($form->populate($_POST, $_FILES)->isValid()) { if ($form->save()) { $this->afterCreate($form); $request->flash->success('Данные успешно сохранены'); $next = $this->getNextRoute($_POST, $form); if ($next) { $request->redirect($next); } else { $request->refresh(); } } else { $request->flash->error('При сохранении данных произошла ошибка, пожалуйста попробуйте выполнить сохранение позже или обратитесь к разработчику проекта, или вашему системному администратору'); } } else { $request->flash->warning('Пожалуйста укажите корректные данные'); } } echo $this->render($this->getTemplate('change_password.html'), ['model' => $model, 'form' => $form, 'breadcrumbs' => $this->fetchBreadcrumbs($model, 'change_password')]); }
/** * @param $username string * @param $email string * @param $hashType null|string * @param $superuser bool */ protected function createUser($username, $email, $hashType = null, $superuser) { if ($username === null) { $username = Console::prompt("Username:"******"Email:"); } $emailValidator = new EmailValidator(true); if (!$emailValidator->validate($email)) { echo "Incorrect email address\n"; exit(1); } $has = User::objects()->filter(['username' => $username])->orFilter(['email' => $email])->get(); if ($has === null) { $password = $this->getPassword(); if ($superuser) { $model = User::objects()->createSuperUser($username, $password, $email, ['hash_type' => $hashType]); } else { $model = User::objects()->createUser($username, $password, $email, ['hash_type' => $hashType]); } if (is_array($model)) { echo implode("\n", $model); exit(1); } else { echo "Created\n"; } exit(0); } else { echo "User already exists\n"; exit(0); } }
public function actionRecover($key = null) { if ($key) { $user = User::objects()->get(['activation_key' => $key]); if ($user === null) { echo $this->json(['status' => false, 'error' => 'User not found']); $this->end(); } $user->password = ''; $user->save(['password']); $form = new ChangePasswordForm(); $form->setModel($user); $r = $this->getRequest(); if ($r->getIsPost() && $form->populate($_POST)->isValid() && $form->save()) { echo $this->json(['status' => true, 'message' => UserModule::t('Password changed')]); $this->end(); } else { echo $this->json(['errors' => $form->getJsonErrors()]); $this->end(); } } else { $form = new RecoverForm(); if ($form->populate($_POST)->isValid() && $form->send()) { echo $this->json(['status' => true]); } else { echo $this->json(['errors' => $form->getJsonErrors()]); } } }
function logoutAction() { if (!User::factory()->_admin) { HTTP::redirect('backend/' . Route::controller() . '/login'); } User::factory()->logout(); HTTP::redirect('backend/' . Route::controller() . '/login'); }
public function actionIndex() { if ($this->getModule()->userList) { $this->addBreadcrumb(UserModule::t("Users"), Mindy::app()->urlManager->reverse('user:list')); } $qs = User::objects()->active(); $pager = new Pagination($qs); echo $this->render('user/list.html', ['pager' => $pager, 'models' => $pager->paginate()]); }
public function save() { $extra = array_merge($this->cleanedData, ['is_active' => defined('MINDY_TESTS'), 'sms_key' => mt_rand(1000, 9999)]); $model = User::objects()->createUser($this->username->getValue(), $this->password->getValue(), $this->email->getValue(), $extra); if ($model->hasErrors() === false) { return $model; } else { d($model->getErrors()); } return false; }
public function actionMigrate() { foreach (BitrixUser::objects()->using('bitrix')->batch(30) as $models) { foreach ($models as $model) { $phones = array_filter([self::convert($model->PERSONAL_PHONE), self::convert($model->PERSONAL_MOBILE)]); $profile = new Profile(['first_name' => self::convert($model->NAME), 'last_name' => self::convert($model->LAST_NAME), 'middle_name' => self::convert($model->SECOND_NAME), 'birthday' => self::convert($model->PERSONAL_BIRTHDAY), 'phone' => empty($phones) ? '' : implode(', ', $phones)]); $profile->save(); $user = new User(['username' => self::convert($model->LOGIN), 'email' => self::convert($model->EMAIL), 'is_active' => $model->getIsActive(), 'password' => self::convert($model->PASSWORD), 'hash_type' => 'bitrix', 'profile' => $profile]); $user->save(); list($city, $created) = City::objects()->getOrCreate(['name' => self::convert($model->PERSONAL_CITY), 'country_id' => 1, 'region_id' => 1]); $address = new UserAddress(['city' => $city, 'address' => self::convert($model->PERSONAL_STREET), 'user' => $user, 'house' => '?', 'apartment' => '?']); $address->save(); if (!empty($model->XML_ID)) { $social = new SocialProfile(['user' => $user, 'social_id' => $model->XML_ID, 'info' => '']); $social->save(); } } } echo 'Memory in use: ' . memory_get_usage() . ' (' . memory_get_usage() / 1024 / 1024 . 'M)' . PHP_EOL; echo 'Peak usage: ' . memory_get_peak_usage() . ' (' . memory_get_peak_usage() / 1024 / 1024 . 'M)' . PHP_EOL; }
/** * @return array|bool */ public function send() { $user = $this->getUser(); if ($user === null) { return false; } /** @var \Modules\Mail\Components\DbMailer $mail */ $mail = Mindy::app()->mail; $activationKey = User::objects()->generateActivationKey(); $user->setAttributes(['activation_key' => $activationKey])->save(['activation_key']); return $mail->fromCode('user.activation_email', $user->email, ['activation_key' => $activationKey]); }
public function testBizRuleViaParams() { $perm = new Permission(['code' => 'test', 'name' => 'Test codename', 'is_default' => true, 'bizrule' => '$params["foo"]=="bar"']); $this->assertTrue($perm->isValid()); $this->assertTrue($perm->save()); $user = User::objects()->createUser('foo', 'bar', '*****@*****.**'); $this->assertEquals(1, $user->permissions->count()); $this->p->fetchData(); $this->assertTrue($this->app->permissions->canBizRule('test', ['foo' => 'bar'])); $this->assertFalse($this->app->permissions->canBizRule('test', ['foo' => 'default'])); $this->assertTrue($user->can('test', ['foo' => 'bar'], false)); $this->assertFalse($user->can('test', ['foo' => 'default'], false)); }
public function testLoginAndLogout() { /** @var \Modules\User\Components\Auth $auth */ $auth = $this->app->auth; $username = '******'; $password = '******'; $user = User::objects()->createUser($username, $password, '*****@*****.**'); $this->assertTrue($auth->getIsGuest()); $this->assertTrue($auth->login($user)); $this->assertFalse($auth->getIsGuest()); $auth->logout(); $this->assertTrue($auth->getIsGuest()); }
public function actionView() { $id = (int) $this->getRequest()->get->get('id'); if (empty($id)) { echo $this->json(['error' => true, 'message' => 'Missing id']); $this->end(); } $model = User::objects()->asArray()->select(User::TRUSTED_FIELDS)->get(['id' => $id]); if ($model === null) { echo $this->json(['error' => true, 'message' => 'User not found']); $this->end(); } echo $this->json(['status' => true, 'user' => $model]); $this->end(); }
public function getFields() { $fields = parent::getFields(); $newFields = array_merge($fields, ['last_name' => ['class' => CharField::class, 'label' => UserModule::t('Last name')], 'first_name' => ['class' => CharField::class, 'label' => UserModule::t('First name')], 'middle_name' => ['class' => CharField::class, 'label' => UserModule::t('Middle name')], 'phone' => ['class' => CharField::class, 'label' => UserModule::t('Phone'), 'hint' => 'На данный номер телефона придет смс с подтверждением регистрации', 'validators' => [function ($value) { if (User::objects()->filter(['phone' => $value])->count() > 0) { return UserModule::t("Phone must be a unique"); } return true; }]], 'i_accept_license' => ['class' => CheckboxField::class, 'required' => true, 'label' => UserModule::t('I accept the license')]]); if (isset($fields['captcha'])) { $captcha = $fields['captcha']; unset($fields['captcha']); return array_merge($newFields, [$captcha]); } return $newFields; }
public function actionActivate($key) { $model = User::objects()->filter(['activation_key' => $key])->get(); if ($model === null) { $this->error(404); } if ($model->is_active) { $this->r->redirect('user:login'); } if ($model->activation_key === $key) { $model->is_active = true; $model->save(['is_active']); echo $this->render('user/registration_activation_success.html'); } else { echo $this->render('user/registration_activation_failed.html'); } }
public function actionActivate($key) { $model = User::objects()->filter(['activation_key' => $key])->get(); if ($model === null) { $this->error(404); } if ($model->activation_key === $key) { $form = new ChangePasswordForm(['model' => $model]); if ($this->getRequest()->isPost && $form->populate($_POST)->isValid() && $form->save()) { $this->getRequest()->flash->success(UserModule::t('Password changed')); $this->getRequest()->redirect('user:login'); } else { echo $this->render('user/recover_change_password.html', ['form' => $form, 'model' => $model, 'key' => $key]); } } else { echo $this->render('user/change_password_incorrect.html'); } }
public function actionActivate($key) { $model = User::objects()->get(['activation_key' => $key]); if ($model === null) { echo $this->json(['status' => false, 'error' => 'Key not found']); $this->end(); } if ($model->is_active == false && $model->activation_key === $key) { $model->is_active = true; $model->save(['is_active']); echo $this->json(['status' => true, 'is_active' => true]); } else { if ($model->is_active) { echo $this->json(['status' => true, 'is_active' => true]); } else { echo $this->json(['status' => false, 'error' => 'Incorrect key']); } } }
public function actionChangepassword($id) { $auth = Mindy::app()->auth; if ($auth->isGuest) { $this->r->redirect(Mindy::app()->homeUrl); } $model = User::objects()->filter(['pk' => $id])->get(); if ($model === null) { $this->error(404); } $admin = new UserAdmin(); $this->addBreadcrumb(Text::mbUcfirst($admin->getVerboseName()), Mindy::app()->urlManager->reverse('admin:list', ['module' => User::getModuleName(), 'adminClass' => $admin->classNameShort()])); $this->addBreadcrumb((string) $model, Mindy::app()->urlManager->reverse('admin:update', ['module' => User::getModuleName(), 'adminClass' => $admin->classNameShort(), 'id' => $id])); $this->addBreadcrumb(UserModule::t('Change password')); $form = new ChangePasswordForm(['model' => $model]); if ($this->r->isPost && $form->populate($_POST)->isValid() && $form->save()) { $this->r->flash->success(UserModule::t('Password changed')); $this->r->http->refresh(); } echo $this->render('admin/changepassword.html', ['model' => $model, 'form' => $form]); }
/** * @return \Modules\User\Models\User|null */ public function getUser() { return User::objects()->get(['phone' => $this->phone->getValue(), 'is_active' => false]); }
/** * @param \Modules\User\Models\User $user the user object * @return boolean whether the rule applies to the role */ protected function isGroupMatched($user) { if (empty($this->groups)) { return true; } foreach ($this->groups as $key => $role) { if (is_numeric($key) && $user->can($role)) { return true; } else { if ($user->can($key, $role)) { return true; } } } return false; }
/** * Inserts or updates a user model in the database. * * @param UserModel $user * * @return int The userId of the updated or inserted user. */ public function save(UserModel $user) { $fields = array(); $name = $user->getName(); $password = $user->getPassword(); $email = $user->getEmail(); $dateConfirmed = $user->getDateConfirmed(); $dateLastActivity = $user->getDateLastActivity(); $dateCreated = $user->getDateCreated(); $confirmed = $user->getConfirmed(); $confirmedCode = $user->getConfirmedCode(); if (!empty($name)) { $fields['name'] = $user->getName(); } if (!empty($password)) { $fields['password'] = $user->getPassword(); } if (!empty($email)) { $fields['email'] = $user->getEmail(); } if (!empty($dateCreated)) { $fields['date_created'] = $user->getDateCreated()->toDb(); } if (!empty($dateConfirmed)) { $fields['date_confirmed'] = $user->getDateConfirmed()->toDb(); } if (!empty($dateLastActivity)) { $fields['date_last_activity'] = $user->getDateLastActivity()->toDb(); } if ($confirmed !== null) { $fields['confirmed'] = $confirmed; } if ($confirmedCode !== null) { $fields['confirmed_code'] = $confirmedCode; } $fields['first_name'] = $user->getFirstName(); $fields['last_name'] = $user->getLastName(); $fields['homepage'] = $user->getHomepage(); $fields['city'] = $user->getCity(); $fields['birthday'] = $user->getBirthday(); $fields['avatar'] = $user->getAvatar(); $fields['signature'] = $user->getSignature(); $fields['opt_mail'] = $user->getOptMail(); $userId = (int) $this->db()->select('id')->from('users')->where(array('id' => $user->getId()))->execute()->fetchCell(); if ($userId) { /* * User does exist already, update. */ $this->db()->update('users')->values($fields)->where(array('id' => $userId))->execute(); } else { /* * User does not exist yet, insert. */ $userId = $this->db()->insert('users')->values($fields)->execute(); } if ($user->getGroups()) { $this->db()->delete('users_groups')->where(array('user_id' => $userId))->execute(); foreach ($user->getGroups() as $group) { $this->db()->insert('users_groups')->values(array('user_id' => $userId, 'group_id' => $group->getId()))->execute(); } } return $userId; }
public function change_passwordAction() { if (!U::info()) { return Config::error(); } $this->addMeta('Изменить пароль'); $this->_content = View::tpl(array(), 'User/ChangePassword'); }
public function testCreateUserWithDefaultGroup() { $group = new Group(['name' => 'test', 'is_default' => true]); $this->assertTrue($group->save()); $user = User::objects()->createUser('foo', 'bar', '*****@*****.**'); $this->assertEquals(1, $user->groups->count()); }
public static function getFields() { return ['user' => ['class' => ForeignField::className(), 'null' => true, 'modelClass' => User::className(), 'verboseName' => CoreModule::t('User')], 'ip' => ['class' => IpField::className(), 'null' => false, 'verboseName' => CoreModule::t('Ip address')], 'name' => ['class' => CharField::className(), 'verboseName' => CoreModule::t('Message'), 'null' => true], 'message' => ['class' => TextField::className(), 'verboseName' => CoreModule::t('Message')], 'module' => ['class' => CharField::className(), 'verboseName' => CoreModule::t('Module')], 'model' => ['class' => CharField::className(), 'verboseName' => CoreModule::t('Model'), 'null' => true], 'url' => ['class' => CharField::className(), 'null' => true, 'verboseName' => CoreModule::t('Url')], 'created_at' => ['class' => DateTimeField::className(), 'autoNowAdd' => true, 'verboseName' => CoreModule::t('Created at')]]; }
public static function getFields() { return ['user' => ['class' => ForeignField::className(), 'modelClass' => User::className(), 'verboseName' => self::t("User")], 'permission' => ['class' => ForeignField::className(), 'modelClass' => Permission::className(), 'verboseName' => self::t("Permission")]]; }
public function createGuestModel() { $guest = new User(); $guest->setAttributes(['username' => UserModule::t('Guest'), 'is_superuser' => false, 'is_staff' => false]); $guest->setIsGuest(true); return $guest; }
public function updateUserById($id) { $user = User::objects()->filter(['pk' => $id])->get(); if ($user) { $this->setModel($user); } }
/** * @return \Modules\User\Models\User|null */ public function getUser() { return User::objects()->get(['sms_key' => $this->code->getValue(), 'is_active' => false]); }
public function forgot_passwordAction() { // Check incoming data $email = Arr::get($this->post, 'email'); if (!$email or !filter_var($email, FILTER_VALIDATE_EMAIL)) { $this->error('Вы неверно ввели E-Mail!'); } $user = DB::select('users')->where('email', '=', $email)->as_object()->execute()->current(); if (!$user) { $this->error('Пользователя с указанным E-Mail адресом не существует!'); } if (!$user->status) { $this->error('Пользователь с указанным E-Mail адресом либо заблокирован либо не подтвердил E-Mail адрес. Пожалуйста обратитесь к Администратору для решения сложившейся ситуации'); } // Generate new password for user and save it to his account $password = User::factory()->generate_random_password(); User::factory()->update_password($user->id, $password); // Send E-Mail to user with instructions how recover password $mail = DB::select()->from('mail_templates')->where('id', '=', 5)->where('status', '=', 1)->as_object()->execute()->current(); if ($mail) { $from = array('{{site}}', '{{ip}}', '{{date}}', '{{password}}'); $to = array(Arr::get($_SERVER, 'HTTP_HOST'), System::getRealIP(), date('d.m.Y H:i'), $password); $subject = str_replace($from, $to, $mail->subject); $text = str_replace($from, $to, $mail->text); Email::send($subject, $text, $user->email); } $this->success('На указанный E-Mail адрес выслан новый пароль для входа'); // $this->success(array('password' => $password)); }
public function settingAction() { $profilMapper = new UserMapper(); $this->getLayout()->getHmenu()->add($this->getTranslator()->trans('menuPanel'), array('controller' => 'panel', 'action' => 'index'))->add($this->getTranslator()->trans('menuSettings'), array('controller' => 'panel', 'action' => 'settings'))->add($this->getTranslator()->trans('menuSetting'), array('controller' => 'panel', 'action' => 'setting')); if ($this->getRequest()->isPost()) { $model = new UserModel(); $model->setId($this->getUser()->getId()); $model->setOptMail($this->getRequest()->getPost('opt_mail')); $profilMapper->save($model); $this->redirect(array('action' => 'setting')); } }
public static function getFields() { return ['user' => ['class' => ForeignField::className(), 'modelClass' => User::className(), 'verboseName' => UserModule::t('User')], 'key' => ['class' => CharField::className(), 'length' => 40, 'verboseName' => UserModule::t("Key"), 'unique' => true]]; }