<?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 RegisterForm extends Model
{
public $username;
public $password;
public $passwordConfirm;
public $email;
private $_user = false;
/**
* @return array the validation rules.
*/
public function rules()
{
return [
[['username', 'email', 'password','passwordConfirm'], 'required','message'=>"Поле обязательно к заполнению"],
[['username', 'email', 'password','passwordConfirm'], 'trim'],
[['password'],'string', 'length'=>[6,12],'message'=>"Пароль должен содержать от 6 до 12 символов"],
[['username'],'string', 'length'=>[4,12],'message'=>"Логин должен содержать от 4 до 12 символов"],
[['username'],'unique', 'targetAttribute'=>"username","targetClass"=>"app\models\User", 'message'=>"Этот логин уже занят"],
[['email'],'unique', 'targetAttribute'=>"email","targetClass"=>"app\models\User", 'message'=>"Эта почта уже зарегистрирована"],
['password', 'compare', 'compareAttribute' => 'passwordConfirm','message'=>"Пароли не совпадают"],
['email','email','message'=>"Некорректный email"],
];
}
public function attributeLabels() {
return [
'username'=>'Логин',
'password'=>'Пароль',
'passwordConfirm'=>'Подтверждение пароля',
'email'=>'Email',
];
}
/**
* 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
*/
/**
* Logs in a user using the provided username and password.
* @return bool whether the user is logged in successfully
*/
public function register()
{
if ($this->validate()) {
$user=new User;
$user->username=$this->username;
$user->email=$this->email;
$user->save();
return true;
}
else {
return false;
}
}
/**
* Finds user by [[username]]
*
* @return User|null
*/
public function getUser()
{
if ($this->_user === false) {
$this->_user = User::findByUsername($this->username);
}
return $this->_user;
}
}
<?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 $username;
public $password;
public $rememberMe = true;
private $_user = false;
/**
* @return array the validation rules.
*/
public function rules()
{
return [
// username and password are both required
[['username', 'password'], 'required','message'=>'Поле не заполнено'],
// rememberMe must be a boolean value
['rememberMe', 'boolean'],
// password is validated by validatePassword()
['password', 'validatePassword'],
];
}
public function attributeLabels() {
return [
'username'=>'Логин',
'password'=>'Пароль'
];
}
/**
* 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 = $this->getUser();
if (!$user || !$user->validatePassword($this->password)) {
$this->addError($attribute, 'Неправильные учетные данные');
}
}
}
/**
* 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($this->getUser(), $this->rememberMe ? 3600*24*30 : 0);
}
return false;
}
/**
* Finds user by [[username]]
*
* @return User|null
*/
public function getUser()
{
if ($this->_user === false) {
$this->_user = User::findByUsername($this->username);
}
return $this->_user;
}
}
<?php
namespace app\models;
use Yii;
use yii\base\NotSupportedException;
use yii\db\ActiveRecord;
use yii\web\IdentityInterface;
class User extends \yii\db\ActiveRecord implements IdentityInterface
{
public static function tableName(){
return "users";
}
public static function findIdentity($id) {
return static::findOne($id);
}
public static function findIdentityByAccessToken($token, $type = null)
{
return static::findOne(['access_token' => $token]);
}
/**
* @return int|string current user ID
*/
public function getId()
{
return $this->id;
}
public function findByUsername($username) {
return static::findOne(["username"=>$username]);
}
/**
* @return string current user auth key
*/
public function getAuthKey()
{
return $this->authKey;
}
/**
* @param string $authKey
* @return bool if auth key is valid for current user
*/
public function validateAuthKey($authKey)
{
return $this->getAuthKey() === $authKey;
}
public function validatePassword($password)
{
return $this->paswordHash==$password;
}
public function setPassword($password)
{
$this->passwordHash=\Yii::$app->getSecurity()->generatePasswordHash($password);
}
public function beforeSave($insert)
{
if (parent::beforeSave($insert)) {
if ($this->isNewRecord) {
$this->authKey = \Yii::$app->security->generateRandomString();
$this->setPassword($this->password);
}
return true;
}
return false;
}
}
public function validatePassword($attribute, $params)
{
if (!$this->hasErrors()) {
$user = $this->getUser();
if (!$user || !Yii::$app->getSecurity()->validatePassword($password, $user->passwordHash)) {
$this->addError($attribute, 'Неправильные учетные данные');
}
}
}
public function validatePassword($attribute, $params)
{
if (!$this->hasErrors()) {
$user = $this->getUser();
if (!$user || !$user->validatePassword($this->password)) {
$this->addError($attribute, 'Неправильные учетные данные');
}
}
}
/**
* 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($this->getUser(), $this->rememberMe ? 3600*24*30 : 0);
}
return false;
}
public function validatePassword($password)
{
if (\Yii::$app->getSecurity()->validatePassword($password, $this->passwordHash)) {
return true;
}
else {
return false;
}
}
public function setPassword($password)
{
$this->passwordHash=\Yii::$app->getSecurity()->generatePasswordHash($password);
}
public function beforeSave($insert)
{
if (parent::beforeSave($insert)) {
if ($this->isNewRecord) {
$this->authKey = \Yii::$app->security->generateRandomString();
$this->setPassword($this->password);
}
return true;
}
return false;
}
}
а если бы заглянули, то увидели, что всё давно за Вас сделано, с применением и password_hash() и password_verify()
'grozzzny\depends\bootstrap4\Bootstrap4Asset',
'grozzzny\depends\bootstrap4\Bootstrap4PluginAsset
<?php
/* @var $this \yii\web\View */
/* @var $content string */
use yii\helpers\Html;
use app\assets\ProfileAsset;
ProfileAsset::register($this);
?>
<?php $this->beginPage() ?>
<!DOCTYPE html>
<html>
<head>
<meta charset="<?= Yii::$app->charset ?>">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<?php $this->registerCsrfMetaTags() ?>
<title><?= Html::encode($this->title) ?></title>
<?php $this->head() ?>
</head>
<body>
<?php $this->beginBody() ?>
<div class="overlay"></div>
<?=$content?>
<?php $this->endBody() ?>
</body>
</html>
<?php $this->endPage() ?>
$this->layout="profile";
return $this->render("test",array("data"=>"sadsadas"));
Выводит false и длину хэша 7 символов без каких-либо ошибок. Если же хэш взять в одинарные кавычки, то выводит true и длину хэша 60 символов. Интересно.