Commit 3f3d509a authored by Олег Гиммельшпах's avatar Олег Гиммельшпах

Merge branch 'master' of git.task-on.com:ktask/task-on.com

parents 3bc2491c 404700e6
......@@ -11,7 +11,6 @@ nbproject
.buildpath
.project
.settings
.htaccess
# windows thumbnail cache
Thumbs.db
......
Options +FollowSymLinks
IndexIgnore */*
RewriteEngine on
RewriteCond %{REQUEST_URI} !^/(web)
RewriteRule ^assets/(.*)$ /web/assets/$1 [L]
RewriteRule ^css/(.*)$ web/css/$1 [L]
RewriteRule ^js/(.*)$ web/js/$1 [L]
RewriteRule ^images/(.*)$ web/images/$1 [L]
RewriteRule (.*) /web/$1
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /web/index.php
\ No newline at end of file
......@@ -35,6 +35,10 @@ return [
'analyticsSchool' => ['class' => 'common\modules\analyticsSchool\Module',],
],
'components' => [
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
'useFileTransport' => false,
],
'session' => [
'class' => 'yii\web\Session',
],
......@@ -126,29 +130,20 @@ return [
'showScriptName' => false,
'enableStrictParsing' => true,
'rules' => [
/*[
'class' => 'yii\rest\UrlRule',
'controller' => 'mainAdmin',
]
'main/mainAdmin/index' => 'main/mainAdmin/index',*/
'<module_id>/settings/manage' => 'settings/manage',
'<module_id>/settings/create' => 'settings/create',
'<module_id>/settings/update/<id>' => 'settings/update',
'<module_id>/settings/delete/<id>' => 'settings/delete',
'<module_id>/settings/view/<id>' => 'settings/view',
'main/mainAdmin' => 'main/main-admin/index',
'/' => 'main/main-admin/index',
'' => 'main/main-admin/index',
'/' => 'site/index',
'' => 'site/index',
'users/user-admin/manage/is_deleted/<is_deleted>' => 'users/user-admin/manage',
'users/userAdmin/SetDeletedFlag/id/<id>/is_deleted/<is_deleted>' => 'users/userAdmin/SetDeletedFlag',
'users/userAdmin/delete/id/<id>/ajax/<ajax>' => 'users/userAdmin/delete',
'<_m>/<_c>/<_a>/<id>' => '<_m>/<_c>/<_a>',
'<_m>/<_c>/<_a>' => '<_m>/<_c>/<_a>',
'<_c>/<_a>' => '<_c>/<_a>',
//'module/<module:\w+>/<controller:\w+>/<action:\w+>' => '<module>/<controller>/<action>',
]
],
'formatter' => [
......
......@@ -2,4 +2,5 @@
return [
'adminEmail' => 'admin@example.com',
'name' => 'Арт Проект',
'user.passwordResetTokenExpire' => 3600,
];
......@@ -4,7 +4,10 @@ namespace backend\controllers;
use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use common\models\LoginForm;
use common\models\RecoveryForm;
use common\models\ResetPasswordForm;
use common\modules\users\models\User;
/**
......@@ -24,11 +27,11 @@ class SiteController extends Controller
'class' => AccessControl::className(),
'rules' => [
[
'actions' => ['login', 'error'],
'actions' => ['login', 'recovery', 'reset-password', 'error'],
'allow' => true,
],
[
'actions' => ['logout'],
'actions' => ['logout', 'index'],
'allow' => true,
'roles' => ['@'],
],
......@@ -37,15 +40,24 @@ class SiteController extends Controller
];
}
public function actionIndex()
{
$this->page_title = 'Просмотр главной страницы';
return $this->render('index');
}
public function actionError()
{
$this->layout = "clear";
return $this->render('error');
$exception = Yii::$app->errorHandler->exception;
return $this->render('error', ['exception' => $exception]);
}
public function actionLogin()
{
if (!\Yii::$app->user->isGuest)
if (!Yii::$app->user->isGuest)
{
return $this->goHome();
}
......@@ -59,20 +71,72 @@ class SiteController extends Controller
if($model->user->role == User::ROLE_ADMIN)
{
$model->login();
return $this->goBack();
}
else
{
return $this->refresh();
$model->addError('password', 'Вы не имеете доступ в этот раздел');
}
}
return $this->goBack();
return $this->render('login', [
'model' => $model,
]);
}
else
public function actionRecovery()
{
return $this->render('login', [
if (!Yii::$app->user->isGuest)
{
return $this->goHome();
}
$this->page_title = 'Востановление пароля';
$this->layout = "blank";
$success = false;
$model = new RecoveryForm();
if ($model->load(Yii::$app->request->post()) && $model->validate())
{
$model->recovery();
$success = true;
}
return $this->render('recovery', [
'model' => $model,
'success' => $success,
]);
}
public function actionResetPassword($token)
{
if (!Yii::$app->user->isGuest)
{
return $this->goHome();
}
$this->page_title = 'Востановление пароля';
$this->layout = "blank";
$success = false;
try {
$model = new ResetPasswordForm($token);
} catch (InvalidParamException $e) {
throw new BadRequestHttpException($e->getMessage());
}
if ($model->load(Yii::$app->request->post()) && $model->validate() && $model->resetPassword())
{
$success = true;
}
return $this->render('reset-password', [
'model' => $model,
'success' => $success,
]);
}
public function actionLogout()
......
......@@ -17,9 +17,9 @@ use common\models\Settings;
<div id="page-container" class="fade">
<!-- begin error -->
<div class="error">
<div class="error-code m-b-10">404 <i class="fa fa-warning"></i></div>
<div class="error-code m-b-10"><?=($exception?$exception->statusCode:'404')?> <i class="fa fa-warning"></i></div>
<div class="error-content">
<div class="error-message">Произошла какая-то ошибка</div>
<div class="error-message"><?=($exception?$exception->getMessage():'Произошла какая-то ошибка')?></div>
<div class="error-desc m-b-20">
Страница не существует или у вас нет прав для ее просмотра.<br />
Проверьте введенный URL-адрес страницы или обратитесь в Службу технической поддержки для решения данного вопроса
......
<?php
/* @var $this yii\web\View */
$this->title = 'My Yii Application';
?>
<div class="site-index">
<div class="jumbotron">
<h1>Congratulations!</h1>
<p class="lead">You have successfully created your Yii-powered application.</p>
<p><a class="btn btn-lg btn-success" href="http://www.yiiframework.com">Get started with Yii</a></p>
</div>
<div class="body-content">
<div class="row">
<div class="col-lg-4">
<h2>Heading</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et
dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip
ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu
fugiat nulla pariatur.</p>
<p><a class="btn btn-default" href="http://www.yiiframework.com/doc/">Yii Documentation &raquo;</a></p>
</div>
<div class="col-lg-4">
<h2>Heading</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et
dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip
ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu
fugiat nulla pariatur.</p>
<p><a class="btn btn-default" href="http://www.yiiframework.com/forum/">Yii Forum &raquo;</a></p>
</div>
<div class="col-lg-4">
<h2>Heading</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et
dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip
ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu
fugiat nulla pariatur.</p>
<p><a class="btn btn-default" href="http://www.yiiframework.com/extensions/">Yii Extensions &raquo;</a></p>
</div>
</div>
</div>
</div>
......@@ -6,39 +6,15 @@ use yii\bootstrap\ActiveForm;
/* @var $form yii\bootstrap\ActiveForm */
/* @var $model \common\models\LoginForm */
$this->title = 'Login';
$this->params['breadcrumbs'][] = $this->title;
?>
<!--
<div class="site-login">
<h1><?= Html::encode($this->title) ?></h1>
<p>Please fill out the following fields to login:</p>
<div class="row">
<div class="col-lg-5">
<?php $form = ActiveForm::begin(['id' => 'login-form']); ?>
<?= $form->field($model, 'username') ?>
<?= $form->field($model, 'password')->passwordInput() ?>
<?= $form->field($model, 'rememberMe')->checkbox() ?>
<div class="form-group">
<?= Html::submitButton('Login', ['class' => 'btn btn-primary', 'name' => 'login-button']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
</div>
</div>
-->
<!-- begin login -->
<div class="login login-v2" data-pageload-addclass="animated flipInX">
<!-- begin login -->
<div class="login login-v2" data-pageload-addclass="animated flipInX">
<!-- begin brand -->
<div class="login-header">
<div class="brand">
<img src="/img/logo.png">
<small>Virtual intelligence exists</small>
<!-- Микрокредит
<small>Микрокредит Микрокредит Микрокредит</small>-->
<small>Авторизация</small>
</div>
<div class="icon">
<i class="fa fa-sign-in"></i>
......@@ -99,23 +75,14 @@ $this->params['breadcrumbs'][] = $this->title;
<div class="login-buttons">
<?= Html::submitButton('Войти', ['class' => 'btn btn-success btn-block btn-lg', 'name' => 'login-button']) ?>
</div>
<!--div class="m-t-20">
Забыли свой пароль? Нажмите <a href="#">здесь</a> чтобы восстановить.
</div-->
<?php ActiveForm::end(); ?>
<div class="m-t-20">
Забыли свой пароль? Нажмите <?=Html::a('здесь', ['recovery'])?> чтобы восстановить.
</div>
<?php ActiveForm::end(); ?>
</div>
<!-- end login -->
<!--
<ul class="login-bg-list">
<li class="active"><a href="#" data-click="change-bg"><img src="/img/login-bg/bg-1.jpg" alt="" /></a></li>
<li><a href="#" data-click="change-bg"><img src="/img/login-bg/bg-2.jpg" alt="" /></a></li>
<li><a href="#" data-click="change-bg"><img src="/img/login-bg/bg-3.jpg" alt="" /></a></li>
<li><a href="#" data-click="change-bg"><img src="/img/login-bg/bg-4.jpg" alt="" /></a></li>
<li><a href="#" data-click="change-bg"><img src="/img/login-bg/bg-5.jpg" alt="" /></a></li>
<li><a href="#" data-click="change-bg"><img src="/img/login-bg/bg-6.jpg" alt="" /></a></li>
</ul>
-->
</div>
<!-- end login -->
<?php
$this->registerJsFile('/js/login-v2.demo.min.js', ['position' => \yii\web\View::POS_END ]);
......
<?php
use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
?>
<!-- begin login -->
<div class="login login-v2" data-pageload-addclass="animated flipInX">
<!-- begin brand -->
<div class="login-header">
<div class="brand">
<img src="/img/logo.png">
<small>Востановление пароля</small>
</div>
<div class="icon">
<i class="fa fa-sign-in"></i>
</div>
</div>
<!-- end brand -->
<div class="login-content">
<?php if($success) : ?>
<center>
На указанные e-mail отправлено письмо для подтверждения. <br>
<?=Html::a('Вернуться к авторизации', ['login'])?>
</center>
<?php else : ?>
<?php $form = ActiveForm::begin([
'enableClientValidation' => true,
'id' => 'login-form',
'options' => [
'class' => 'margin-bottom-0'
],
'fieldConfig' => [
'template' => '{input}{error}',
],
]); ?>
<div class="form-group m-b-20">
<?= $form->field(
$model,
'email',
[
'inputOptions' => [
'class' => 'form-control input-lg',
'placeholder' => 'Укажи свой e-mail',
]
]
)->label(false) ?>
</div>
<div class="login-buttons">
<?= Html::submitButton('Востановить', ['class' => 'btn btn-success btn-block btn-lg', 'name' => 'login-button']) ?>
</div>
<?php ActiveForm::end(); ?>
<div class="m-t-20">
<center>
<?=Html::a('Вернуться к авторизации', ['login'])?>
</center>
</div>
<?php endif; ?>
</div>
</div>
<!-- end login -->
<?php
$this->registerJsFile('/js/login-v2.demo.min.js', ['position' => \yii\web\View::POS_END ]);
$this->registerJs('App.init();LoginV2.init();', \yii\web\View::POS_READY);
?>
\ No newline at end of file
<?php
use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
?>
<!-- begin login -->
<div class="login login-v2" data-pageload-addclass="animated flipInX">
<!-- begin brand -->
<div class="login-header">
<div class="brand">
<img src="/img/logo.png">
<small>Востановление пароля</small>
</div>
<div class="icon">
<i class="fa fa-sign-in"></i>
</div>
</div>
<!-- end brand -->
<div class="login-content">
<?php if($success) : ?>
<center>
Новый пароль успешно сохранен. <br>
<?=Html::a('Вернуться к авторизации', ['login'])?>
</center>
<?php else : ?>
<?php $form = ActiveForm::begin([
'enableClientValidation' => true,
'id' => 'login-form',
'options' => [
'class' => 'margin-bottom-0'
],
'fieldConfig' => [
'template' => '{input}{error}',
],
]); ?>
<div class="form-group m-b-20">
<?= $form->field(
$model,
'password',
[
'inputOptions' => [
'class' => 'form-control input-lg',
'placeholder' => 'Введите новый пароль',
]
]
)->passwordInput()->label(false) ?>
</div>
<div class="login-buttons">
<?= Html::submitButton('Сохранить', ['class' => 'btn btn-success btn-block btn-lg', 'name' => 'login-button']) ?>
</div>
<?php ActiveForm::end(); ?>
<?php endif; ?>
</div>
</div>
<!-- end login -->
<?php
$this->registerJsFile('/js/login-v2.demo.min.js', ['position' => \yii\web\View::POS_END ]);
$this->registerJs('App.init();LoginV2.init();', \yii\web\View::POS_READY);
?>
\ No newline at end of file
RewriteEngine On RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php
\ No newline at end of file
......@@ -26,16 +26,11 @@ abstract class AdminController extends \common\components\BaseController
return $this->redirect('/site/login');
}
if(Yii::$app->user->identity->role != User::ROLE_ADMIN)
{
throw new NotSupportedException('The requested page does not exist.');
}
$module = $this->getModuleName();
if($module && !Yii::$app->authManager->checkAccess(Yii::$app->user->id, $module))
if(Yii::$app->user->identity->role != User::ROLE_ADMIN || ($module && !Yii::$app->authManager->checkAccess(Yii::$app->user->id, $module)))
{
throw new \Exception('There is no access to this page', 403);
throw new \yii\web\HttpException(403, 'У Вас нет прав для просмотра этой страницы');
}
}
......
This diff is collapsed.
......@@ -3,10 +3,21 @@
/* @var $this yii\web\View */
/* @var $user common\models\User */
$resetLink = Yii::$app->urlManager->createAbsoluteUrl(['site/reset-password', 'token' => $user->password_reset_token]);
use common\models\Settings;
$resetLink = Yii::$app->urlManager->createAbsoluteUrl(['site/reset-password', 'token' => $user->password_change_code]);
?>
Hello <?= $user->username ?>,
Follow the link below to reset your password:
Добрый день!
Для Вас был сброшен пароль на сайте <?=Settings::getValue('setting-project-name')?>.
Для того что бы задать новый пароль перейдите по ссылке ниже. Если ссылка не открывается, то скопируйте ее в адресную строку браузера.
<?= $resetLink ?>
В целях безопасности просим вас не передавать данную ссылку третьим лицам и не хранить данное письмо после сброса пароля.
С уважением, команда <?=Settings::getValue('setting-project-name')?>.
Если у Вас есть вопросы обратитесь к администратору сервиса на адрес <?=Settings::getValue('content-support-email')?>
\ No newline at end of file
This diff is collapsed.
<?php
/* @var $this yii\web\View */
/* @var $user common\models\User */
use common\models\Settings;
?>
Добрый день!
Уведомляем Вас о том, что Вы были зарегистрированы на сайте <?=Settings::getValue('setting-project-name')?>.
Для входа используйте следующие пароли доступа:
Логин: <?= $user->email; ?>
Пароль: <?= $user->password; ?>
В целях безопасности просим Вас не передавать пароль третьим лицам.
С уважением, команда <?=Settings::getValue('setting-project-name')?>.
Если у Вас есть вопросы обратитесь к администратору сервиса на адрес <?=Settings::getValue('content-support-email')?>
\ No newline at end of file
......@@ -44,11 +44,18 @@ class LoginForm extends Model
*/
public function validatePassword($attribute, $params)
{
if (!$this->hasErrors()) {
if (!$this->hasErrors())
{
$user = $this->getUser();
if (!$user || !$user->validatePassword($this->password)) {
if (!$user || !$user->validatePassword($this->password))
{
$this->addError($attribute, 'Неверно указан e-mail или пароль. Проверьте правильность ввода.');
}
elseif($user->status == User::STATUS_BLOCKED)
{
$this->addError($attribute, 'У Вас нет прав для просмотра данного раздела. Обратитесь к Администратору для изменения параметров авторизации.');
}
}
}
......@@ -61,12 +68,17 @@ class LoginForm extends Model
{
$user = $this->getUser();
if($user)
{
$user->last_logon = time();
$user->save(false, ['last_logon']);
return Yii::$app->user->login($user, $this->rememberMe ? 3600 * 24 * 30 : 0);
}
return false;
}
/**
* Finds user by [[username]]
*
......
<?php
namespace common\models;
use Yii;
use yii\base\Model;
use common\models\Settings;
use common\modules\users\models\User;
class RecoveryForm extends Model
{
public $email;
private $_user = null;
/**
* @inheritdoc
*/
public function rules()
{
return [
['email', 'filter', 'filter' => 'trim'],
[['email'], 'required', 'message' => 'Укажи свой e-mail для восстановления пароля.'],
[['email'], 'email', 'message' => 'Некорректный формат.'],
['email', 'validateEmail'],
];
}
public function validateEmail($attribute, $params)
{
if (!$this->hasErrors())
{
$user = $this->getUser();
if (!$user)
{
$this->addError($attribute, 'Такой пользователь не найден.');
}
}
}
/**
* Logs in a user using the provided username and password.
*
* @return boolean whether the user is logged in successfully
*/
public function recovery()
{
$user = $this->getUser();
if (!User::isPasswordResetTokenValid($user->password_change_code))
{
$user->generatePasswordResetToken();
}
if ($user->save())
{
return Yii::$app->mailer->compose(['html' => 'passwordResetToken-html', 'text' => 'passwordResetToken-text'], ['user' => $user])
->setFrom([Settings::getValue('setting-info-email') => Settings::getValue('setting-from-email')])
->setTo($this->email)
->setSubject('Восстановление пароля')
->send();
}
}
/**
* Finds user by [[username]]
*
* @return User|null
*/
public function getUser()
{
if ($this->_user === null)
{
$this->_user = User::findOne([
'status' => User::STATUS_ACTIVE,
'email' => $this->email,
]);
}
return $this->_user;
}
public function attributeLabels()
{
return [
'email' => 'E-mail',
];
}
}
<?php
namespace common\models;
use Yii;
use yii\base\InvalidParamException;
use yii\base\Model;
use common\modules\users\models\User;
/**
* Password reset form
*/
class ResetPasswordForm extends Model
{
public $password;
/**
* @var \common\models\User
*/
private $_user;
/**
* Creates a form model given a token.
*
* @param string $token
* @param array $config name-value pairs that will be used to initialize the object properties
* @throws \yii\base\InvalidParamException if token is empty or not valid
*/
public function __construct($token, $config = [])
{
if (empty($token) || !is_string($token)) {
throw new InvalidParamException('Password reset token cannot be blank.');
}
$this->_user = User::findByPasswordResetToken($token);
if (!$this->_user) {
throw new InvalidParamException('Wrong password reset token.');
}
parent::__construct($config);
}
/**
* @inheritdoc
*/
public function rules()
{
return [
['password', 'required', 'message' => 'Введите новый пароль'],
['password', 'string', 'min' => 7],
];
}
/**
* Resets password.
*
* @return boolean if password was reset.
*/
public function resetPassword()
{
$user = $this->_user;
$user->setPassword($this->password);
$user->removePasswordResetToken();
return $user->save(false);
}
}
......@@ -9,13 +9,8 @@ class MainAdminController extends \common\components\AdminController
public static function actionsTitles()
{
return array(
'Index' => 'Просмотр главной страницы',
);
}
public function actionIndex()
{
return $this->render('index');
}
}
......@@ -149,7 +149,7 @@ class RoleAdminController extends \common\components\AdminController
$modules = [];
$columns = [
[
'label' => ИО',
'label' => амилия, Имя',
'attribute' => 'fullName',
'format' => 'raw',
'value' => function($model) {
......@@ -157,15 +157,19 @@ class RoleAdminController extends \common\components\AdminController
}
],
[
'label' => 'Дата добавления пользователя',
'label' => 'Дата добавления <br> пользователя',
'encodeLabel' => false,
'attribute' => 'date_create',
'value' => function($model) {
return ($model->date_create?date('d.m.Y H:i', strtotime($model->date_create)):'Нет данных');
}
],
[
'label' => 'Последний вход в систему',
'label' => 'Последний вход <br> в систему',
'encodeLabel' => false,
'attribute' => 'last_logon',
'filter' => false,
'value' => function($model) {
return ($model->last_logon?date('d.m.Y H:i', $model->last_logon):null);
return ($model->last_logon?date('d.m.Y H:i', $model->last_logon):'Нет данных');
}
]
];
......
......@@ -29,7 +29,7 @@ $not_system_role = '!in_array($data->name, AuthItem::$system_roles)';
echo AdminGrid::widget([
'id' => 'access-grid-roles',
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'formatDateValues' => false,
'rowOptions' => function ($model, $index, $widget, $grid){
if($model->status == 'blocked')
//return ['style'=>'background-color:#575d63 !important;'];
......
......@@ -15,6 +15,7 @@ use common\modules\messageTemplate\models\MessageTemplate;
* @property integer $case_id
* @property integer $template_id
* @property string $sended_date
* @property string $email
* @property integer $sended
* @property integer $actual
*
......@@ -38,12 +39,13 @@ class CasesSchedule extends \yii\db\ActiveRecord
public function rules()
{
return [
[['user_id', 'case_id'], 'required'],
[['case_id'], 'required'],
[['email'], 'string'],
[['user_id', 'case_id', 'template_id', 'sended', 'actual'], 'integer'],
[['sended_date'], 'safe'],
[['template_id'], 'exist', 'skipOnError' => true, 'targetClass' => MessageTemplate::className(), 'targetAttribute' => ['template_id' => 'id']],
[['case_id'], 'exist', 'skipOnError' => true, 'targetClass' => CoContent::className(), 'targetAttribute' => ['case_id' => 'id']],
[['user_id'], 'exist', 'skipOnError' => true, 'targetClass' => User::className(), 'targetAttribute' => ['user_id' => 'id']],
[['user_id'], 'exist', 'skipOnError' => false, 'targetClass' => User::className(), 'targetAttribute' => ['user_id' => 'id']],
];
}
......@@ -55,6 +57,7 @@ class CasesSchedule extends \yii\db\ActiveRecord
return [
'id' => 'ID',
'user_id' => 'Пользователь',
'email' => 'E-mail',
'case_id' => 'Кейс',
'template_id' => 'Шаблон',
'sended_date' => 'Дата отправки',
......
......@@ -69,7 +69,8 @@ class UserAdminController extends \common\components\AdminController
];
}
public function actionBlock($id) {
public function actionBlock($id)
{
$model = User::find()->where(['id'=>$id])->one();
if(empty($model)) $error;
......@@ -78,59 +79,9 @@ class UserAdminController extends \common\components\AdminController
$this->redirect(['/rbac/role-admin/manage']);
}
public function actionSendNewPassword($id)
{
$model = $this->loadModel($id);
$model->scenario = User::SCENARIO_SEND_NEW_PASSWORD;
$form = new BaseForm('users.SendNewPasswordForm', $model);
//$this->performAjaxValidation($model);
/*
print_r($form);
die();
*/
if(isset($_POST['User'])) {
if (isset($_POST['User']['password']) && isset($_POST['User']['password_c'])) {
$model->password = $_POST['User']['password'];
$model->password_c = $_POST['User']['password_c'];
} else {
$model->password = 123;
$model->password_c = 123;
}
if ($model->validate()) {
if ($_POST['User']['generate_new'] == 1) {
$password = PasswordGenerator::generate(7);
} else {
$password = $_POST['User']['password'];
}
$model->password = md5($password);
$model->password_c = md5($password);
if ($model->save()) {
Yii::app()->user->setFlash('flash','Пароль для пользователя <b>'.$model->name.'</b> был изменён.');
$email = Yii::app()->email;
$email->to = $user;
$email->from = Setting::getValue('support_email');
$email->subject = 'Hello';
$email->message = Yii::app()->controller->renderInternal(Yii::getPathOfAlias('application.views.yii-mail.pass').'.php', array('password' => $password), true);
$email->send();
$this->redirect('/users/userAdmin/manage');
}
}
}
$this->render('sendNewPassword', array('form' => $form));
}
public function actionManage($is_deleted = 0)
{
//$is_deleted = $this->getRequest()->getQueryParam('is_deleted') ? $this->getRequest()->getQueryParam('is_deleted') : 0;
$model = new \common\modules\users\models\User(/*User::SCENARIO_SEARCH*/);
$model = new \common\modules\users\models\User;
$model->scenario = User::SCENARIO_SEARCH;
$model->is_deleted = $is_deleted;
......@@ -147,7 +98,6 @@ class UserAdminController extends \common\components\AdminController
));
}
public function actionView($id)
{
$this->render('view', array(
......@@ -175,11 +125,6 @@ class UserAdminController extends \common\components\AdminController
$model->scenario = User::SCENARIO_CREATE;
$model->status = "active";
if (!isset($_POST['User']))
{
$model->send_email = true;
}
\Yii::$app->controller->page_title = 'Добавить пользователя';
\Yii::$app->controller->tabs = array(
......@@ -196,19 +141,20 @@ class UserAdminController extends \common\components\AdminController
if ($model->validate())
{
$password = $model->password;
$model->sendPassword();
$model->password = \Yii::$app->security->generatePasswordHash($model->password);
$model->activate_code=\Yii::$app->security->generatePasswordHash($model->password.'xdf5sf');
if(!$model->save(false)) die(print_r($model->error));
$this->redirect(array(
$model->save(false);
return $this->redirect(array(
'/rbac/role-admin/manage',
'id' => $model->id,
'is_created'=>1
));
}
}
$form = new \common\components\BaseForm('/common/modules/users/forms/UserForm', $model);
return $this->render('create', [
......@@ -239,6 +185,11 @@ class UserAdminController extends \common\components\AdminController
{
if($model->password)
{
if($model->send_email)
{
$model->sendPassword();
}
$model->password = $model->password_c = \Yii::$app->security->generatePasswordHash($model->password);
}
else
......@@ -248,11 +199,8 @@ class UserAdminController extends \common\components\AdminController
if($model->save())
{
AuthAssignment::updateUserRole($model->id, $_POST['User']['role']);
return $this->redirect(array(
'/rbac/role-admin/manage',
'id'=> $model->id
'/rbac/role-admin/manage'
));
}
}
......
<?php
use yii\db\Migration;
class m160506_095235_fix_user extends Migration
{
public function up()
{
$this->alterColumn('users', 'password_change_code', $this->string(255));
}
public function down()
{
$this->alterColumn('users', 'password_change_code', $this->string(32));
}
}
<?php
use yii\db\Migration;
class m160506_145707_fix_user extends Migration
{
public function up()
{
$this->alterColumn('users', 'phone', $this->string(20));
$this->alterColumn('users', 'mobile_phone', $this->string(20));
}
public function down()
{
$this->alterColumn('users', 'phone', $this->string(14));
$this->alterColumn('users', 'mobile_phone', $this->string(14));
}
}
......@@ -25,6 +25,7 @@ use yii\data\ActiveDataProvider;
use himiklab\sortablegrid\SortableGridBehavior;
use \common\components\validators\RuEmailValidator;
use \common\modules\messageTemplate\components\Templates;
use common\models\Settings;
use \common\modules\rbac\models\AuthItem;
use \common\modules\rbac\models\AuthAssignment;
......@@ -142,6 +143,8 @@ class User extends \common\components\ActiveRecordModel implements IdentityInter
"post" => "Должность",
"status" => "Активен / заблокирован",
"occupation" => "Род занятий",
"phone" => "Телефон",
"mobile_phone" => "Мобильный телефон",
));
return $attrs;
......@@ -198,15 +201,9 @@ class User extends \common\components\ActiveRecordModel implements IdentityInter
self::SCENARIO_UPDATE,
self::SCENARIO_CREATE,
]],
//array('password', 'unsafe', 'on' => array(
[['password'], 'safe', 'on' => [
self::SCENARIO_UPDATE,
]],
/*[['email'], 'email', 'message' => $this->emailErrorMessage(), 'on'=> [
self::SCENARIO_RECOVER_PASSWORD,
self::SCENARIO_SEND_NEW_PASSWORD,
self::SCENARIO_LOGIN,
]],*/
[['email'], 'unique','on' => [
self::SCENARIO_REGISTRATION,
self::SCENARIO_CREATE,
......@@ -220,12 +217,10 @@ class User extends \common\components\ActiveRecordModel implements IdentityInter
self::SCENARIO_SEND_NEW_PASSWORD,
], 'message' => 'Пароли должны совпадать и состоять из букв латинского алфавита или цифр.'],
[['password'], 'safe', 'on' => self::SCENARIO_CSV_IMPORT],
//array('phone, mobile_phone, phone_ext, fax', 'PhoneValidator'),
['is_deleted, date_delete', 'safe', 'on' => [
self::SCENARIO_DELETE,
]],
[['is_deleted'], 'integer','integerOnly' => true],
//array('phone', 'integer'),
[['fio'], 'string','min' => 2],
[['email'], 'string','max' => 200],
[['source'], 'string','max' => 50],
......@@ -235,7 +230,6 @@ class User extends \common\components\ActiveRecordModel implements IdentityInter
[['csv_file'], 'file', 'mimeTypes' => 'csv', 'on' => [
self::SCENARIO_CSV_IMPORT,
]],
// [['fio', 'phone',' mobile_phone'], 'filter', 'filter' => 'strip_tags'],
[['id', 'email', 'status', 'date_create', 'fio'], 'safe', 'on'=> [
self::SCENARIO_SEARCH,
self::SCENARIO_CREATE,
......@@ -273,7 +267,7 @@ class User extends \common\components\ActiveRecordModel implements IdentityInter
*/
public static function findIdentity($id)
{
return static::findOne(['id' => $id/*, 'status' => self::STATUS_ACTIVE*/]);
return static::findOne(['id' => $id, 'status' => self::STATUS_ACTIVE]);
}
/**
......@@ -308,11 +302,46 @@ class User extends \common\components\ActiveRecordModel implements IdentityInter
}
return static::findOne([
'password_reset_token' => $token,
'password_change_code' => $token,
'status' => self::STATUS_ACTIVE,
]);
}
/**
* Finds out if password reset token is valid
*
* @param string $token password reset token
* @return boolean
*/
public static function isPasswordResetTokenValid($token)
{
if (empty($token))
{
return false;
}
$timestamp = (int) substr($token, strrpos($token, '_') + 1);
$expire = Yii::$app->params['user.passwordResetTokenExpire'];
return $timestamp + $expire >= time();
}
/**
* Generates new password reset token
*/
public function generatePasswordResetToken()
{
$this->password_change_code = Yii::$app->security->generateRandomString() . '_' . time();
$this->password_change_date = date('Y-m-d H:i:s');
}
/**
* Removes password reset token
*/
public function removePasswordResetToken()
{
$this->password_change_code = null;
}
public function getPost()
{
if(!empty($this->post))
......@@ -403,6 +432,16 @@ class User extends \common\components\ActiveRecordModel implements IdentityInter
return $score;
}
public function beforeValidate()
{
if($this->status != static::STATUS_ACTIVE)
{
$this->status = static::STATUS_BLOCKED;
}
return parent::beforeValidate();
}
public function getFullName()
{
return $this->name . ' ' . $this->surname;
......@@ -413,6 +452,15 @@ class User extends \common\components\ActiveRecordModel implements IdentityInter
$this->fullName = $value;
}
public function sendPassword()
{
return Yii::$app->mailer->compose(['html' => 'sendNewPassword-html', 'text' => 'sendNewPassword-text'], ['user' => $this])
->setFrom([Settings::getValue('setting-info-email') => Settings::getValue('setting-from-email')])
->setTo($this->email)
->setSubject('Данные для входа')
->send();
}
public function getCustomName($user = null)
{
if (!$user)
......@@ -588,6 +636,7 @@ class User extends \common\components\ActiveRecordModel implements IdentityInter
return $result;
}
public function beforeDelete()
{
if (parent::beforeDelete())
......
<?php
use yii\db\Migration;
class m160511_154131_add_settings extends Migration
{
public function up()
{
$this->update('settings', ['module_id' => 'main'], ['code' => 'content-support-email']);
$this->insert('settings', [
'module_id' => 'main',
'code' => 'setting-info-email',
'name' => 'E-mail для отправки уведомлений (данный e-mail будет использоваться в качестве отправителя)',
'value' => 'info@task-on.com',
'element' => 'text',
'hidden' => 0,
'description' => 'E-mail для отправки уведомлений (данный e-mail будет использоваться в качестве отправителя)',
]);
$this->insert('settings', [
'module_id' => 'main',
'code' => 'setting-from-email',
'name' => 'Имя отправителя в E-mail письмах (данное имя будет отображаться в качестве отправителя)',
'value' => 'Task-On',
'element' => 'text',
'hidden' => 0,
'description' => 'Имя отправителя в E-mail письмах (данное имя будет отображаться в качестве отправителя)',
]);
$this->insert('settings', [
'module_id' => 'main',
'code' => 'setting-project-name',
'name' => 'Название проекта (отображается в письмах отправляемых сайтом)',
'value' => 'Task-On',
'element' => 'text',
'hidden' => 0,
'description' => 'Название проекта (отображается в письмах отправляемых сайтом)',
]);
$this->insert('settings', [
'module_id' => 'main',
'code' => 'setting-project-url',
'name' => 'URL адреса сайта (отображается в письмах отправляемых сайтом)',
'value' => 'http://task-on.com',
'element' => 'text',
'hidden' => 0,
'description' => 'URL адреса сайта (отображается в письмах отправляемых сайтом)',
]);
}
public function down()
{
$this->update('settings', ['module_id' => 'content'], ['code' => 'content-support-email']);
$this->delete('settings', ['code' => 'setting-info-email']);
$this->delete('settings', ['code' => 'setting-from-email']);
$this->delete('settings', ['code' => 'setting-project-name']);
$this->delete('settings', ['code' => 'setting-project-url']);
}
}
<?php
use yii\db\Migration;
class m160512_151201_update_the_cases_schedule_table extends Migration
{
// Use safeUp/safeDown to run migration code within a transaction
public function safeUp()
{
$this->dropForeignKey(
'fk_cases_schedule_user',
'cases_schedule'
);
$this->alterColumn(
'cases_schedule',
'user_id',
$this->integer(11)->defaultValue(null)
);
$this->addForeignKey(
'fk_cases_schedule_user',
'cases_schedule', 'user_id',
'users', 'id'
);
$this->addColumn(
'cases_schedule',
'email',
'varchar(255) NOT NULL'
);
}
public function safeDown()
{
$this->dropForeignKey(
'fk_cases_schedule_user',
'cases_schedule'
);
$this->alterColumn(
'cases_schedule',
'user_id',
$this->integer(11)->notNull()
);
$this->addForeignKey(
'fk_cases_schedule_user',
'cases_schedule', 'user_id',
'users', 'id'
);
$this->dropColumn(
'cases_schedule',
'email'
);
}
}
RewriteEngine On RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php
\ No newline at end of file
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment