Объединены сущности для авторизации посредством 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

@@ -18,7 +18,7 @@ class HasJoinedForm extends Model {
parent::__construct($config);
}
public function hasJoined() : Account {
public function hasJoined(): Account {
if (!$this->protocol->validate()) {
throw new IllegalArgumentException();
}

View File

@@ -7,10 +7,10 @@ use api\modules\session\models\protocols\JoinInterface;
use api\modules\session\Module as Session;
use api\modules\session\validators\RequiredValidator;
use common\helpers\StringHelper;
use common\models\OauthScope as S;
use common\validators\UuidValidator;
use common\rbac\Permissions as P;
use common\models\Account;
use common\models\MinecraftAccessKey;
use Ramsey\Uuid\Uuid;
use Yii;
use yii\base\ErrorException;
use yii\base\Model;
@@ -84,16 +84,7 @@ class JoinForm extends Model {
return;
}
if ($attribute === 'selectedProfile' && !StringHelper::isUuid($this->selectedProfile)) {
// Это нормально. Там может быть ник игрока, если это Legacy авторизация
return;
}
$validator = new UuidValidator();
$validator->allowNil = false;
$validator->validateAttribute($this, $attribute);
if ($this->hasErrors($attribute)) {
if ($this->$attribute === Uuid::NIL) {
throw new IllegalArgumentException();
}
}
@@ -105,9 +96,17 @@ class JoinForm extends Model {
$accessToken = $this->accessToken;
/** @var MinecraftAccessKey|null $accessModel */
$accessModel = MinecraftAccessKey::findOne($accessToken);
if ($accessModel === null) {
if ($accessModel !== null) {
/** @var MinecraftAccessKey|\api\components\OAuth2\Entities\AccessTokenEntity $accessModel */
if ($accessModel->isExpired()) {
Session::error("User with access_token = '{$accessToken}' failed join by expired access_token.");
throw new ForbiddenOperationException('Expired access_token.');
}
$account = $accessModel->account;
} else {
try {
$identity = Yii::$app->apiUser->loginByAccessToken($accessToken);
$identity = Yii::$app->user->loginByAccessToken($accessToken);
} catch (UnauthorizedHttpException $e) {
$identity = null;
}
@@ -117,21 +116,12 @@ class JoinForm extends Model {
throw new ForbiddenOperationException('Invalid access_token.');
}
if (!Yii::$app->apiUser->can(S::MINECRAFT_SERVER_SESSION)) {
if (!Yii::$app->user->can(P::MINECRAFT_SERVER_SESSION)) {
Session::error("User with access_token = '{$accessToken}' doesn't have enough scopes to make join.");
throw new ForbiddenOperationException('The token does not have required scope.');
}
$accessModel = $identity->getAccessToken();
$account = $identity->getAccount();
} else {
$account = $accessModel->account;
}
/** @var MinecraftAccessKey|\api\components\OAuth2\Entities\AccessTokenEntity $accessModel */
if ($accessModel->isExpired()) {
Session::error("User with access_token = '{$accessToken}' failed join by expired access_token.");
throw new ForbiddenOperationException('Expired access_token.');
}
$selectedProfile = $this->selectedProfile;
@@ -142,7 +132,9 @@ class JoinForm extends Model {
" but access_token issued to account with id = '{$account->uuid}'."
);
throw new ForbiddenOperationException('Wrong selected_profile.');
} elseif (!$isUuid && $account->username !== $selectedProfile) {
}
if (!$isUuid && $account->username !== $selectedProfile) {
Session::error(
"User with access_token = '{$accessToken}' trying to join with identity = '{$selectedProfile}'," .
" but access_token issued to account with username = '{$account->username}'."
@@ -153,10 +145,7 @@ class JoinForm extends Model {
$this->account = $account;
}
/**
* @return Account|null
*/
protected function getAccount() {
protected function getAccount(): Account {
return $this->account;
}

View File

@@ -17,24 +17,16 @@ class SessionModel {
$this->serverId = $serverId;
}
/**
* @param $username
* @param $serverId
*
* @return static|null
*/
public static function find($username, $serverId) {
public static function find(string $username, string $serverId): ?self {
$key = static::buildKey($username, $serverId);
$result = Yii::$app->redis->executeCommand('GET', [$key]);
if (!$result) {
/** @noinspection PhpIncompatibleReturnTypeInspection шторм что-то сума сходит, когда видит static */
return null;
}
$data = json_decode($result, true);
$model = new static($data['username'], $data['serverId']);
return $model;
return new static($data['username'], $data['serverId']);
}
public function save() {
@@ -51,15 +43,11 @@ class SessionModel {
return Yii::$app->redis->executeCommand('DEL', [static::buildKey($this->username, $this->serverId)]);
}
/**
* @return Account|null
* TODO: после перехода на PHP 7.1 установить тип как ?Account
*/
public function getAccount() {
public function getAccount(): ?Account {
return Account::findOne(['username' => $this->username]);
}
protected static function buildKey($username, $serverId) : string {
protected static function buildKey($username, $serverId): string {
return md5('minecraft:join-server:' . mb_strtolower($username) . ':' . $serverId);
}

View File

@@ -1,31 +1,30 @@
<?php
namespace api\modules\session\models\protocols;
use yii\validators\RequiredValidator;
abstract class BaseHasJoined implements HasJoinedInterface {
private $username;
private $serverId;
public function __construct(string $username, string $serverId) {
$this->username = $username;
$this->serverId = $serverId;
$this->username = trim($username);
$this->serverId = trim($serverId);
}
public function getUsername() : string {
public function getUsername(): string {
return $this->username;
}
public function getServerId() : string {
public function getServerId(): string {
return $this->serverId;
}
public function validate() : bool {
$validator = new RequiredValidator();
public function validate(): bool {
return !$this->isEmpty($this->username) && !$this->isEmpty($this->serverId);
}
return $validator->validate($this->username)
&& $validator->validate($this->serverId);
private function isEmpty($value): bool {
return $value === null || $value === '';
}
}

View File

@@ -3,12 +3,8 @@ namespace api\modules\session\models\protocols;
abstract class BaseJoin implements JoinInterface {
abstract public function getAccessToken() : string;
abstract public function getSelectedProfile() : string;
abstract public function getServerId() : string;
abstract public function validate() : bool;
protected function isEmpty($value): bool {
return $value === null || $value === '';
}
}

View File

@@ -3,10 +3,10 @@ namespace api\modules\session\models\protocols;
interface HasJoinedInterface {
public function getUsername() : string;
public function getUsername(): string;
public function getServerId() : string;
public function getServerId(): string;
public function validate() : bool;
public function validate(): bool;
}

View File

@@ -3,13 +3,12 @@ namespace api\modules\session\models\protocols;
interface JoinInterface {
public function getAccessToken() : string;
public function getAccessToken(): string;
// TODO: после перехода на PHP 7.1 сменить тип на ?string и возвращать null, если параметр не передан
public function getSelectedProfile() : string;
public function getSelectedProfile(): string;
public function getServerId() : string;
public function getServerId(): string;
public function validate() : bool;
public function validate(): bool;
}

View File

@@ -1,8 +1,6 @@
<?php
namespace api\modules\session\models\protocols;
use yii\validators\RequiredValidator;
class LegacyJoin extends BaseJoin {
private $user;
@@ -13,9 +11,9 @@ class LegacyJoin extends BaseJoin {
private $uuid;
public function __construct(string $user, string $sessionId, string $serverId) {
$this->user = $user;
$this->sessionId = $sessionId;
$this->serverId = $serverId;
$this->user = trim($user);
$this->sessionId = trim($sessionId);
$this->serverId = trim($serverId);
$this->parseSessionId($this->sessionId);
}
@@ -24,23 +22,19 @@ class LegacyJoin extends BaseJoin {
return $this->accessToken;
}
public function getSelectedProfile() : string {
public function getSelectedProfile(): string {
return $this->uuid ?: $this->user;
}
public function getServerId() : string {
public function getServerId(): string {
return $this->serverId;
}
/**
* @return bool
*/
public function validate() : bool {
$validator = new RequiredValidator();
return $validator->validate($this->accessToken)
&& $validator->validate($this->user)
&& $validator->validate($this->serverId);
public function validate(): bool {
return !$this->isEmpty($this->accessToken) && !$this->isEmpty($this->user) && !$this->isEmpty($this->serverId);
}
/**
@@ -50,7 +44,7 @@ class LegacyJoin extends BaseJoin {
* Бьём по ':' для учёта авторизации в современных лаунчерах и входе на более старую
* версию игры. Там sessionId передаётся как "token:{accessToken}:{uuid}", так что это нужно обработать
*/
protected function parseSessionId(string $sessionId) {
private function parseSessionId(string $sessionId) {
$parts = explode(':', $sessionId);
if (count($parts) === 3) {
$this->accessToken = $parts[1];

View File

@@ -1,8 +1,6 @@
<?php
namespace api\modules\session\models\protocols;
use yii\validators\RequiredValidator;
class ModernJoin extends BaseJoin {
private $accessToken;
@@ -10,29 +8,25 @@ class ModernJoin extends BaseJoin {
private $serverId;
public function __construct(string $accessToken, string $selectedProfile, string $serverId) {
$this->accessToken = $accessToken;
$this->selectedProfile = $selectedProfile;
$this->serverId = $serverId;
$this->accessToken = trim($accessToken);
$this->selectedProfile = trim($selectedProfile);
$this->serverId = trim($serverId);
}
public function getAccessToken() : string {
public function getAccessToken(): string {
return $this->accessToken;
}
public function getSelectedProfile() : string {
public function getSelectedProfile(): string {
return $this->selectedProfile;
}
public function getServerId() : string {
public function getServerId(): string {
return $this->serverId;
}
public function validate() : bool {
$validator = new RequiredValidator();
return $validator->validate($this->accessToken)
&& $validator->validate($this->selectedProfile)
&& $validator->validate($this->serverId);
public function validate(): bool {
return !$this->isEmpty($this->accessToken) && !$this->isEmpty($this->selectedProfile) && !$this->isEmpty($this->serverId);
}
}