Объединены сущности для авторизации посредством JWT токенов и токенов, выданных через oAuth2.

Все действия, связанные с аккаунтами, теперь вызываются через url `/api/v1/accounts/<id>/<action>`.
Добавлена вменяемая система разграничения прав на основе RBAC.
Теперь oAuth2 токены генерируются как случайная строка в 40 символов длинной, а не UUID.
Исправлен баг с неправильным временем жизни токена в ответе успешного запроса аутентификации.
Теперь все unit тесты можно успешно прогнать без наличия интернета.
This commit is contained in:
ErickSkrauch
2017-09-19 20:06:16 +03:00
parent 928b3aa7fc
commit dd2c4bc413
173 changed files with 2719 additions and 2748 deletions

View File

@@ -1,58 +1,42 @@
<?php
namespace api\modules\internal\controllers;
use api\components\ApiUser\AccessControl;
use api\controllers\Controller;
use api\modules\internal\models\BanForm;
use api\modules\internal\models\PardonForm;
use common\models\Account;
use common\models\OauthScope as S;
use Yii;
use common\rbac\Permissions as P;
use yii\filters\AccessControl;
use yii\helpers\ArrayHelper;
use yii\web\BadRequestHttpException;
use yii\web\NotFoundHttpException;
class AccountsController extends Controller {
public function behaviors() {
public function behaviors(): array {
return ArrayHelper::merge(parent::behaviors(), [
'authenticator' => [
'user' => Yii::$app->apiUser,
],
'access' => [
'class' => AccessControl::class,
'rules' => [
[
'actions' => ['ban'],
'allow' => true,
'roles' => [S::ACCOUNT_BLOCK],
],
[
'actions' => ['info'],
'allow' => true,
'roles' => [S::INTERNAL_ACCOUNT_INFO],
'roles' => [P::OBTAIN_EXTENDED_ACCOUNT_INFO],
'roleParams' => function() {
return [
'accountId' => 0,
];
},
],
],
],
]);
}
public function verbs() {
public function verbs(): array {
return [
'ban' => ['POST', 'DELETE'],
'info' => ['GET'],
];
}
public function actionBan(int $accountId) {
$account = $this->findAccount($accountId);
if (Yii::$app->request->isPost) {
return $this->banAccount($account);
} else {
return $this->pardonAccount($account);
}
}
public function actionInfo(int $id = null, string $username = null, string $uuid = null) {
if ($id !== null) {
$account = Account::findOne($id);
@@ -76,43 +60,4 @@ class AccountsController extends Controller {
];
}
private function banAccount(Account $account) {
$model = new BanForm($account);
$model->load(Yii::$app->request->post());
if (!$model->ban()) {
return [
'success' => false,
'errors' => $model->getFirstErrors(),
];
}
return [
'success' => true,
];
}
private function pardonAccount(Account $account) {
$model = new PardonForm($account);
$model->load(Yii::$app->request->post());
if (!$model->pardon()) {
return [
'success' => false,
'errors' => $model->getFirstErrors(),
];
}
return [
'success' => true,
];
}
private function findAccount(int $accountId): Account {
$account = Account::findOne($accountId);
if ($account === null) {
throw new NotFoundHttpException();
}
return $account;
}
}

View File

@@ -1,95 +0,0 @@
<?php
namespace api\modules\internal\models;
use api\models\base\ApiForm;
use api\modules\internal\helpers\Error as E;
use common\helpers\Amqp;
use common\models\Account;
use common\models\amqp\AccountBanned;
use PhpAmqpLib\Message\AMQPMessage;
use Yii;
use yii\base\ErrorException;
class BanForm extends ApiForm {
public const DURATION_FOREVER = -1;
/**
* Нереализованный функционал блокировки аккаунта на определённый период времени.
* Сейчас установка этого параметра ничего не даст, аккаунт будет заблокирован навечно,
* но, по задумке, здесь можно передать количество секунд, на которое будет
* заблокирован аккаунт пользователя.
*
* @var int
*/
public $duration = self::DURATION_FOREVER;
/**
* Нереализованный функционал указания причины блокировки аккаунта.
*
* @var string
*/
public $message = '';
/**
* @var Account
*/
private $account;
public function rules(): array {
return [
[['duration'], 'integer', 'min' => self::DURATION_FOREVER],
[['message'], 'string'],
[['account'], 'validateAccountActivity'],
];
}
public function getAccount(): Account {
return $this->account;
}
public function validateAccountActivity() {
if ($this->account->status === Account::STATUS_BANNED) {
$this->addError('account', E::ACCOUNT_ALREADY_BANNED);
}
}
public function ban(): bool {
if (!$this->validate()) {
return false;
}
$transaction = Yii::$app->db->beginTransaction();
$account = $this->account;
$account->status = Account::STATUS_BANNED;
if (!$account->save()) {
throw new ErrorException('Cannot ban account');
}
$this->createTask();
$transaction->commit();
return true;
}
public function createTask(): void {
$model = new AccountBanned();
$model->accountId = $this->account->id;
$model->duration = $this->duration;
$model->message = $this->message;
$message = Amqp::getInstance()->prepareMessage($model, [
'delivery_mode' => AMQPMessage::DELIVERY_MODE_PERSISTENT,
]);
Amqp::sendToEventsExchange('accounts.account-banned', $message);
}
public function __construct(Account $account, array $config = []) {
$this->account = $account;
parent::__construct($config);
}
}

View File

@@ -1,72 +0,0 @@
<?php
namespace api\modules\internal\models;
use api\models\base\ApiForm;
use api\modules\internal\helpers\Error as E;
use common\helpers\Amqp;
use common\models\Account;
use common\models\amqp\AccountPardoned;
use PhpAmqpLib\Message\AMQPMessage;
use Yii;
use yii\base\ErrorException;
class PardonForm extends ApiForm {
/**
* @var Account
*/
private $account;
public function rules(): array {
return [
[['account'], 'validateAccountBanned'],
];
}
public function getAccount(): Account {
return $this->account;
}
public function validateAccountBanned(): void {
if ($this->account->status !== Account::STATUS_BANNED) {
$this->addError('account', E::ACCOUNT_NOT_BANNED);
}
}
public function pardon(): bool {
if (!$this->validate()) {
return false;
}
$transaction = Yii::$app->db->beginTransaction();
$account = $this->account;
$account->status = Account::STATUS_ACTIVE;
if (!$account->save()) {
throw new ErrorException('Cannot pardon account');
}
$this->createTask();
$transaction->commit();
return true;
}
public function createTask(): void {
$model = new AccountPardoned();
$model->accountId = $this->account->id;
$message = Amqp::getInstance()->prepareMessage($model, [
'delivery_mode' => AMQPMessage::DELIVERY_MODE_PERSISTENT,
]);
Amqp::sendToEventsExchange('accounts.account-pardoned', $message);
}
public function __construct(Account $account, array $config = []) {
$this->account = $account;
parent::__construct($config);
}
}