Первичное портирование логики сервера авторизации с PhalconPHP на Yii2

This commit is contained in:
ErickSkrauch 2016-08-21 02:21:39 +03:00
parent d0fcc8cd6f
commit b57b015f66
24 changed files with 573 additions and 9 deletions

View File

@ -9,7 +9,7 @@ $params = array_merge(
return [
'id' => 'accounts-site-api',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'bootstrap' => ['log', 'authserver'],
'controllerNamespace' => 'api\controllers',
'params' => $params,
'components' => [
@ -48,4 +48,10 @@ return [
'grantTypes' => ['authorization_code'],
],
],
'modules' => [
'authserver' => [
'class' => \api\modules\authserver\Module::class,
'baseDomain' => $params['authserverDomain'],
],
],
];

View File

@ -52,6 +52,7 @@ class LoginForm extends ApiForm {
}
public function validateActivity($attribute) {
// TODO: проверить, не заблокирован ли аккаунт
if (!$this->hasErrors()) {
$account = $this->getAccount();
if ($account->status !== Account::STATUS_ACTIVE) {

View File

@ -0,0 +1,34 @@
<?php
namespace api\modules\authserver;
use yii\base\BootstrapInterface;
use yii\base\InvalidConfigException;
class Module extends \yii\base\Module implements BootstrapInterface {
public $id = 'authserver';
public $defaultRoute = 'index';
/**
* @var string базовый домен, запросы на который этот модуль должен обрабатывать
*/
public $baseDomain = 'https://authserver.ely.by';
public function init() {
parent::init();
if ($this->baseDomain === null) {
throw new InvalidConfigException('base domain must be specified');
}
}
/**
* @param \yii\base\Application $app the application currently running
*/
public function bootstrap($app) {
$app->getUrlManager()->addRules([
$this->baseDomain . '/' . $this->id . '/auth/<action>' => $this->id . '/authentication/<action>',
], false);
}
}

View File

@ -0,0 +1,54 @@
<?php
namespace api\modules\authserver\controllers;
use api\controllers\Controller;
use api\modules\authserver\models;
class AuthenticationController extends Controller {
public function behaviors() {
$behaviors = parent::behaviors();
unset($behaviors['authenticator']);
return $behaviors;
}
public function actionAuthenticate() {
$model = new models\AuthenticationForm();
$model->loadByPost();
return $model->authenticate()->getResponseData(true);
}
public function refreshAction() {
$model = new models\RefreshTokenForm();
$model->loadByPost();
return $model->refresh()->getResponseData(false);
}
public function validateAction() {
$model = new models\ValidateForm();
$model->loadByPost();
$model->validateToken();
// В случае успеха ожидается пустой ответ. В случае ошибки же бросается исключение,
// которое обработает ErrorHandler
}
public function signoutAction() {
$model = new models\SignoutForm();
$model->loadByPost();
$model->signout();
// В случае успеха ожидается пустой ответ. В случае ошибки же бросается исключение,
// которое обработает ErrorHandler
}
public function invalidateAction() {
$model = new models\InvalidateForm();
$model->loadByPost();
$model->invalidateToken();
// В случае успеха ожидается пустой ответ. В случае ошибки же бросается исключение,
// которое обработает ErrorHandler
}
}

View File

@ -0,0 +1,15 @@
<?php
namespace api\modules\authserver\controllers;
use api\controllers\Controller;
class IndexController extends Controller {
// TODO: симулировать для этого модуля обработчик 404 ошибок, как был в фалконе
public function notFoundAction() {
/*return $this->response
->setStatusCode(404, 'Not Found')
->setContent('Page not found. Check our <a href="http://docs.ely.by">documentation site</a>.');*/
}
}

View File

@ -0,0 +1,8 @@
<?php
namespace api\modules\authserver\exceptions;
use yii\web\HttpException;
class AuthserverException extends HttpException {
}

View File

@ -0,0 +1,10 @@
<?php
namespace api\modules\authserver\exceptions;
class ForbiddenOperationException extends AuthserverException {
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\authserver\exceptions;
class IllegalArgumentException extends AuthserverException {
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,44 @@
<?php
namespace api\modules\authserver\models;
use common\models\MinecraftAccessKey;
class AuthenticateData {
/**
* @var MinecraftAccessKey
*/
private $minecraftAccessKey;
public function __construct(MinecraftAccessKey $minecraftAccessKey) {
$this->minecraftAccessKey = $minecraftAccessKey;
}
public function getMinecraftAccessKey() : MinecraftAccessKey {
return $this->minecraftAccessKey;
}
public function getResponseData(bool $includeAvailableProfiles = false) : array {
$accessKey = $this->minecraftAccessKey;
$account = $accessKey->account;
$result = [
'accessToken' => $accessKey->access_token,
'clientToken' => $accessKey->client_token,
'selectedProfile' => [
'id' => $account->uuid,
'name' => $account->username,
'legacy' => false,
],
];
if ($includeAvailableProfiles) {
// Сами моянги ещё ничего не придумали с этими availableProfiles
$availableProfiles[0] = $result['selectedProfile'];
$result['availableProfiles'] = $availableProfiles;
}
return $result;
}
}

View File

@ -0,0 +1,74 @@
<?php
namespace api\modules\authserver\models;
use api\models\authentication\LoginForm;
use api\modules\authserver\exceptions\ForbiddenOperationException;
use api\modules\authserver\validators\RequiredValidator;
use common\models\MinecraftAccessKey;
use Yii;
class AuthenticationForm extends Form {
public $username;
public $password;
public $clientToken;
public function rules() {
return [
[['username', 'password', 'clientToken'], RequiredValidator::class],
];
}
/**
* @return AuthenticateData
* @throws \api\modules\authserver\exceptions\AuthserverException
*/
public function authenticate() {
$this->validate();
Yii::info("Trying to authenticate user by login = '{$this->username}'.", 'legacy-authentication');
$loginForm = new LoginForm();
$loginForm->login = $this->username;
$loginForm->password = $this->password;
if (!$loginForm->validate()) {
$errors = $loginForm->getFirstErrors();
if (isset($errors['login'])) {
Yii::error("Cannot find user by login = '{$this->username}", 'legacy-authentication');
} elseif (isset($errors['password'])) {
Yii::error("User with login = '{$this->username}' passed wrong password.", 'legacy-authentication');
}
// На старом сервере авторизации использовалось поле nickname, а не username, так что сохраняем эту логику
$attribute = $loginForm->getLoginAttribute();
if ($attribute === 'username') {
$attribute = 'nickname';
}
// TODO: если аккаунт заблокирован, то возвращалось сообщение return "This account has been suspended."
// TODO: эта логика дублируется с логикой в SignoutForm
throw new ForbiddenOperationException("Invalid credentials. Invalid {$attribute} or password.");
}
$account = $loginForm->getAccount();
/** @var MinecraftAccessKey|null $accessTokenModel */
$accessTokenModel = MinecraftAccessKey::findOne(['client_token' => $this->clientToken]);
if ($accessTokenModel === null) {
$accessTokenModel = new MinecraftAccessKey();
$accessTokenModel->client_token = $this->clientToken;
$accessTokenModel->account_id = $account->id;
$accessTokenModel->insert();
} else {
$accessTokenModel->refreshPrimaryKeyValue();
}
$dataModel = new AuthenticateData($accessTokenModel);
Yii::info("User with id = {$account->id}, username = '{$account->username}' and email = '{$account->email}' successfully logged in.", 'legacy-authentication');
return $dataModel;
}
}

View File

@ -0,0 +1,23 @@
<?php
namespace api\modules\authserver\models;
use Yii;
use yii\base\Model;
abstract class Form extends Model {
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,37 @@
<?php
namespace api\modules\authserver\models;
use api\modules\authserver\validators\RequiredValidator;
use common\models\MinecraftAccessKey;
class InvalidateForm extends Form {
public $accessToken;
public $clientToken;
public function rules() {
return [
[['accessToken', 'clientToken'], RequiredValidator::class],
];
}
/**
* @return bool
* @throws \api\modules\authserver\exceptions\AuthserverException
*/
public function invalidateToken() : bool {
$this->validate();
$token = MinecraftAccessKey::findOne([
'access_token' => $this->accessToken,
'client_token' => $this->clientToken,
]);
if ($token !== null) {
$token->delete();
}
return true;
}
}

View File

@ -0,0 +1,45 @@
<?php
namespace api\modules\authserver\models;
use api\modules\authserver\exceptions\ForbiddenOperationException;
use api\modules\authserver\validators\RequiredValidator;
use common\models\MinecraftAccessKey;
class RefreshTokenForm extends Form {
public $accessToken;
public $clientToken;
public $selectedProfile;
public $requestUser;
public function rules() {
return [
[['accessToken', 'clientToken', 'selectedProfile', 'requestUser'], RequiredValidator::class],
];
}
/**
* @return AuthenticateData
* @throws \api\modules\authserver\exceptions\AuthserverException
*/
public function refresh() {
$this->validate();
/** @var MinecraftAccessKey|null $accessToken */
$accessToken = MinecraftAccessKey::findOne([
'access_token' => $this->accessToken,
'client_token' => $this->clientToken,
]);
if ($accessToken === null) {
throw new ForbiddenOperationException('Invalid token.');
}
$accessToken->refreshPrimaryKeyValue();
$accessToken->update();
$dataModel = new AuthenticateData($accessToken);
return $dataModel;
}
}

View File

@ -0,0 +1,51 @@
<?php
namespace api\modules\authserver\models;
use api\models\authentication\LoginForm;
use api\modules\authserver\exceptions\ForbiddenOperationException;
use api\modules\authserver\validators\RequiredValidator;
use common\models\MinecraftAccessKey;
use Yii;
class SignoutForm extends Form {
public $username;
public $password;
public function rules() {
return [
[['username', 'password'], RequiredValidator::class],
];
}
public function signout() : bool {
$this->validate();
$loginForm = new LoginForm();
$loginForm->login = $this->username;
$loginForm->password = $this->password;
if (!$loginForm->validate()) {
// На старом сервере авторизации использовалось поле nickname, а не username, так что сохраняем эту логику
$attribute = $loginForm->getLoginAttribute();
if ($attribute === 'username') {
$attribute = 'nickname';
}
throw new ForbiddenOperationException("Invalid credentials. Invalid {$attribute} or password.");
}
$account = $loginForm->getAccount();
/** @noinspection SqlResolve */
Yii::$app->db->createCommand('
DELETE
FROM ' . MinecraftAccessKey::tableName() . '
WHERE account_id = :userId
', [
'userId' => $account->id,
])->execute();
return true;
}
}

View File

@ -0,0 +1,35 @@
<?php
namespace api\modules\authserver\models;
use api\modules\authserver\exceptions\ForbiddenOperationException;
use api\modules\authserver\validators\RequiredValidator;
use common\models\MinecraftAccessKey;
class ValidateForm extends Form {
public $accessToken;
public function rules() {
return [
[['accessToken'], RequiredValidator::class],
];
}
public function validateToken() : bool {
$this->validate();
/** @var MinecraftAccessKey|null $result */
$result = MinecraftAccessKey::findOne($this->accessToken);
if ($result === null) {
throw new ForbiddenOperationException('Invalid token.');
}
if (!$result->isActual()) {
$result->delete();
throw new ForbiddenOperationException('Token expired.');
}
return true;
}
}

View File

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

View File

@ -25,18 +25,21 @@ class PrimaryKeyValueBehavior extends Behavior {
}
public function setPrimaryKeyValue() : bool {
$owner = $this->owner;
if ($owner->getPrimaryKey() === null) {
do {
$key = $this->generateValue();
} while ($this->isValueExists($key));
$owner->{$this->getPrimaryKeyName()} = $key;
if ($this->owner->getPrimaryKey() === null) {
$this->refreshPrimaryKeyValue();
}
return true;
}
public function refreshPrimaryKeyValue() {
do {
$key = $this->generateValue();
} while ($this->isValueExists($key));
$this->owner->{$this->getPrimaryKeyName()} = $key;
}
protected function generateValue() : string {
return (string)call_user_func($this->value);
}

View File

@ -43,6 +43,7 @@ use const common\LATEST_RULES_VERSION;
class Account extends ActiveRecord {
const STATUS_DELETED = -10;
const STATUS_BANNED = -1;
const STATUS_REGISTERED = 0;
const STATUS_ACTIVE = 10;

View File

@ -0,0 +1,60 @@
<?php
namespace common\models;
use common\behaviors\PrimaryKeyValueBehavior;
use Ramsey\Uuid\Uuid;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveQuery;
use yii\db\ActiveRecord;
/**
* Это временный класс, куда мигрирует вся логика ныне существующего authserver.ely.by.
* Поскольку там допускался вход по логину и паролю, а формат хранения выданных токенов был
* иным, то на период, пока мы окончательно не мигрируем, нужно сохранить старую логику
* и структуру под неё.
*
* Поля модели:
* @property string $access_token
* @property string $client_token
* @property integer $account_id
* @property integer $created_at
* @property integer $updated_at
*
* Отношения:
* @property Account $account
*
* Поведения:
* @mixin TimestampBehavior
* @mixin PrimaryKeyValueBehavior
*/
class MinecraftAccessKey extends ActiveRecord {
const LIFETIME = 172800; // Ключ актуален в течение 2 дней
public static function tableName() {
return '{{%minecraft_access_keys}}';
}
public function behaviors() {
return [
[
'class' => TimestampBehavior::class,
],
[
'class' => PrimaryKeyValueBehavior::class,
'value' => function() {
return Uuid::uuid4()->toString();
},
],
];
}
public function getAccount() : ActiveQuery {
return $this->hasOne(Account::class, ['id' => 'account_id']);
}
public function isActual() : bool {
return $this->timestamp + self::LIFETIME >= time();
}
}

View File

@ -0,0 +1,25 @@
<?php
use console\db\Migration;
class m160819_211139_minecraft_access_tokens extends Migration {
public function safeUp() {
$this->createTable('{{%minecraft_access_keys}}', [
'access_token' => $this->string(36)->notNull(),
'client_token' => $this->string(36)->notNull(),
'account_id' => $this->db->getTableSchema('{{%accounts}}')->getColumn('id')->dbType . ' NOT NULL',
'created_at' => $this->integer()->unsigned()->notNull(),
'updated_at' => $this->integer()->unsigned()->notNull(),
]);
$this->addPrimaryKey('access_token', '{{%minecraft_access_keys}}', 'access_token');
$this->addForeignKey('FK_minecraft_access_token_to_account', '{{%minecraft_access_keys}}', 'account_id', '{{%accounts}}', 'id', 'CASCADE', 'CASCADE');
$this->createIndex('client_token', '{{%minecraft_access_keys}}', 'client_token', true);
}
public function safeDown() {
$this->dropTable('{{%minecraft_access_keys}}');
}
}

View File

@ -1,4 +1,5 @@
<?php
return [
'userSecret' => 'some-long-secret-key',
'authserverDomain' => 'http://authserver.ely.by.local',
];

View File

@ -1,4 +1,5 @@
<?php
return [
'userSecret' => 'some-long-secret-key',
'authserverDomain' => 'https://authserver.ely.by',
];

View File

@ -1,4 +1,5 @@
<?php
return [
'userSecret' => 'some-long-secret-key',
'authserverDomain' => 'https://authserver.ely.by',
];

View File

@ -9,7 +9,7 @@ use yii\db\ActiveRecord;
class PrimaryKeyValueBehaviorTest extends TestCase {
use Specify;
public function testSetPrimaryKeyValue() {
public function testRefreshPrimaryKeyValue() {
$this->specify('method should generate value for primary key field on call', function() {
$model = new DummyModel();
/** @var PrimaryKeyValueBehavior|\PHPUnit_Framework_MockObject_MockObject $behavior */