Implementation of the backend for the OAuth2 clients management

This commit is contained in:
ErickSkrauch
2018-02-28 01:27:35 +03:00
parent ddec87e3a9
commit 673429e577
55 changed files with 1810 additions and 65 deletions

View File

@@ -3,16 +3,40 @@ namespace tests\codeception\api\_pages;
class OauthRoute extends BasePage {
public function validate($queryParams) {
public function validate(array $queryParams): void {
$this->getActor()->sendGET('/oauth2/v1/validate', $queryParams);
}
public function complete($queryParams = [], $postParams = []) {
public function complete(array $queryParams = [], array $postParams = []): void {
$this->getActor()->sendPOST('/oauth2/v1/complete?' . http_build_query($queryParams), $postParams);
}
public function issueToken($postParams = []) {
public function issueToken(array $postParams = []): void {
$this->getActor()->sendPOST('/oauth2/v1/token', $postParams);
}
public function createClient(string $type, array $postParams): void {
$this->getActor()->sendPOST('/v1/oauth2/' . $type, $postParams);
}
public function updateClient(string $clientId, array $params): void {
$this->getActor()->sendPUT('/v1/oauth2/' . $clientId, $params);
}
public function deleteClient(string $clientId): void {
$this->getActor()->sendDELETE('/v1/oauth2/' . $clientId);
}
public function resetClient(string $clientId, bool $regenerateSecret = false): void {
$this->getActor()->sendPOST("/v1/oauth2/$clientId/reset" . ($regenerateSecret ? '?regenerateSecret' : ''));
}
public function getClient(string $clientId): void {
$this->getActor()->sendGET("/v1/oauth2/$clientId");
}
public function getPerAccount(int $accountId): void {
$this->getActor()->sendGET("/v1/accounts/$accountId/oauth2/clients");
}
}

View File

@@ -22,7 +22,6 @@ coverage:
- ../../../api/*
exclude:
- ../../../api/config/*
- ../../../api/mails/*
- ../../../api/web/*
- ../../../api/runtime/*
c3url: 'http://localhost/api/web/index.php'

View File

@@ -0,0 +1,92 @@
<?php
namespace tests\codeception\api\oauth;
use tests\codeception\api\_pages\OauthRoute;
use tests\codeception\api\FunctionalTester;
class CreateClientCest {
/**
* @var OauthRoute
*/
private $route;
public function _before(FunctionalTester $I) {
$this->route = new OauthRoute($I);
}
public function testCreateApplicationWithWrongParams(FunctionalTester $I) {
$I->amAuthenticated('admin');
$this->route->createClient('application', []);
$I->canSeeResponseCodeIs(200);
$I->canSeeResponseContainsJson([
'success' => false,
'errors' => [
'name' => 'error.name_required',
'redirectUri' => 'error.redirectUri_required',
],
]);
$this->route->createClient('application', [
'name' => 'my test oauth client',
'redirectUri' => 'localhost',
]);
$I->canSeeResponseCodeIs(200);
$I->canSeeResponseContainsJson([
'success' => false,
'errors' => [
'redirectUri' => 'error.redirectUri_invalid',
],
]);
}
public function testCreateApplication(FunctionalTester $I) {
$I->amAuthenticated('admin');
$this->route->createClient('application', [
'name' => 'My admin application',
'description' => 'Application description.',
'redirectUri' => 'http://some-site.com/oauth/ely',
'websiteUrl' => 'http://some-site.com',
]);
$I->canSeeResponseCodeIs(200);
$I->canSeeResponseIsJson();
$I->canSeeResponseContainsJson([
'success' => true,
'data' => [
'clientId' => 'my-admin-application',
'name' => 'My admin application',
'description' => 'Application description.',
'websiteUrl' => 'http://some-site.com',
'countUsers' => 0,
'redirectUri' => 'http://some-site.com/oauth/ely',
],
]);
$I->canSeeResponseJsonMatchesJsonPath('$.data.clientSecret');
$I->canSeeResponseJsonMatchesJsonPath('$.data.createdAt');
}
public function testCreateMinecraftServer(FunctionalTester $I) {
$I->amAuthenticated('admin');
$this->route->createClient('minecraft-server', [
'name' => 'My amazing server',
'websiteUrl' => 'http://some-site.com',
'minecraftServerIp' => 'hypixel.com:25565',
]);
$I->canSeeResponseCodeIs(200);
$I->canSeeResponseIsJson();
$I->canSeeResponseContainsJson([
'success' => true,
'data' => [
'clientId' => 'my-amazing-server',
'name' => 'My amazing server',
'websiteUrl' => 'http://some-site.com',
'countUsers' => 0,
'minecraftServerIp' => 'hypixel.com:25565',
],
]);
$I->canSeeResponseJsonMatchesJsonPath('$.data.clientSecret');
$I->canSeeResponseJsonMatchesJsonPath('$.data.createdAt');
}
}

View File

@@ -0,0 +1,28 @@
<?php
namespace tests\codeception\api\oauth;
use tests\codeception\api\_pages\OauthRoute;
use tests\codeception\api\FunctionalTester;
class DeleteClientCest {
/**
* @var OauthRoute
*/
private $route;
public function _before(FunctionalTester $I) {
$this->route = new OauthRoute($I);
}
public function testDelete(FunctionalTester $I) {
$I->amAuthenticated('TwoOauthClients');
$this->route->deleteClient('first-test-oauth-client');
$I->canSeeResponseCodeIs(200);
$I->canSeeResponseIsJson();
$I->canSeeResponseContainsJson([
'success' => true,
]);
}
}

View File

@@ -0,0 +1,89 @@
<?php
namespace tests\codeception\api\oauth;
use tests\codeception\api\_pages\OauthRoute;
use tests\codeception\api\FunctionalTester;
class GetClientsCest {
/**
* @var OauthRoute
*/
private $route;
public function _before(FunctionalTester $I) {
$this->route = new OauthRoute($I);
}
public function testGet(FunctionalTester $I) {
$I->amAuthenticated('admin');
$this->route->getClient('admin-oauth-client');
$I->canSeeResponseCodeIs(200);
$I->canSeeResponseIsJson();
$I->canSeeResponseContainsJson([
'clientId' => 'admin-oauth-client',
'clientSecret' => 'FKyO71iCIlv4YM2IHlLbhsvYoIJScUzTZt1kEK7DQLXXYISLDvURVXK32Q58sHWS',
'type' => 'application',
'name' => 'Admin\'s oauth client',
'description' => 'Personal oauth client',
'redirectUri' => 'http://some-site.com/oauth/ely',
'websiteUrl' => '',
'createdAt' => 1519254133,
]);
}
public function testGetNotOwn(FunctionalTester $I) {
$I->amAuthenticated('admin');
$this->route->getClient('another-test-oauth-client');
$I->canSeeResponseCodeIs(403);
$I->canSeeResponseIsJson();
$I->canSeeResponseContainsJson([
'name' => 'Forbidden',
'status' => 403,
'message' => 'You are not allowed to perform this action.',
]);
}
public function testGetAllPerAccountList(FunctionalTester $I) {
$I->amAuthenticated('TwoOauthClients');
$this->route->getPerAccount(14);
$I->canSeeResponseCodeIs(200);
$I->canSeeResponseIsJson();
$I->canSeeResponseContainsJson([
[
'clientId' => 'first-test-oauth-client',
'clientSecret' => 'Zt1kEK7DQLXXYISLDvURVXK32Q58sHWSFKyO71iCIlv4YM2IHlLbhsvYoIJScUzT',
'type' => 'application',
'name' => 'First test oauth client',
'description' => 'Some description to the first oauth client',
'redirectUri' => 'http://some-site-1.com/oauth/ely',
'websiteUrl' => '',
'countUsers' => 0,
'createdAt' => 1519487434,
],
[
'clientId' => 'another-test-oauth-client',
'clientSecret' => 'URVXK32Q58sHWSFKyO71iCIlv4YM2Zt1kEK7DQLXXYISLDvIHlLbhsvYoIJScUzT',
'type' => 'minecraft-server',
'name' => 'Another test oauth client',
'websiteUrl' => '',
'minecraftServerIp' => '136.243.88.97:25565',
'countUsers' => 0,
'createdAt' => 1519487472,
],
]);
}
public function testGetAllPerNotOwnAccount(FunctionalTester $I) {
$I->amAuthenticated('TwoOauthClients');
$this->route->getPerAccount(1);
$I->canSeeResponseCodeIs(403);
$I->canSeeResponseIsJson();
$I->canSeeResponseContainsJson([
'name' => 'Forbidden',
'status' => 403,
'message' => 'You are not allowed to perform this action.',
]);
}
}

View File

@@ -0,0 +1,60 @@
<?php
namespace tests\codeception\api\oauth;
use tests\codeception\api\_pages\OauthRoute;
use tests\codeception\api\FunctionalTester;
class ResetClientCest {
/**
* @var OauthRoute
*/
private $route;
public function _before(FunctionalTester $I) {
$this->route = new OauthRoute($I);
}
public function testReset(FunctionalTester $I) {
$I->amAuthenticated('TwoOauthClients');
$this->route->resetClient('first-test-oauth-client');
$I->canSeeResponseCodeIs(200);
$I->canSeeResponseIsJson();
$I->canSeeResponseContainsJson([
'success' => true,
'data' => [
'clientId' => 'first-test-oauth-client',
'clientSecret' => 'Zt1kEK7DQLXXYISLDvURVXK32Q58sHWSFKyO71iCIlv4YM2IHlLbhsvYoIJScUzT',
'name' => 'First test oauth client',
'description' => 'Some description to the first oauth client',
'redirectUri' => 'http://some-site-1.com/oauth/ely',
'websiteUrl' => '',
'countUsers' => 0,
'createdAt' => 1519487434,
],
]);
}
public function testResetWithSecretChanging(FunctionalTester $I) {
$I->amAuthenticated('TwoOauthClients');
$this->route->resetClient('first-test-oauth-client', true);
$I->canSeeResponseCodeIs(200);
$I->canSeeResponseIsJson();
$I->canSeeResponseContainsJson([
'success' => true,
'data' => [
'clientId' => 'first-test-oauth-client',
'name' => 'First test oauth client',
'description' => 'Some description to the first oauth client',
'redirectUri' => 'http://some-site-1.com/oauth/ely',
'websiteUrl' => '',
'countUsers' => 0,
'createdAt' => 1519487434,
],
]);
$I->canSeeResponseJsonMatchesJsonPath('$.data.clientSecret');
$secret = $I->grabDataFromResponseByJsonPath('$.data.clientSecret')[0];
$I->assertNotEquals('Zt1kEK7DQLXXYISLDvURVXK32Q58sHWSFKyO71iCIlv4YM2IHlLbhsvYoIJScUzT', $secret);
}
}

View File

@@ -0,0 +1,65 @@
<?php
namespace tests\codeception\api\oauth;
use tests\codeception\api\_pages\OauthRoute;
use tests\codeception\api\FunctionalTester;
class UpdateClientCest {
/**
* @var OauthRoute
*/
private $route;
public function _before(FunctionalTester $I) {
$this->route = new OauthRoute($I);
}
public function testUpdateApplication(FunctionalTester $I) {
$I->amAuthenticated('TwoOauthClients');
$this->route->updateClient('first-test-oauth-client', [
'name' => 'Updated name',
'description' => 'Updated description.',
'redirectUri' => 'http://new-site.com/oauth/ely',
'websiteUrl' => 'http://new-site.com',
]);
$I->canSeeResponseCodeIs(200);
$I->canSeeResponseIsJson();
$I->canSeeResponseContainsJson([
'success' => true,
'data' => [
'clientId' => 'first-test-oauth-client',
'clientSecret' => 'Zt1kEK7DQLXXYISLDvURVXK32Q58sHWSFKyO71iCIlv4YM2IHlLbhsvYoIJScUzT',
'name' => 'Updated name',
'description' => 'Updated description.',
'redirectUri' => 'http://new-site.com/oauth/ely',
'websiteUrl' => 'http://new-site.com',
'createdAt' => 1519487434,
'countUsers' => 0,
],
]);
}
public function testUpdateMinecraftServer(FunctionalTester $I) {
$I->amAuthenticated('TwoOauthClients');
$this->route->updateClient('another-test-oauth-client', [
'name' => 'Updated server name',
'websiteUrl' => 'http://new-site.com',
'minecraftServerIp' => 'hypixel.com:25565',
]);
$I->canSeeResponseCodeIs(200);
$I->canSeeResponseIsJson();
$I->canSeeResponseContainsJson([
'success' => true,
'data' => [
'clientId' => 'another-test-oauth-client',
'clientSecret' => 'URVXK32Q58sHWSFKyO71iCIlv4YM2Zt1kEK7DQLXXYISLDvIHlLbhsvYoIJScUzT',
'name' => 'Updated server name',
'websiteUrl' => 'http://new-site.com',
'minecraftServerIp' => 'hypixel.com:25565',
'createdAt' => 1519487472,
],
]);
}
}

View File

@@ -0,0 +1,27 @@
<?php
namespace tests\codeception\api\unit\modules\oauth\models;
use api\modules\oauth\models\ApplicationType;
use common\models\OauthClient;
use tests\codeception\api\unit\TestCase;
class ApplicationTypeTest extends TestCase {
public function testApplyToClient(): void {
$model = new ApplicationType();
$model->name = 'Application name';
$model->websiteUrl = 'http://example.com';
$model->redirectUri = 'http://example.com/oauth/ely';
$model->description = 'Application description.';
$client = new OauthClient();
$model->applyToClient($client);
$this->assertSame('Application name', $client->name);
$this->assertSame('Application description.', $client->description);
$this->assertSame('http://example.com/oauth/ely', $client->redirect_uri);
$this->assertSame('http://example.com', $client->website_url);
}
}

View File

@@ -0,0 +1,24 @@
<?php
namespace tests\codeception\api\unit\modules\oauth\models;
use api\modules\oauth\models\BaseOauthClientType;
use common\models\OauthClient;
use tests\codeception\api\unit\TestCase;
class BaseOauthClientTypeTest extends TestCase {
public function testApplyTyClient(): void {
$client = new OauthClient();
/** @var BaseOauthClientType|\Mockery\MockInterface $form */
$form = mock(BaseOauthClientType::class);
$form->makePartial();
$form->name = 'Application name';
$form->websiteUrl = 'http://example.com';
$form->applyToClient($client);
$this->assertSame('Application name', $client->name);
$this->assertSame('http://example.com', $client->website_url);
}
}

View File

@@ -0,0 +1,25 @@
<?php
namespace tests\codeception\api\unit\modules\oauth\models;
use api\modules\oauth\models\MinecraftServerType;
use common\models\OauthClient;
use tests\codeception\api\unit\TestCase;
class MinecraftServerTypeTest extends TestCase {
public function testApplyToClient(): void {
$model = new MinecraftServerType();
$model->name = 'Server name';
$model->websiteUrl = 'http://example.com';
$model->minecraftServerIp = 'localhost:12345';
$client = new OauthClient();
$model->applyToClient($client);
$this->assertSame('Server name', $client->name);
$this->assertSame('http://example.com', $client->website_url);
$this->assertSame('localhost:12345', $client->minecraft_server_ip);
}
}

View File

@@ -0,0 +1,49 @@
<?php
namespace tests\codeception\api\unit\modules\oauth\models;
use api\modules\oauth\models\ApplicationType;
use api\modules\oauth\models\MinecraftServerType;
use api\modules\oauth\models\OauthClientFormFactory;
use common\models\OauthClient;
use tests\codeception\api\unit\TestCase;
class OauthClientFormFactoryTest extends TestCase {
public function testCreate() {
$client = new OauthClient();
$client->type = OauthClient::TYPE_APPLICATION;
$client->name = 'Application name';
$client->description = 'Application description.';
$client->website_url = 'http://example.com';
$client->redirect_uri = 'http://example.com/oauth/ely';
/** @var ApplicationType $requestForm */
$requestForm = OauthClientFormFactory::create($client);
$this->assertInstanceOf(ApplicationType::class, $requestForm);
$this->assertSame('Application name', $requestForm->name);
$this->assertSame('Application description.', $requestForm->description);
$this->assertSame('http://example.com', $requestForm->websiteUrl);
$this->assertSame('http://example.com/oauth/ely', $requestForm->redirectUri);
$client = new OauthClient();
$client->type = OauthClient::TYPE_MINECRAFT_SERVER;
$client->name = 'Server name';
$client->website_url = 'http://example.com';
$client->minecraft_server_ip = 'localhost:12345';
/** @var MinecraftServerType $requestForm */
$requestForm = OauthClientFormFactory::create($client);
$this->assertInstanceOf(MinecraftServerType::class, $requestForm);
$this->assertSame('Server name', $requestForm->name);
$this->assertSame('http://example.com', $requestForm->websiteUrl);
$this->assertSame('localhost:12345', $requestForm->minecraftServerIp);
}
/**
* @expectedException \api\modules\oauth\exceptions\UnsupportedOauthClientType
*/
public function testCreateUnknownType() {
$client = new OauthClient();
$client->type = 'unknown-type';
OauthClientFormFactory::create($client);
}
}

View File

@@ -0,0 +1,140 @@
<?php
namespace tests\codeception\api\unit\modules\oauth\models;
use api\modules\oauth\models\OauthClientForm;
use api\modules\oauth\models\OauthClientTypeForm;
use common\models\OauthClient;
use common\tasks\ClearOauthSessions;
use tests\codeception\api\unit\TestCase;
class OauthClientFormTest extends TestCase {
public function testSave() {
/** @var OauthClient|\Mockery\MockInterface $client */
$client = mock(OauthClient::class . '[save]');
$client->shouldReceive('save')->andReturn(true);
$client->account_id = 1;
$client->type = OauthClient::TYPE_APPLICATION;
$client->name = 'Test application';
/** @var OauthClientForm|\Mockery\MockInterface $form */
$form = mock(OauthClientForm::class . '[isClientExists]', [$client]);
$form->shouldAllowMockingProtectedMethods();
$form->shouldReceive('isClientExists')
->times(3)
->andReturnValues([true, true, false]);
/** @var OauthClientTypeForm|\Mockery\MockInterface $requestType */
$requestType = mock(OauthClientTypeForm::class);
$requestType->shouldReceive('validate')->once()->andReturn(true);
$requestType->shouldReceive('applyToClient')->once()->withArgs([$client]);
$this->assertTrue($form->save($requestType));
$this->assertSame('test-application2', $client->id);
$this->assertNotNull($client->secret);
$this->assertSame(64, mb_strlen($client->secret));
}
public function testSaveUpdateExistsModel() {
/** @var OauthClient|\Mockery\MockInterface $client */
$client = mock(OauthClient::class . '[save]');
$client->shouldReceive('save')->andReturn(true);
$client->setIsNewRecord(false);
$client->id = 'application-id';
$client->secret = 'application_secret';
$client->account_id = 1;
$client->type = OauthClient::TYPE_APPLICATION;
$client->name = 'Application name';
$client->description = 'Application description';
$client->redirect_uri = 'http://example.com/oauth/ely';
$client->website_url = 'http://example.com';
/** @var OauthClientForm|\Mockery\MockInterface $form */
$form = mock(OauthClientForm::class . '[isClientExists]', [$client]);
$form->shouldAllowMockingProtectedMethods();
$form->shouldReceive('isClientExists')->andReturn(false);
$request = new class implements OauthClientTypeForm {
public function load($data): bool {
return true;
}
public function validate(): bool {
return true;
}
public function getValidationErrors(): array {
return [];
}
public function applyToClient(OauthClient $client): void {
$client->name = 'New name';
$client->description = 'New description.';
}
};
$this->assertTrue($form->save($request));
$this->assertSame('application-id', $client->id);
$this->assertSame('application_secret', $client->secret);
$this->assertSame('New name', $client->name);
$this->assertSame('New description.', $client->description);
$this->assertSame('http://example.com/oauth/ely', $client->redirect_uri);
$this->assertSame('http://example.com', $client->website_url);
}
public function testDelete() {
/** @var OauthClient|\Mockery\MockInterface $client */
$client = mock(OauthClient::class . '[save]');
$client->id = 'mocked-id';
$client->type = OauthClient::TYPE_APPLICATION;
$client->shouldReceive('save')->andReturn(true);
$form = new OauthClientForm($client);
$this->assertTrue($form->delete());
$this->assertTrue($form->getClient()->is_deleted);
/** @var ClearOauthSessions $job */
$job = $this->tester->grabLastQueuedJob();
$this->assertInstanceOf(ClearOauthSessions::class, $job);
$this->assertSame('mocked-id', $job->clientId);
$this->assertNull($job->notSince);
}
public function testReset() {
/** @var OauthClient|\Mockery\MockInterface $client */
$client = mock(OauthClient::class . '[save]');
$client->id = 'mocked-id';
$client->secret = 'initial_secret';
$client->type = OauthClient::TYPE_APPLICATION;
$client->shouldReceive('save')->andReturn(true);
$form = new OauthClientForm($client);
$this->assertTrue($form->reset());
$this->assertSame('initial_secret', $form->getClient()->secret);
/** @var ClearOauthSessions $job */
$job = $this->tester->grabLastQueuedJob();
$this->assertInstanceOf(ClearOauthSessions::class, $job);
$this->assertSame('mocked-id', $job->clientId);
$this->assertEquals(time(), $job->notSince, '', 2);
}
public function testResetWithSecret() {
/** @var OauthClient|\Mockery\MockInterface $client */
$client = mock(OauthClient::class . '[save]');
$client->id = 'mocked-id';
$client->secret = 'initial_secret';
$client->type = OauthClient::TYPE_APPLICATION;
$client->shouldReceive('save')->andReturn(true);
$form = new OauthClientForm($client);
$this->assertTrue($form->reset(true));
$this->assertNotSame('initial_secret', $form->getClient()->secret);
/** @var ClearOauthSessions $job */
$job = $this->tester->grabLastQueuedJob();
$this->assertInstanceOf(ClearOauthSessions::class, $job);
$this->assertSame('mocked-id', $job->clientId);
$this->assertEquals(time(), $job->notSince, '', 2);
}
}

View File

@@ -186,4 +186,20 @@ return [
'updated_at' => 1485124685,
'password_changed_at' => 1485124685,
],
'account-with-two-oauth-clients' => [
'id' => 14,
'uuid' => '1b946267-b1a9-4409-ae83-94f84a329883',
'username' => 'TwoOauthClients',
'email' => 'oauth2-two@gmail.com',
'password_hash' => '$2y$13$2rYkap5T6jG8z/mMK8a3Ou6aZxJcmAaTha6FEuujvHEmybSHRzW5e', # password_0
'password_hash_strategy' => \common\models\Account::PASS_HASH_STRATEGY_YII2,
'lang' => 'ru',
'status' => \common\models\Account::STATUS_ACTIVE,
'rules_agreement_version' => \common\LATEST_RULES_VERSION,
'otp_secret' => null,
'is_otp_enabled' => false,
'created_at' => 1519487320,
'updated_at' => 1519487320,
'password_changed_at' => 1519487320,
],
];

View File

@@ -3,51 +3,141 @@ return [
'ely' => [
'id' => 'ely',
'secret' => 'ZuM1vGchJz-9_UZ5HC3H3Z9Hg5PzdbkM',
'type' => 'application',
'name' => 'Ely.by',
'description' => 'Всем знакомое елуби',
'redirect_uri' => 'http://ely.by',
'website_url' => '',
'minecraft_server_ip' => '',
'account_id' => null,
'is_trusted' => 0,
'is_deleted' => 0,
'created_at' => 1455309271,
],
'tlauncher' => [
'id' => 'tlauncher',
'secret' => 'HsX-xXzdGiz3mcsqeEvrKHF47sqiaX94',
'type' => 'application',
'name' => 'TLauncher',
'description' => 'Лучший альтернативный лаунчер для Minecraft с большим количеством версий и их модификаций, а также возмоностью входа как с лицензионным аккаунтом, так и без него.',
'redirect_uri' => '',
'website_url' => '',
'minecraft_server_ip' => '',
'account_id' => null,
'is_trusted' => 0,
'is_deleted' => 0,
'created_at' => 1455318468,
],
'test1' => [
'id' => 'test1',
'secret' => 'eEvrKHF47sqiaX94HsX-xXzdGiz3mcsq',
'type' => 'application',
'name' => 'Test1',
'description' => 'Some description',
'redirect_uri' => 'http://test1.net',
'website_url' => '',
'minecraft_server_ip' => '',
'account_id' => null,
'is_trusted' => 0,
'is_deleted' => 0,
'created_at' => 1479937982,
],
'trustedClient' => [
'id' => 'trusted-client',
'secret' => 'tXBbyvMcyaOgHMOAXBpN2EC7uFoJAaL9',
'type' => 'application',
'name' => 'Trusted client',
'description' => 'Это клиент, которому мы доверяем',
'redirect_uri' => null,
'website_url' => '',
'minecraft_server_ip' => '',
'account_id' => null,
'is_trusted' => 1,
'is_deleted' => 0,
'created_at' => 1482922663,
],
'defaultClient' => [
'id' => 'default-client',
'secret' => 'AzWRy7ZjS1yRQUk2vRBDic8fprOKDB1W',
'type' => 'application',
'name' => 'Default client',
'description' => 'Это обычный клиент, каких может быть много',
'redirect_uri' => null,
'website_url' => '',
'minecraft_server_ip' => '',
'account_id' => null,
'is_trusted' => 0,
'is_deleted' => 0,
'created_at' => 1482922711,
],
'admin_oauth_client' => [
'id' => 'admin-oauth-client',
'secret' => 'FKyO71iCIlv4YM2IHlLbhsvYoIJScUzTZt1kEK7DQLXXYISLDvURVXK32Q58sHWS',
'type' => 'application',
'name' => 'Admin\'s oauth client',
'description' => 'Personal oauth client',
'redirect_uri' => 'http://some-site.com/oauth/ely',
'website_url' => '',
'minecraft_server_ip' => '',
'account_id' => 1,
'is_trusted' => 0,
'is_deleted' => 0,
'created_at' => 1519254133,
],
'first_test_oauth_client' => [
'id' => 'first-test-oauth-client',
'secret' => 'Zt1kEK7DQLXXYISLDvURVXK32Q58sHWSFKyO71iCIlv4YM2IHlLbhsvYoIJScUzT',
'type' => 'application',
'name' => 'First test oauth client',
'description' => 'Some description to the first oauth client',
'redirect_uri' => 'http://some-site-1.com/oauth/ely',
'website_url' => '',
'minecraft_server_ip' => '',
'account_id' => 14,
'is_trusted' => 0,
'is_deleted' => 0,
'created_at' => 1519487434,
],
'another_test_oauth_client' => [
'id' => 'another-test-oauth-client',
'secret' => 'URVXK32Q58sHWSFKyO71iCIlv4YM2Zt1kEK7DQLXXYISLDvIHlLbhsvYoIJScUzT',
'type' => 'minecraft-server',
'name' => 'Another test oauth client',
'description' => null,
'redirect_uri' => null,
'website_url' => '',
'minecraft_server_ip' => '136.243.88.97:25565',
'account_id' => 14,
'is_trusted' => 0,
'is_deleted' => 0,
'created_at' => 1519487472,
],
'deleted_oauth_client' => [
'id' => 'deleted-oauth-client',
'secret' => 'YISLDvIHlLbhsvYoIJScUzTURVXK32Q58sHWSFKyO71iCIlv4YM2Zt1kEK7DQLXX',
'type' => 'application',
'name' => 'I was deleted :(',
'description' => null,
'redirect_uri' => 'http://not-exists-site.com/oauth/ely',
'website_url' => '',
'minecraft_server_ip' => null,
'account_id' => 1,
'is_trusted' => 0,
'is_deleted' => 1,
'created_at' => 1519504563,
],
'deleted_oauth_client_with_sessions' => [
'id' => 'deleted-oauth-client-with-sessions',
'secret' => 'EK7DQLXXYISLDvIHlLbhsvYoIJScUzTURVXK32Q58sHWSFKyO71iCIlv4YM2Zt1k',
'type' => 'application',
'name' => 'I still have some sessions ^_^',
'description' => null,
'redirect_uri' => 'http://not-exists-site.com/oauth/ely',
'website_url' => '',
'minecraft_server_ip' => null,
'account_id' => 1,
'is_trusted' => 0,
'is_deleted' => 1,
'created_at' => 1519507190,
],
];

View File

@@ -6,6 +6,7 @@ return [
'owner_id' => 1,
'client_id' => 'test1',
'client_redirect_uri' => 'http://test1.net/oauth',
'created_at' => 1479944472,
],
'banned-account-session' => [
'id' => 2,
@@ -13,5 +14,22 @@ return [
'owner_id' => 10,
'client_id' => 'test1',
'client_redirect_uri' => 'http://test1.net/oauth',
'created_at' => 1481421663,
],
'deleted-client-session' => [
'id' => 3,
'owner_type' => 'user',
'owner_id' => 1,
'client_id' => 'deleted-oauth-client-with-sessions',
'client_redirect_uri' => 'http://not-exists-site.com/oauth/ely',
'created_at' => 1519510065,
],
'actual-deleted-client-session' => [
'id' => 4,
'owner_type' => 'user',
'owner_id' => 2,
'client_id' => 'deleted-oauth-client-with-sessions',
'client_redirect_uri' => 'http://not-exists-site.com/oauth/ely',
'created_at' => 1519511568,
],
];

View File

@@ -0,0 +1,42 @@
<?php
namespace tests\codeception\common\unit\models;
use common\models\OauthClient;
use tests\codeception\common\fixtures\OauthClientFixture;
use tests\codeception\common\unit\TestCase;
class OauthClientQueryTest extends TestCase {
public function _fixtures() {
return [
'oauthClients' => OauthClientFixture::class,
];
}
public function testDefaultHideDeletedEntries() {
/** @var OauthClient[] $clients */
$clients = OauthClient::find()->all();
$this->assertEmpty(array_filter($clients, function(OauthClient $client) {
return (bool)$client->is_deleted === true;
}));
$this->assertNull(OauthClient::findOne('deleted-oauth-client'));
}
public function testAllowFindDeletedEntries() {
/** @var OauthClient[] $clients */
$clients = OauthClient::find()->includeDeleted()->all();
$this->assertNotEmpty(array_filter($clients, function(OauthClient $client) {
return (bool)$client->is_deleted === true;
}));
$client = OauthClient::find()
->includeDeleted()
->andWhere(['id' => 'deleted-oauth-client'])
->one();
$this->assertInstanceOf(OauthClient::class, $client);
$deletedClients = OauthClient::find()->onlyDeleted()->all();
$this->assertEmpty(array_filter($deletedClients, function(OauthClient $client) {
return (bool)$client->is_deleted === false;
}));
}
}

View File

@@ -40,6 +40,7 @@ class AccountOwnerTest extends TestCase {
Yii::$app->set('user', $component);
$this->assertFalse($rule->execute('token', $item, []));
$this->assertFalse($rule->execute('token', $item, ['accountId' => 2]));
$this->assertFalse($rule->execute('token', $item, ['accountId' => '2']));
$this->assertTrue($rule->execute('token', $item, ['accountId' => 1]));
@@ -53,11 +54,4 @@ class AccountOwnerTest extends TestCase {
$this->assertFalse($rule->execute('token', $item, ['accountId' => 1, 'optionalRules' => true]));
}
/**
* @expectedException \yii\base\InvalidParamException
*/
public function testExecuteWithException() {
(new AccountOwner())->execute('', new Item(), []);
}
}

View File

@@ -0,0 +1,53 @@
<?php
namespace tests\codeception\common\unit\rbac\rules;
use api\components\User\Component;
use api\components\User\IdentityInterface;
use common\models\Account;
use common\rbac\Permissions as P;
use common\rbac\rules\OauthClientOwner;
use tests\codeception\common\fixtures\OauthClientFixture;
use tests\codeception\common\unit\TestCase;
use Yii;
use yii\rbac\Item;
use const common\LATEST_RULES_VERSION;
class OauthClientOwnerTest extends TestCase {
public function _fixtures() {
return [
'oauthClients' => OauthClientFixture::class,
];
}
public function testExecute() {
$rule = new OauthClientOwner();
$item = new Item();
$account = new Account();
$account->id = 1;
$account->status = Account::STATUS_ACTIVE;
$account->rules_agreement_version = LATEST_RULES_VERSION;
/** @var IdentityInterface|\Mockery\MockInterface $identity */
$identity = mock(IdentityInterface::class);
$identity->shouldReceive('getAccount')->andReturn($account);
/** @var Component|\Mockery\MockInterface $component */
$component = mock(Component::class . '[findIdentityByAccessToken]', [['secret' => 'secret']]);
$component->shouldDeferMissing();
$component->shouldReceive('findIdentityByAccessToken')->withArgs(['token'])->andReturn($identity);
Yii::$app->set('user', $component);
$this->assertFalse($rule->execute('token', $item, []));
$this->assertTrue($rule->execute('token', $item, ['clientId' => 'admin-oauth-client']));
$this->assertFalse($rule->execute('token', $item, ['clientId' => 'not-exists-client']));
$account->id = 2;
$this->assertFalse($rule->execute('token', $item, ['clientId' => 'admin-oauth-client']));
$item->name = P::VIEW_OWN_OAUTH_CLIENTS;
$this->assertTrue($rule->execute('token', $item, ['accountId' => 2]));
$this->assertFalse($rule->execute('token', $item, ['accountId' => 1]));
}
}

View File

@@ -0,0 +1,55 @@
<?php
namespace tests\codeception\common\unit\tasks;
use common\models\OauthClient;
use common\models\OauthSession;
use common\tasks\ClearOauthSessions;
use tests\codeception\common\fixtures;
use tests\codeception\common\unit\TestCase;
use yii\queue\Queue;
class ClearOauthSessionsTest extends TestCase {
public function _fixtures() {
return [
'oauthClients' => fixtures\OauthClientFixture::class,
'oauthSessions' => fixtures\OauthSessionFixture::class,
];
}
public function testCreateFromClient() {
$client = new OauthClient();
$client->id = 'mocked-id';
$result = ClearOauthSessions::createFromOauthClient($client);
$this->assertInstanceOf(ClearOauthSessions::class, $result);
$this->assertSame('mocked-id', $result->clientId);
$this->assertNull($result->notSince);
$result = ClearOauthSessions::createFromOauthClient($client, time());
$this->assertInstanceOf(ClearOauthSessions::class, $result);
$this->assertSame('mocked-id', $result->clientId);
$this->assertEquals(time(), $result->notSince, '', 1);
}
public function testExecute() {
$task = new ClearOauthSessions();
$task->clientId = 'deleted-oauth-client-with-sessions';
$task->notSince = 1519510065;
$task->execute(mock(Queue::class));
$this->assertFalse(OauthSession::find()->andWhere(['id' => 3])->exists());
$this->assertTrue(OauthSession::find()->andWhere(['id' => 4])->exists());
$task = new ClearOauthSessions();
$task->clientId = 'deleted-oauth-client-with-sessions';
$task->execute(mock(Queue::class));
$this->assertFalse(OauthSession::find()->andWhere(['id' => 4])->exists());
$task = new ClearOauthSessions();
$task->clientId = 'some-not-exists-client-id';
$task->execute(mock(Queue::class));
}
}

View File

@@ -0,0 +1,33 @@
<?php
namespace tests\codeception\common\unit\validators;
use common\validators\MinecraftServerAddressValidator;
use tests\codeception\common\unit\TestCase;
class MinecraftServerAddressValidatorTest extends TestCase {
/**
* @dataProvider domainNames
*/
public function testValidate($address, $shouldBeValid) {
$validator = new MinecraftServerAddressValidator();
$validator->validate($address, $errors);
$this->assertEquals($shouldBeValid, $errors === null);
}
public function domainNames() {
return [
['localhost', true ],
['localhost:25565', true ],
['mc.hypixel.net', true ],
['mc.hypixel.net:25565', true ],
['136.243.88.97', true ],
['136.243.88.97:25565', true ],
['http://ely.by', false],
['http://ely.by:80', false],
['ely.by/abcd', false],
['ely.by?abcd', false],
];
}
}

View File

@@ -4,6 +4,7 @@ modules:
- Yii2:
part: [orm, email, fixtures]
- tests\codeception\common\_support\Mockery
- tests\codeception\common\_support\queue\CodeceptionQueueHelper
config:
Yii2:
configFile: '../config/console/unit.php'

View File

@@ -4,10 +4,10 @@ namespace codeception\console\unit\controllers;
use common\models\AccountSession;
use common\models\EmailActivation;
use common\models\MinecraftAccessKey;
use common\models\OauthClient;
use common\tasks\ClearOauthSessions;
use console\controllers\CleanupController;
use tests\codeception\common\fixtures\AccountSessionFixture;
use tests\codeception\common\fixtures\EmailActivationFixture;
use tests\codeception\common\fixtures\MinecraftAccessKeyFixture;
use tests\codeception\common\fixtures;
use tests\codeception\console\unit\TestCase;
use Yii;
@@ -15,9 +15,11 @@ class CleanupControllerTest extends TestCase {
public function _fixtures() {
return [
'emailActivations' => EmailActivationFixture::class,
'minecraftSessions' => MinecraftAccessKeyFixture::class,
'accountsSessions' => AccountSessionFixture::class,
'emailActivations' => fixtures\EmailActivationFixture::class,
'minecraftSessions' => fixtures\MinecraftAccessKeyFixture::class,
'accountsSessions' => fixtures\AccountSessionFixture::class,
'oauthClients' => fixtures\OauthClientFixture::class,
'oauthSessions' => fixtures\OauthSessionFixture::class,
];
}
@@ -56,4 +58,22 @@ class CleanupControllerTest extends TestCase {
$this->assertEquals($totalSessionsCount - 2, AccountSession::find()->count());
}
public function testActionOauthClients() {
/** @var OauthClient $deletedClient */
$totalClientsCount = OauthClient::find()->includeDeleted()->count();
$controller = new CleanupController('cleanup', Yii::$app);
$this->assertEquals(0, $controller->actionOauthClients());
$this->assertNull(OauthClient::find()->includeDeleted()->andWhere(['id' => 'deleted-oauth-client'])->one());
$this->assertNotNull(OauthClient::find()->includeDeleted()->andWhere(['id' => 'deleted-oauth-client-with-sessions'])->one());
$this->assertEquals($totalClientsCount - 1, OauthClient::find()->includeDeleted()->count());
/** @var ClearOauthSessions $job */
$job = $this->tester->grabLastQueuedJob();
$this->assertInstanceOf(ClearOauthSessions::class, $job);
$this->assertSame('deleted-oauth-client-with-sessions', $job->clientId);
$this->assertNull($job->notSince);
}
}