Перенесена логика 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

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