Перенесена логика join операции для современных серверов.

Нужно признать, что перенесена она так себе, но в будущем я обязательно это перепишу.
This commit is contained in:
ErickSkrauch 2016-09-03 01:54:22 +03:00
parent 762fab447b
commit 34d725abe2
19 changed files with 543 additions and 6 deletions

View File

@ -7,6 +7,7 @@ use yii\web\User as YiiUserComponent;
* @property Identity|null $identity * @property Identity|null $identity
* *
* @method Identity|null getIdentity() * @method Identity|null getIdentity()
* @method Identity|null loginByAccessToken(string $token, $type = null)
*/ */
class Component extends YiiUserComponent { class Component extends YiiUserComponent {

View File

@ -2,11 +2,12 @@
namespace api\components; namespace api\components;
use api\modules\authserver\exceptions\AuthserverException; use api\modules\authserver\exceptions\AuthserverException;
use api\modules\session\exceptions\SessionServerException;
class ErrorHandler extends \yii\web\ErrorHandler { class ErrorHandler extends \yii\web\ErrorHandler {
public function convertExceptionToArray($exception) { public function convertExceptionToArray($exception) {
if ($exception instanceof AuthserverException) { if ($exception instanceof AuthserverException || $exception instanceof SessionServerException) {
return [ return [
'error' => $exception->getName(), 'error' => $exception->getName(),
'errorMessage' => $exception->getMessage(), 'errorMessage' => $exception->getMessage(),

View File

@ -9,7 +9,7 @@ $params = array_merge(
return [ return [
'id' => 'accounts-site-api', 'id' => 'accounts-site-api',
'basePath' => dirname(__DIR__), 'basePath' => dirname(__DIR__),
'bootstrap' => ['log', 'authserver'], 'bootstrap' => ['log', 'authserver', 'sessionserver'],
'controllerNamespace' => 'api\controllers', 'controllerNamespace' => 'api\controllers',
'params' => $params, 'params' => $params,
'components' => [ 'components' => [
@ -56,5 +56,8 @@ return [
'class' => \api\modules\authserver\Module::class, 'class' => \api\modules\authserver\Module::class,
'baseDomain' => $params['authserverDomain'], 'baseDomain' => $params['authserverDomain'],
], ],
'sessionserver' => [
'class' => \api\modules\session\Module::class,
],
], ],
]; ];

View File

@ -24,7 +24,7 @@ class ValidateForm extends Form {
throw new ForbiddenOperationException('Invalid token.'); throw new ForbiddenOperationException('Invalid token.');
} }
if (!$result->isActual()) { if ($result->isExpired()) {
$result->delete(); $result->delete();
throw new ForbiddenOperationException('Token expired.'); throw new ForbiddenOperationException('Token expired.');
} }

View File

@ -0,0 +1,31 @@
<?php
namespace api\modules\session;
use Yii;
use yii\base\BootstrapInterface;
class Module extends \yii\base\Module implements BootstrapInterface {
public $id = 'session';
public $defaultRoute = 'session';
/**
* @param \yii\base\Application $app the application currently running
*/
public function bootstrap($app) {
$app->getUrlManager()->addRules([
// TODO: define normal routes
//$this->baseDomain . '/' . $this->id . '/auth/<action>' => $this->id . '/authentication/<action>',
], false);
}
public static function info($message) {
Yii::info($message, 'session');
}
public static function error($message) {
Yii::info($message, 'session');
}
}

View File

@ -0,0 +1,28 @@
<?php
namespace api\modules\session\controllers;
use api\controllers\ApiController;
use api\modules\session\models\JoinForm;
class SessionController extends ApiController {
public function behaviors() {
$behaviors = parent::behaviors();
unset($behaviors['authenticator']);
return $behaviors;
}
public function actionJoin() {
$joinForm = new JoinForm();
$joinForm->loadByPost();
$joinForm->join();
return ['id' => 'OK'];
}
public function actionJoinLegacy() {
}
}

View File

@ -0,0 +1,10 @@
<?php
namespace api\modules\session\exceptions;
class ForbiddenOperationException extends SessionServerException {
public function __construct($message, $code = 0, \Exception $previous = null) {
parent::__construct($status = 401, $message, $code, $previous);
}
}

View File

@ -0,0 +1,10 @@
<?php
namespace api\modules\session\exceptions;
class IllegalArgumentException extends SessionServerException {
public function __construct($status = null, $message = null, $code = 0, \Exception $previous = null) {
parent::__construct(400, 'credentials can not be null.', $code, $previous);
}
}

View File

@ -0,0 +1,19 @@
<?php
namespace api\modules\session\exceptions;
use ReflectionClass;
use yii\web\HttpException;
class SessionServerException extends HttpException {
/**
* Рефлексия быстрее, как ни странно:
* @url https://coderwall.com/p/cpxxxw/php-get-class-name-without-namespace#comment_19313
*
* @return string
*/
public function getName() {
return (new ReflectionClass($this))->getShortName();
}
}

View File

@ -0,0 +1,27 @@
<?php
namespace api\modules\session\models;
use Yii;
use yii\base\Model;
abstract class Form extends Model {
public function formName() {
return '';
}
public function loadByGet() {
return $this->load(Yii::$app->request->get());
}
public function loadByPost() {
$data = Yii::$app->request->post();
// TODO: проверить, парсит ли Yii2 raw body и что он делает, если там неспаршенный json
/*if (empty($data)) {
$data = $request->getJsonRawBody(true);
}*/
return $this->load($data);
}
}

View File

@ -0,0 +1,122 @@
<?php
namespace api\modules\session\models;
use api\modules\session\exceptions\ForbiddenOperationException;
use api\modules\session\exceptions\IllegalArgumentException;
use api\modules\session\Module as Session;
use api\modules\session\validators\RequiredValidator;
use common\models\OauthScope as S;
use common\validators\UuidValidator;
use common\models\Account;
use common\models\MinecraftAccessKey;
use Yii;
use yii\base\ErrorException;
use yii\web\UnauthorizedHttpException;
class JoinForm extends Form {
public $accessToken;
public $selectedProfile;
public $serverId;
private $account;
public function rules() {
return [
[['accessToken', 'selectedProfile', 'serverId'], RequiredValidator::class],
[['accessToken', 'selectedProfile'], 'validateUuid'],
[['accessToken'], 'validateAccessToken'],
];
}
public function join() {
Session::info(
"User with access_token = '{$this->accessToken}' trying join to server with server_id = " .
"'{$this->serverId}'."
);
if (!$this->validate()) {
return false;
}
$account = $this->getAccount();
$sessionModel = new SessionModel($account->username, $this->serverId);
if (!$sessionModel->save()) {
throw new ErrorException('Cannot save join session model');
}
Session::info(
"User with access_token = '{$this->accessToken}' and nickname = '{$account->username}' successfully " .
"joined to server_id = '{$this->serverId}'."
);
return true;
}
public function validateUuid($attribute) {
if ($this->hasErrors($attribute)) {
return;
}
$validator = new UuidValidator();
$validator->validateAttribute($this, $attribute);
if ($this->hasErrors($attribute)) {
throw new IllegalArgumentException();
}
}
/**
* @throws \api\modules\session\exceptions\SessionServerException
*/
public function validateAccessToken() {
$accessToken = $this->accessToken;
/** @var MinecraftAccessKey|null $accessModel */
$accessModel = MinecraftAccessKey::findOne($accessToken);
if ($accessModel === null) {
try {
$identity = Yii::$app->apiUser->loginByAccessToken($accessToken);
} catch (UnauthorizedHttpException $e) {
$identity = null;
}
if ($identity === null) {
Session::error("User with access_token = '{$accessToken}' failed join by wrong access_token.");
throw new ForbiddenOperationException('Invalid access_token.');
}
if (!Yii::$app->apiUser->can(S::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|\common\models\OauthAccessToken $accessModel */
if ($accessModel->isExpired()) {
Session::error("User with access_token = '{$accessToken}' failed join by expired access_token.");
throw new ForbiddenOperationException('Expired access_token.');
}
if ($account->uuid !== $this->selectedProfile) {
Session::error(
"User with access_token = '{$accessToken}' trying to join with identity = '{$this->selectedProfile}'," .
" but access_token issued to account with id = '{$account->uuid}'."
);
throw new ForbiddenOperationException('Wrong selected_profile.');
}
$this->account = $account;
}
/**
* @return Account|null
*/
protected function getAccount() {
return $this->account;
}
}

View File

@ -0,0 +1,57 @@
<?php
namespace api\modules\session\models;
use Yii;
class SessionModel {
const KEY_TIME = 120; // 2 min
public $username;
public $serverId;
public function __construct(string $username, string $serverId) {
$this->username = $username;
$this->serverId = $serverId;
}
/**
* @param $username
* @param $serverId
*
* @return static|null
*/
public static function find($username, $serverId) {
$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;
}
public function save() {
$key = static::buildKey($this->username, $this->serverId);
$data = json_encode([
'username' => $this->username,
'serverId' => $this->serverId,
]);
return Yii::$app->redis->executeCommand('SETEX', [$key, self::KEY_TIME, $data]);
}
public function delete() {
return Yii::$app->redis->executeCommand('DEL', [static::buildKey($this->username, $this->serverId)]);
}
protected static function buildKey($username, $serverId) {
return md5('minecraft:join-server:' . mb_strtolower($username) . ':' . $serverId);
}
}

View File

@ -0,0 +1,25 @@
<?php
namespace api\modules\session\validators;
use api\modules\session\exceptions\IllegalArgumentException;
/**
* Для данного модуля нам не принципиально, что там за ошибка: если не хватает хотя бы одного
* параметра - тут же отправляем исключение и дело с концом
*/
class RequiredValidator extends \yii\validators\RequiredValidator {
/**
* @param string $value
* @return null
* @throws \api\modules\session\exceptions\SessionServerException
*/
protected function validateValue($value) {
if (parent::validateValue($value) !== null) {
throw new IllegalArgumentException();
}
return null;
}
}

View File

@ -53,8 +53,8 @@ class MinecraftAccessKey extends ActiveRecord {
return $this->hasOne(Account::class, ['id' => 'account_id']); return $this->hasOne(Account::class, ['id' => 'account_id']);
} }
public function isActual() : bool { public function isExpired() : bool {
return $this->updated_at + self::LIFETIME >= time(); return time() > $this->updated_at + self::LIFETIME;
} }
} }

View File

@ -39,7 +39,7 @@ class OauthAccessToken extends ActiveRecord {
return true; return true;
} }
public function isExpired() { public function isExpired() : bool {
return time() > $this->expire_time; return time() > $this->expire_time;
} }

View File

@ -0,0 +1,23 @@
<?php
namespace common\validators;
use InvalidArgumentException;
use Ramsey\Uuid\Uuid;
use yii\validators\Validator;
class UuidValidator extends Validator {
public $skipOnEmpty = false;
public $message = '{attribute} must be valid uuid';
public function validateAttribute($model, $attribute) {
try {
$uuid = Uuid::fromString($model->$attribute)->toString();
$model->$attribute = $uuid;
} catch (InvalidArgumentException $e) {
$this->addError($model, $attribute, $this->message, []);
}
}
}

View File

@ -0,0 +1,16 @@
<?php
namespace tests\codeception\api\_pages;
use yii\codeception\BasePage;
/**
* @property \tests\codeception\api\FunctionalTester $actor
*/
class SessionServerRoute extends BasePage {
public function join($params) {
$this->route = ['sessionserver/session/join'];
$this->actor->sendPOST($this->getUrl(), $params);
}
}

View File

@ -0,0 +1,111 @@
<?php
namespace tests\codeception\api\functional\sessionserver;
use common\models\OauthScope as S;
use Faker\Provider\Uuid;
use tests\codeception\api\_pages\SessionServerRoute;
use tests\codeception\api\functional\_steps\AuthserverSteps;
use tests\codeception\api\functional\_steps\OauthSteps;
use tests\codeception\api\FunctionalTester;
class JoinCest {
/**
* @var SessionServerRoute
*/
private $route;
public function _before(AuthserverSteps $I) {
$this->route = new SessionServerRoute($I);
}
public function joinByLegacyAuthserver(AuthserverSteps $I) {
$I->wantTo('join to server, using legacy authserver access token');
list($accessToken) = $I->amAuthenticated();
$this->route->join([
'accessToken' => $accessToken,
'selectedProfile' => 'df936908-b2e1-544d-96f8-2977ec213022',
'serverId' => Uuid::uuid(),
]);
$this->expectSuccessResponse($I);
}
public function joinByModernOauth2Token(OauthSteps $I) {
$I->wantTo('join to server, using moder oAuth2 generated token');
$accessToken = $I->getAccessToken([S::MINECRAFT_SERVER_SESSION]);
$this->route->join([
'accessToken' => $accessToken,
'selectedProfile' => 'df936908-b2e1-544d-96f8-2977ec213022',
'serverId' => Uuid::uuid(),
]);
$this->expectSuccessResponse($I);
}
public function joinByModernOauth2TokenWithoutPermission(OauthSteps $I) {
$I->wantTo('join to server, using moder oAuth2 generated token, but without minecraft auth permission');
$accessToken = $I->getAccessToken([S::ACCOUNT_INFO, S::ACCOUNT_EMAIL]);
$this->route->join([
'accessToken' => $accessToken,
'selectedProfile' => 'df936908-b2e1-544d-96f8-2977ec213022',
'serverId' => Uuid::uuid(),
]);
$I->seeResponseCodeIs(401);
$I->seeResponseIsJson();
$I->canSeeResponseContainsJson([
'error' => 'ForbiddenOperationException',
'errorMessage' => 'The token does not have required scope.',
]);
}
public function joinWithExpiredToken(FunctionalTester $I) {
$I->wantTo('join to some server with expired accessToken');
$this->route->join([
'accessToken' => '6042634a-a1e2-4aed-866c-c661fe4e63e2',
'selectedProfile' => 'df936908-b2e1-544d-96f8-2977ec213022',
'serverId' => Uuid::uuid(),
]);
$I->seeResponseCodeIs(401);
$I->seeResponseIsJson();
$I->canSeeResponseContainsJson([
'error' => 'ForbiddenOperationException',
'errorMessage' => 'Expired access_token.',
]);
}
public function wrongArguments(FunctionalTester $I) {
$I->wantTo('get error on wrong amount of arguments');
$this->route->join([
'wrong' => 'argument',
]);
$I->canSeeResponseCodeIs(400);
$I->canSeeResponseIsJson();
$I->canSeeResponseContainsJson([
'error' => 'IllegalArgumentException',
'errorMessage' => 'credentials can not be null.',
]);
}
public function joinWithWrongAccessToken(FunctionalTester $I) {
$I->wantTo('join to some server with wrong accessToken');
$this->route->join([
'accessToken' => Uuid::uuid(),
'selectedProfile' => 'df936908-b2e1-544d-96f8-2977ec213022',
'serverId' => Uuid::uuid(),
]);
$I->seeResponseCodeIs(401);
$I->seeResponseIsJson();
$I->canSeeResponseContainsJson([
'error' => 'ForbiddenOperationException',
'errorMessage' => 'Invalid access_token.',
]);
}
private function expectSuccessResponse(FunctionalTester $I) {
$I->seeResponseCodeIs(200);
$I->seeResponseIsJson();
$I->canSeeResponseContainsJson([
'id' => 'OK',
]);
}
}

View File

@ -0,0 +1,53 @@
<?php
namespace tests\codeception\common\unit\validators;
use Codeception\Specify;
use common\validators\UuidValidator;
use Faker\Provider\Uuid;
use tests\codeception\common\unit\TestCase;
use yii\base\Model;
class UuidValidatorTest extends TestCase {
use Specify;
public function testValidateAttribute() {
$this->specify('expected error if passed empty value', function() {
$model = new UuidTestModel();
expect($model->validate())->false();
expect($model->getErrors('attribute'))->equals(['Attribute must be valid uuid']);
});
$this->specify('expected error if passed invalid string', function() {
$model = new UuidTestModel();
$model->attribute = '123456789';
expect($model->validate())->false();
expect($model->getErrors('attribute'))->equals(['Attribute must be valid uuid']);
});
$this->specify('no errors if passed valid uuid', function() {
$model = new UuidTestModel();
$model->attribute = Uuid::uuid();
expect($model->validate())->true();
});
$this->specify('no errors if passed uuid string without dashes and converted to standart value', function() {
$model = new UuidTestModel();
$originalUuid = Uuid::uuid();
$model->attribute = str_replace('-', '', $originalUuid);
expect($model->validate())->true();
expect($model->attribute)->equals($originalUuid);
});
}
}
class UuidTestModel extends Model {
public $attribute;
public function rules() {
return [
['attribute', UuidValidator::class],
];
}
}