Описана базовая миграция, добавлена модель аккаунта, добавлена модель авторизации, написаны первичные тесты для этой модели, добавлен модуль авторизации, настроен базовый контроллер. Короче много чего сделано

This commit is contained in:
ErickSkrauch
2016-01-03 03:18:37 +03:00
parent 841303b8ab
commit 7b650e2654
40 changed files with 694 additions and 292 deletions

View File

@@ -13,7 +13,7 @@ return [
'controllerNamespace' => 'api\controllers',
'components' => [
'user' => [
'identityClass' => 'common\models\User',
'identityClass' => 'common\models\Account',
'enableAutoLogin' => true,
],
'log' => [
@@ -28,6 +28,17 @@ return [
'errorHandler' => [
'errorAction' => 'site/error',
],
'request' => [
'baseUrl' => '/api',
],
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [],
],
],
'modules' => [
'login' => 'api\modules\login\Module',
],
'params' => $params,
];

View File

@@ -0,0 +1,17 @@
<?php
namespace api\controllers;
class Controller extends \yii\rest\Controller {
public $enableCsrfValidation = true;
public function behaviors() {
$parentBehaviors = parent::behaviors();
// xml нам не понадобится
unset($parentBehaviors['contentNegotiator']['formats']['application/xml']);
return $parentBehaviors;
}
}

View File

@@ -1,17 +1,17 @@
<?php
namespace api\controllers;
use Yii;
use common\models\LoginForm;
use api\models\ContactForm;
use api\models\LoginForm;
use api\models\PasswordResetRequestForm;
use api\models\ResetPasswordForm;
use api\models\SignupForm;
use api\models\ContactForm;
use Yii;
use yii\base\InvalidParamException;
use yii\filters\AccessControl;
use yii\filters\VerbFilter;
use yii\web\BadRequestHttpException;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
/**
* Site controller

79
api/models/LoginForm.php Normal file
View File

@@ -0,0 +1,79 @@
<?php
namespace api\models;
use common\models\Account;
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 Account|null
*/
protected function getUser()
{
if ($this->_user === null) {
$this->_user = Account::findByEmail($this->username);
}
return $this->_user;
}
}

View File

@@ -1,7 +1,7 @@
<?php
namespace api\models;
use common\models\User;
use common\models\Account;
use yii\base\Model;
/**
@@ -22,7 +22,7 @@ class PasswordResetRequestForm extends Model
['email', 'email'],
['email', 'exist',
'targetClass' => '\common\models\User',
'filter' => ['status' => User::STATUS_ACTIVE],
'filter' => ['status' => Account::STATUS_ACTIVE],
'message' => 'There is no user with such email.'
],
];
@@ -35,14 +35,14 @@ class PasswordResetRequestForm extends Model
*/
public function sendEmail()
{
/* @var $user User */
$user = User::findOne([
'status' => User::STATUS_ACTIVE,
/* @var $user Account */
$user = Account::findOne([
'status' => Account::STATUS_ACTIVE,
'email' => $this->email,
]);
if ($user) {
if (!User::isPasswordResetTokenValid($user->password_reset_token)) {
if (!Account::isPasswordResetTokenValid($user->password_reset_token)) {
$user->generatePasswordResetToken();
}

View File

@@ -1,7 +1,7 @@
<?php
namespace api\models;
use common\models\User;
use common\models\Account;
use yii\base\InvalidParamException;
use yii\base\Model;
use Yii;
@@ -14,7 +14,7 @@ class ResetPasswordForm extends Model
public $password;
/**
* @var \common\models\User
* @var \common\models\Account
*/
private $_user;
@@ -31,7 +31,7 @@ class ResetPasswordForm extends Model
if (empty($token) || !is_string($token)) {
throw new InvalidParamException('Password reset token cannot be blank.');
}
$this->_user = User::findByPasswordResetToken($token);
$this->_user = Account::findByPasswordResetToken($token);
if (!$this->_user) {
throw new InvalidParamException('Wrong password reset token.');
}

View File

@@ -1,7 +1,7 @@
<?php
namespace api\models;
use common\models\User;
use common\models\Account;
use yii\base\Model;
use Yii;
@@ -39,13 +39,12 @@ class SignupForm extends Model
/**
* Signs user up.
*
* @return User|null the saved model or null if saving fails
* @return Account|null the saved model or null if saving fails
*/
public function signup()
{
if ($this->validate()) {
$user = new User();
$user->username = $this->username;
$user = new Account();
$user->email = $this->email;
$user->setPassword($this->password);
$user->generateAuthKey();

View File

@@ -0,0 +1,9 @@
<?php
namespace api\modules\login;
class Module extends \yii\base\Module {
public $id = 'login';
}

View File

@@ -0,0 +1,48 @@
<?php
namespace api\modules\login\controllers;
use api\controllers\Controller;
use api\modules\login\models\AuthenticationForm;
use Yii;
use yii\filters\AccessControl;
class AuthenticationController extends Controller {
public function behaviors() {
return array_merge(parent::behaviors(), [
'access' => [
'class' => AccessControl::className(),
'only' => ['login-info'],
'rules' => [
[
'actions' => ['login-info'],
'allow' => true,
'roles' => ['?'],
],
],
],
]);
}
public function verbs() {
return [
'loginInfo' => ['post'],
];
}
public function actionLoginInfo() {
$model = new AuthenticationForm();
$model->load(Yii::$app->request->post());
if (!$model->login()) {
return [
'success' => false,
'errors' => $model->getErrors(),
];
}
return [
'success' => true,
];
}
}

View File

@@ -0,0 +1,12 @@
<?php
namespace api\modules\login\controllers;
use api\controllers\Controller;
class DefaultController extends Controller {
public function actionIndex() {
return ['hello' => 'world'];
}
}

View File

View File

@@ -0,0 +1,70 @@
<?php
namespace api\modules\login\models;
use common\models\Account;
use Yii;
use yii\base\Model;
class AuthenticationForm extends Model {
public $email;
public $password;
public $rememberMe = true;
private $_user;
public function rules() {
return [
['email', 'required', 'message' => 'error.email_required'],
['email', 'email', 'message' => 'error.email_invalid'],
['email', 'validateEmail'],
['password', 'required', 'message' => 'error.password_required'],
['password', 'validatePassword'],
['rememberMe', 'boolean'],
];
}
public function validateEmail($attribute) {
if (!$this->hasErrors()) {
if ($this->getAccount() === NULL) {
$this->addError($attribute, 'error.email_not_exist');
}
}
}
public function validatePassword($attribute) {
if (!$this->hasErrors()) {
$account = $this->getAccount();
if (!$account || !$account->validatePassword($this->password)) {
$this->addError($attribute, 'error.password_incorrect');
}
}
}
/**
* 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 false;
}
return Yii::$app->user->login($this->getAccount(), $this->rememberMe ? 3600 * 24 * 30 : 0);
}
/**
* @return Account|null
*/
protected function getAccount() {
if ($this->_user === NULL) {
$this->_user = Account::findByEmail($this->email);
}
return $this->_user;
}
}

View File

@@ -34,17 +34,17 @@ AppAsset::register($this);
],
]);
$menuItems = [
['label' => 'Home', 'url' => ['/site/index']],
['label' => 'About', 'url' => ['/site/about']],
['label' => 'Contact', 'url' => ['/site/contact']],
['label' => 'Home', 'url' => ['site/index']],
['label' => 'About', 'url' => ['site/about']],
['label' => 'Contact', 'url' => ['site/contact']],
];
if (Yii::$app->user->isGuest) {
$menuItems[] = ['label' => 'Signup', 'url' => ['/site/signup']];
$menuItems[] = ['label' => 'Login', 'url' => ['/site/login']];
$menuItems[] = ['label' => 'Signup', 'url' => ['site/signup']];
$menuItems[] = ['label' => 'Login', 'url' => ['site/login']];
} else {
$menuItems[] = [
'label' => 'Logout (' . Yii::$app->user->identity->username . ')',
'url' => ['/site/logout'],
'url' => ['site/logout'],
'linkOptions' => ['data-method' => 'post']
];
}

View File

@@ -2,10 +2,10 @@
/* @var $this yii\web\View */
/* @var $form yii\bootstrap\ActiveForm */
/* @var $model \common\models\LoginForm */
/* @var $model \api\models\LoginForm */
use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
use yii\helpers\Html;
$this->title = 'Login';
$this->params['breadcrumbs'][] = $this->title;