'user' => [
'identityClass' => 'common\models\User',
'enableAutoLogin' => true,
'identityCookie' => ['name' => '_identity-frontend', 'httpOnly' => true],
],
class User extends ActiveRecord implements IdentityInterface
{
const STATUS_DELETED = 0;
const STATUS_ACTIVE = 10;
const STATUS_WAIT = 5;
const DATE_FORMAT = 'php:Y-m-d';
const DATETIME_FORMAT = 'php:Y-m-d H:i:s';
const TIME_FORMAT = 'php:H:i:s';
/**
* @inheritdoc
*/
public static function tableName()
{
return '{{%user}}';
}
/**
* @inheritdoc
*/
public function behaviors()
{
return [
TimestampBehavior::className(),
];
}
/**
* @inheritdoc
*/
public function rules()
{
return [
['status', 'default', 'value' => self::STATUS_ACTIVE],
['status', 'in', 'range' => [self::STATUS_DELETED, self::STATUS_WAIT, self::STATUS_ACTIVE]],
];
}
public function afterSave($insert, $changedAttributes)
{
$findUser = Score::find()->where(['user_id' => $this->getId()])->one();
if (!$findUser){
$userBalance = new Score;
$userBalance->user_id = $this->getId();
$userBalance->balance = 0;
if($userBalance->validate()){
return $userBalance->save();
} else die('Что-то пошло не так!');
}
parent::afterSave($insert, $changedAttributes);
}
public function getScore($userId = null)
{
if ($userId)
return $userScore = Score::find()->where(['user_id' => $userId])->one()->balance;
return $userScore = Score::find()->where(['user_id' => Yii::$app->user->id])->one()->balance;
}
/**
* @inheritdoc
*/
public static function findIdentity($id)
{
return static::findOne(['id' => $id, 'status' => self::STATUS_ACTIVE]);
}
/**
* @inheritdoc
*/
public static function findIdentityByAccessToken($token, $type = null)
{
throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
}
/**
* Finds user by username
*
* @param string $username
* @return static|null
*/
public static function findByUsername($username)
{
return static::findOne(['username' => $username]);
}
public static function getAllUsername()
{
$users = (new Query())->select(['username', 'id'])->from('user')->all();
foreach ($users as $value) {
$data[$value['id']] = $value['username'];
}
if (isset($data)) return $data;
else return false;
}
public function getAvatar()
{
if ($this->photo_type != 1)
return '/uploads/profile/'.$this->id.'/'.$this->photo;
else
return '/images/profile/'.$this->photo;
}
public static function getAll()
{
$data = self::find()->all();
return $data;
}
/**
* Finds user by password reset token
*
* @param string $token password reset token
* @return static|null
*/
public static function findByPasswordResetToken($token)
{
if (!static::isPasswordResetTokenValid($token)) {
return null;
}
return static::findOne([
'password_reset_token' => $token,
'status' => self::STATUS_ACTIVE,
]);
}
/**
* Finds out if password reset token is valid
*
* @param string $token password reset token
* @return bool
*/
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();
}
/**
* @inheritdoc
*/
public function getId()
{
return $this->getPrimaryKey();
}
/**
* @inheritdoc
*/
public function getAuthKey()
{
return $this->auth_key;
}
/**
* @inheritdoc
*/
public function validateAuthKey($authKey)
{
return $this->getAuthKey() === $authKey;
}
/**
* Validates password
*
* @param string $password password to validate
* @return bool if password provided is valid for current user
*/
public function validatePassword($password)
{
return Yii::$app->security->validatePassword($password, $this->password_hash);
}
/**
* Generates password hash from password and sets it to the model
*
* @param string $password
*/
public function setPassword($password)
{
$this->password_hash = Yii::$app->security->generatePasswordHash($password);
}
/**
* Generates "remember me" authentication key
*/
public function generateAuthKey()
{
$this->auth_key = Yii::$app->security->generateRandomString();
}
/**
* Generates new password reset token
*/
public function generatePasswordResetToken()
{
$this->password_reset_token = Yii::$app->security->generateRandomString() . '_' . time();
}
/**
* Removes password reset token
*/
public function removePasswordResetToken()
{
$this->password_reset_token = null;
}
}
<?php
namespace common\models;
use Yii;
use yii\base\Model;
/**
* Login form
*/
class LoginForm extends Model
{
public $username;
public $password;
public $rememberMe = true;
private $_user;
/**
* @inheritdoc
*/
public function rules()
{
return [
// username and password are both required
[['username', 'password'], 'required'],
// rememberMe must be a boolean value
['rememberMe', 'boolean'],
// password is validated by validatePassword()
['password', 'validatePassword'],
];
}
public function attributeLabels()
{
return [
'username' => 'Логин',
'password' => 'Пароль',
'rememberMe' => 'Запомнить меня'
];
}
/**
* 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()) {
$user = $this->getUser();
if($user->status === User::STATUS_ACTIVE)
return Yii::$app->user->login($this->getUser(), 60 * 60 * 24 * 365);
if($user->status === User::STATUS_WAIT)
throw new \DomainException('Для завершения регистрации подтвердите адрес электронной почты. <br> Проверить свою электронную почту.');
} else
return false;
}
/**
* Finds user by [[username]]
*
* @return User|null
*/
protected function getUser()
{
if ($this->_user === null) {
$this->_user = User::findByUsername($this->username);
}
return $this->_user;
}
}
public function actionLogin()
{
if (!Yii::$app->user->isGuest) {
return $this->goHome();
}
$form = new LoginForm();
if ($form->load(Yii::$app->request->post())) {
try {
if($form->login())
return $this->goBack();
} catch (\DomainException $e) {
Yii::$app->session->setFlash('error', $e->getMessage());
}
}
return $this->render('login', [
'model' => $form,
]);
}
[
'class' => 'yii\web\GroupUrlRule',
'prefix' => 'profile',
'routePrefix' => 'profile',
'rules' => [
'<username>' => 'view',
'/profile/edit' => 'update',
],
],
$model->save
'layout' => "{sorter}\n{summary}\n{items}\n{pager}",
$dataProvider->sort->link('number_chapters');
$dataProvider->sort->link('-number_chapters');