Контроллер:
Код: Выделить всё
<?php
namespace app\controllers;
use app\models\RegForm;
use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\web\Response;
use yii\filters\VerbFilter;
use app\models\LoginForm;
use app\models\ContactForm;
class SiteController extends Controller
{
/**
* {@inheritdoc}
*/
/**
* {@inheritdoc}
*/
public function actions()
{
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
],
];
}
/**
* Displays homepage.
*
* @return string
*/
public function actionIndex()
{
return $this->render('index');
}
/**
* Login action.
*
* @return Response|string
*/
public function actionLogin()
{
/*if (!Yii::$app->user->isGuest) {
return $this->goHome();
}*/
$model = new LoginForm();
if ($model->load(Yii::$app->request->post()) && $model->login()) {
return $this->goHome() ;
}
return $this->render('LoginForm', compact('model'));
}
/**
* Logout action.
*
* @return Response
*/
public function actionLogout()
{
Yii::$app->user->logout();
return $this->goHome();
}
public function actionReg()
{
$model = new RegForm();
if (Yii::$app->request->isPost) {
if ($model->load(Yii::$app->request->post()) && $model->RegWork()) {
return $this->goHome();
}
}
return $this->render('RegForm', compact('model'));
}
/**
* Displays about page.
*
* @return string
*/
public function actionAbout()
{
return $this->render('about');
}
}
Код: Выделить всё
<?php
namespace app\models;
use Yii;
use yii\base\Model;
/**
* LoginForm is the model behind the login form.
*
* @property User|null $user This property is read-only.
*
*/
class LoginForm extends Model
{
public $login;
public $pass;
public $rememberMe = true;
/**
* @return array the validation rules.
*/
public function rules()
{
return [
// username and password are both required
[['login', 'pass'], 'required'],
// rememberMe must be a boolean value
['rememberMe', 'boolean'],
// password is validated by validatePassword()
['pass', 'validatePassword'],
];
}
/**
* Validates the password.
* This method serves as the inline validation for password.
*
* @param string $attribute the attribute currently being validated
* @param array $params the additional name-value pairs given in the rule
*/
public function validatePassword($attribute, $params)
{
if (!$this->hasErrors()) {
$user = UserModel::getUser($this->login);
if (!$user || !Yii::$app->getSecurity()->validatePassword($this->pass, $user->pass)) {
$this->addError($attribute, 'Incorrect username or password.');
}
}
}
/**
* Logs in a user using the provided username and password.
* @return bool whether the user is logged in successfully
*/
public function login()
{
if ($this->validate()) {
return Yii::$app->user->login(UserModel::getUser($this->login), $this->rememberMe ? 3600*24*30 : 0);
}
return false;
}
}