mirror of
https://github.com/elyby/accounts.git
synced 2025-05-31 14:11:46 +05:30
Описана базовая миграция, добавлена модель аккаунта, добавлена модель авторизации, написаны первичные тесты для этой модели, добавлен модуль авторизации, настроен базовый контроллер. Короче много чего сделано
This commit is contained in:
15
common/components/UserPass.php
Normal file
15
common/components/UserPass.php
Normal file
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
namespace api\components;
|
||||
|
||||
|
||||
/**
|
||||
* Этот класс был использован для изначальной генерации паролей на Ely.by и сейчас должен быть планомерно выпилен
|
||||
* с проекта с целью заменить этот алгоритм каким-нибудь посерьёзнее.
|
||||
*/
|
||||
class UserPass {
|
||||
|
||||
public static function make ($email, $pass) {
|
||||
return md5($pass . md5(strtolower($email)));
|
||||
}
|
||||
|
||||
}
|
@@ -13,5 +13,8 @@ return [
|
||||
'class' => 'yii\swiftmailer\Mailer',
|
||||
'viewPath' => '@common/mail',
|
||||
],
|
||||
'security' => [
|
||||
'passwordHashStrategy' => 'password_hash',
|
||||
]
|
||||
],
|
||||
];
|
||||
|
@@ -2,12 +2,12 @@
|
||||
use yii\helpers\Html;
|
||||
|
||||
/* @var $this yii\web\View */
|
||||
/* @var $user common\models\User */
|
||||
/* @var $user common\models\Account */
|
||||
|
||||
$resetLink = Yii::$app->urlManager->createAbsoluteUrl(['site/reset-password', 'token' => $user->password_reset_token]);
|
||||
?>
|
||||
<div class="password-reset">
|
||||
<p>Hello <?= Html::encode($user->username) ?>,</p>
|
||||
<p>Hello <?= Html::encode($user->email) ?>,</p>
|
||||
|
||||
<p>Follow the link below to reset your password:</p>
|
||||
|
||||
|
@@ -1,11 +1,11 @@
|
||||
<?php
|
||||
|
||||
/* @var $this yii\web\View */
|
||||
/* @var $user common\models\User */
|
||||
/* @var $user common\models\Account */
|
||||
|
||||
$resetLink = Yii::$app->urlManager->createAbsoluteUrl(['site/reset-password', 'token' => $user->password_reset_token]);
|
||||
?>
|
||||
Hello <?= $user->username ?>,
|
||||
Hello <?= $user->email ?>,
|
||||
|
||||
Follow the link below to reset your password:
|
||||
|
||||
|
208
common/models/Account.php
Normal file
208
common/models/Account.php
Normal file
@@ -0,0 +1,208 @@
|
||||
<?php
|
||||
namespace common\models;
|
||||
|
||||
use api\components\UserPass;
|
||||
use Yii;
|
||||
use yii\base\InvalidConfigException;
|
||||
use yii\base\NotSupportedException;
|
||||
use yii\behaviors\TimestampBehavior;
|
||||
use yii\db\ActiveRecord;
|
||||
use yii\web\IdentityInterface;
|
||||
|
||||
/**
|
||||
* Поля модели:
|
||||
* @property integer $id
|
||||
* @property string $uuid
|
||||
* @property string $password_hash
|
||||
* @property integer $password_hash_strategy
|
||||
* @property string $password_reset_token
|
||||
* @property string $email
|
||||
* @property string $auth_key
|
||||
* @property integer $status
|
||||
* @property integer $created_at
|
||||
* @property integer $updated_at
|
||||
*
|
||||
* Геттеры-сеттеры:
|
||||
* @property string $password пароль пользователя (только для записи)
|
||||
*/
|
||||
class Account extends ActiveRecord implements IdentityInterface {
|
||||
|
||||
const STATUS_DELETED = -10;
|
||||
const STATUS_REGISTERED = 0;
|
||||
const STATUS_ACTIVE = 10;
|
||||
|
||||
const PASS_HASH_STRATEGY_OLD_ELY = 0;
|
||||
const PASS_HASH_STRATEGY_YII2 = 1;
|
||||
|
||||
public static function tableName() {
|
||||
return '{{%accounts}}';
|
||||
}
|
||||
|
||||
public function behaviors() {
|
||||
return [
|
||||
TimestampBehavior::className(),
|
||||
];
|
||||
}
|
||||
|
||||
public function rules() {
|
||||
return [
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritdoc
|
||||
*/
|
||||
public static function findIdentity($id) {
|
||||
return static::findOne(['id' => $id]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritdoc
|
||||
*/
|
||||
public static function findIdentityByAccessToken($token, $type = null) {
|
||||
throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $email
|
||||
* @return static|null
|
||||
*/
|
||||
public static function findByEmail($email) {
|
||||
return static::findOne(['email' => $email]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds user by password reset token
|
||||
*
|
||||
* @param string $token password reset token
|
||||
*
|
||||
* @return static|null
|
||||
*
|
||||
* TODO: этот метод нужно убрать из базовой модели
|
||||
*/
|
||||
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 boolean
|
||||
*
|
||||
* TODO: этот метод нужно убрать из базовой модели
|
||||
*/
|
||||
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
|
||||
* @param integer $passwordHashStrategy
|
||||
*
|
||||
* @return bool if password provided is valid for current user
|
||||
* @throws InvalidConfigException
|
||||
*/
|
||||
public function validatePassword($password, $passwordHashStrategy = NULL) {
|
||||
if ($passwordHashStrategy === NULL) {
|
||||
$passwordHashStrategy = $this->password_hash_strategy;
|
||||
}
|
||||
|
||||
switch($passwordHashStrategy) {
|
||||
case self::PASS_HASH_STRATEGY_OLD_ELY:
|
||||
$hashedPass = UserPass::make($this->email, $password);
|
||||
return $hashedPass === $this->password_hash;
|
||||
|
||||
case self::PASS_HASH_STRATEGY_YII2:
|
||||
return Yii::$app->security->validatePassword($password, $this->password_hash);
|
||||
|
||||
default:
|
||||
throw new InvalidConfigException('You must set valid password_hash_strategy before you can validate password');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $password
|
||||
* @throws InvalidConfigException
|
||||
*/
|
||||
public function setPassword($password) {
|
||||
switch($this->password_hash_strategy) {
|
||||
case self::PASS_HASH_STRATEGY_OLD_ELY:
|
||||
$password = UserPass::make($this->email, $password);
|
||||
break;
|
||||
|
||||
case self::PASS_HASH_STRATEGY_YII2:
|
||||
$password = Yii::$app->security->generatePasswordHash($password);
|
||||
break;
|
||||
|
||||
default:
|
||||
throw new InvalidConfigException('You must specify password_hash_strategy before you can set password');
|
||||
}
|
||||
|
||||
$this->password_hash = $password;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates "remember me" authentication key
|
||||
*/
|
||||
public function generateAuthKey() {
|
||||
$this->auth_key = Yii::$app->security->generateRandomString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates new password reset token
|
||||
*
|
||||
* TODO: этот метод нужно отсюда убрать
|
||||
*/
|
||||
public function generatePasswordResetToken() {
|
||||
$this->password_reset_token = Yii::$app->security->generateRandomString() . '_' . time();
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes password reset token
|
||||
*
|
||||
* TODO: этот метод нужно отсюда убрать
|
||||
*/
|
||||
public function removePasswordResetToken() {
|
||||
$this->password_reset_token = null;
|
||||
}
|
||||
|
||||
}
|
@@ -1,78 +0,0 @@
|
||||
<?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'],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 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, 'Incorrect username or password.');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Logs in a user using the provided username and password.
|
||||
*
|
||||
* @return boolean 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);
|
||||
} 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;
|
||||
}
|
||||
}
|
@@ -1,188 +0,0 @@
|
||||
<?php
|
||||
namespace common\models;
|
||||
|
||||
use Yii;
|
||||
use yii\base\NotSupportedException;
|
||||
use yii\behaviors\TimestampBehavior;
|
||||
use yii\db\ActiveRecord;
|
||||
use yii\web\IdentityInterface;
|
||||
|
||||
/**
|
||||
* User model
|
||||
*
|
||||
* @property integer $id
|
||||
* @property string $username
|
||||
* @property string $password_hash
|
||||
* @property string $password_reset_token
|
||||
* @property string $email
|
||||
* @property string $auth_key
|
||||
* @property integer $status
|
||||
* @property integer $created_at
|
||||
* @property integer $updated_at
|
||||
* @property string $password write-only password
|
||||
*/
|
||||
class User extends ActiveRecord implements IdentityInterface
|
||||
{
|
||||
const STATUS_DELETED = 0;
|
||||
const STATUS_ACTIVE = 10;
|
||||
|
||||
/**
|
||||
* @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_ACTIVE, self::STATUS_DELETED]],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @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, 'status' => self::STATUS_ACTIVE]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 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();
|
||||
}
|
||||
|
||||
/**
|
||||
* @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 boolean 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;
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user