mirror of
https://github.com/elyby/accounts.git
synced 2025-05-31 14:11:46 +05:30
Реорганизована выдача JWT токенов
Добавлен механизм сохранения сессий и refresh_token
This commit is contained in:
@ -8,12 +8,18 @@ use yii\codeception\BasePage;
|
||||
*/
|
||||
class AuthenticationRoute extends BasePage {
|
||||
|
||||
public function login($login = '', $password = '') {
|
||||
public function login($login = '', $password = '', $rememberMe = false) {
|
||||
$this->route = ['authentication/login'];
|
||||
$this->actor->sendPOST($this->getUrl(), [
|
||||
$params = [
|
||||
'login' => $login,
|
||||
'password' => $password,
|
||||
]);
|
||||
];
|
||||
|
||||
if ($rememberMe) {
|
||||
$params['rememberMe'] = 1;
|
||||
}
|
||||
|
||||
$this->actor->sendPOST($this->getUrl(), $params);
|
||||
}
|
||||
|
||||
public function forgotPassword($login = '') {
|
||||
|
@ -34,8 +34,8 @@ class FunctionalTester extends Actor {
|
||||
}
|
||||
|
||||
$this->canSeeResponseIsJson();
|
||||
$this->canSeeResponseJsonMatchesJsonPath('$.jwt');
|
||||
$jwt = $this->grabDataFromResponseByJsonPath('$.jwt')[0];
|
||||
$this->canSeeAuthCredentials(false);
|
||||
$jwt = $this->grabDataFromResponseByJsonPath('$.access_token')[0];
|
||||
$this->amBearerAuthenticated($jwt);
|
||||
}
|
||||
|
||||
@ -43,4 +43,14 @@ class FunctionalTester extends Actor {
|
||||
$this->haveHttpHeader('Authorization', null);
|
||||
}
|
||||
|
||||
public function canSeeAuthCredentials($expectRefresh = false) {
|
||||
$this->canSeeResponseJsonMatchesJsonPath('$.access_token');
|
||||
$this->canSeeResponseJsonMatchesJsonPath('$.expires_in');
|
||||
if ($expectRefresh) {
|
||||
$this->canSeeResponseJsonMatchesJsonPath('$.refresh_token');
|
||||
} else {
|
||||
$this->cantSeeResponseJsonMatchesJsonPath('$.refresh_token');
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -36,7 +36,7 @@ class EmailConfirmationCest {
|
||||
'success' => true,
|
||||
]);
|
||||
$I->cantSeeResponseJsonMatchesJsonPath('$.errors');
|
||||
$I->canSeeResponseJsonMatchesJsonPath('$.jwt');
|
||||
$I->canSeeAuthCredentials(true);
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -111,8 +111,8 @@ class LoginCest {
|
||||
$I->canSeeResponseContainsJson([
|
||||
'success' => true,
|
||||
]);
|
||||
$I->canSeeResponseJsonMatchesJsonPath('$.jwt');
|
||||
$I->cantSeeResponseJsonMatchesJsonPath('$.errors');
|
||||
$I->canSeeAuthCredentials(false);
|
||||
}
|
||||
|
||||
public function testLoginByEmailCorrect(FunctionalTester $I) {
|
||||
@ -124,6 +124,7 @@ class LoginCest {
|
||||
'success' => true,
|
||||
]);
|
||||
$I->cantSeeResponseJsonMatchesJsonPath('$.errors');
|
||||
$I->canSeeAuthCredentials(false);
|
||||
}
|
||||
|
||||
public function testLoginInAccWithPasswordMethod(FunctionalTester $I) {
|
||||
@ -134,8 +135,20 @@ class LoginCest {
|
||||
$I->canSeeResponseContainsJson([
|
||||
'success' => true,
|
||||
]);
|
||||
$I->canSeeResponseJsonMatchesJsonPath('$.jwt');
|
||||
$I->cantSeeResponseJsonMatchesJsonPath('$.errors');
|
||||
$I->canSeeAuthCredentials(false);
|
||||
}
|
||||
|
||||
public function testLoginByEmailWithRemember(FunctionalTester $I) {
|
||||
$route = new AuthenticationRoute($I);
|
||||
|
||||
$I->wantTo('login into account using correct data and get refresh_token');
|
||||
$route->login('admin@ely.by', 'password_0', true);
|
||||
$I->canSeeResponseContainsJson([
|
||||
'success' => true,
|
||||
]);
|
||||
$I->cantSeeResponseJsonMatchesJsonPath('$.errors');
|
||||
$I->canSeeAuthCredentials(true);
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -15,10 +15,10 @@ class RecoverPasswordCest {
|
||||
$I->canSeeResponseContainsJson([
|
||||
'success' => true,
|
||||
]);
|
||||
$I->canSeeResponseJsonMatchesJsonPath('$.jwt');
|
||||
$I->canSeeAuthCredentials(false);
|
||||
|
||||
$I->wantTo('ensure, that jwt token is valid');
|
||||
$jwt = $I->grabDataFromResponseByJsonPath('$.jwt')[0];
|
||||
$jwt = $I->grabDataFromResponseByJsonPath('$.access_token')[0];
|
||||
$I->amBearerAuthenticated($jwt);
|
||||
$accountRoute = new AccountsRoute($I);
|
||||
$accountRoute->current();
|
||||
|
101
tests/codeception/api/unit/components/User/ComponentTest.php
Normal file
101
tests/codeception/api/unit/components/User/ComponentTest.php
Normal file
@ -0,0 +1,101 @@
|
||||
<?php
|
||||
namespace codeception\api\unit\components\User;
|
||||
|
||||
use api\components\User\Component;
|
||||
use api\components\User\LoginResult;
|
||||
use api\models\AccountIdentity;
|
||||
use Codeception\Specify;
|
||||
use common\models\AccountSession;
|
||||
use Emarref\Jwt\Algorithm\AlgorithmInterface;
|
||||
use Emarref\Jwt\Claim\ClaimInterface;
|
||||
use tests\codeception\api\unit\DbTestCase;
|
||||
use tests\codeception\common\_support\ProtectedCaller;
|
||||
use tests\codeception\common\fixtures\AccountFixture;
|
||||
use tests\codeception\common\fixtures\AccountSessionFixture;
|
||||
|
||||
/**
|
||||
* @property AccountFixture $accounts
|
||||
* @property AccountSessionFixture $sessions
|
||||
*/
|
||||
class ComponentTest extends DbTestCase {
|
||||
use Specify;
|
||||
use ProtectedCaller;
|
||||
|
||||
private $originalRemoteHost;
|
||||
|
||||
/**
|
||||
* @var Component
|
||||
*/
|
||||
private $component;
|
||||
|
||||
public function _before() {
|
||||
$this->originalRemoteHost = $_SERVER['REMOTE_ADDR'] ?? null;
|
||||
$_SERVER['REMOTE_ADDR'] = '127.0.0.1';
|
||||
parent::_before();
|
||||
|
||||
$this->component = new Component([
|
||||
'identityClass' => AccountIdentity::class,
|
||||
'enableSession' => false,
|
||||
'loginUrl' => null,
|
||||
'secret' => 'secret',
|
||||
]);
|
||||
}
|
||||
|
||||
public function _after() {
|
||||
parent::_after();
|
||||
$_SERVER['REMOTE_ADDR'] = $this->originalRemoteHost;
|
||||
}
|
||||
|
||||
public function fixtures() {
|
||||
return [
|
||||
'accounts' => AccountFixture::class,
|
||||
'sessions' => AccountSessionFixture::class,
|
||||
];
|
||||
}
|
||||
|
||||
public function testLogin() {
|
||||
$this->specify('success get LoginResult object without session value', function() {
|
||||
$account = new AccountIdentity(['id' => 1]);
|
||||
$result = $this->component->login($account, false);
|
||||
expect($result)->isInstanceOf(LoginResult::class);
|
||||
expect($result->getSession())->null();
|
||||
expect(is_string($result->getJwt()))->true();
|
||||
expect($result->getIdentity())->equals($account);
|
||||
});
|
||||
|
||||
$this->specify('success get LoginResult object with session value if rememberMe is true', function() {
|
||||
/** @var AccountIdentity $account */
|
||||
$account = AccountIdentity::findOne($this->accounts['admin']['id']);
|
||||
$result = $this->component->login($account, true);
|
||||
expect($result)->isInstanceOf(LoginResult::class);
|
||||
expect($result->getSession())->isInstanceOf(AccountSession::class);
|
||||
expect(is_string($result->getJwt()))->true();
|
||||
expect($result->getIdentity())->equals($account);
|
||||
expect($result->getSession()->refresh())->true();
|
||||
});
|
||||
}
|
||||
|
||||
public function testGetJWT() {
|
||||
$this->specify('get string, contained jwt token', function() {
|
||||
expect($this->component->getJWT(new AccountIdentity(['id' => 1])))
|
||||
->regExp('/^[A-Za-z0-9-_=]+\.[A-Za-z0-9-_=]+\.?[A-Za-z0-9-_.+\/=]*$/');
|
||||
});
|
||||
}
|
||||
|
||||
public function testGetAlgorithm() {
|
||||
$this->specify('get expected hash algorithm object', function() {
|
||||
expect($this->component->getAlgorithm())->isInstanceOf(AlgorithmInterface::class);
|
||||
});
|
||||
}
|
||||
|
||||
public function testGetClaims() {
|
||||
$this->specify('get expected array of claims', function() {
|
||||
$claims = $this->callProtected($this->component, 'getClaims', new AccountIdentity(['id' => 1]));
|
||||
expect(is_array($claims))->true();
|
||||
expect('all array items should have valid type', array_filter($claims, function($claim) {
|
||||
return !$claim instanceof ClaimInterface;
|
||||
}))->isEmpty();
|
||||
});
|
||||
}
|
||||
|
||||
}
|
64
tests/codeception/api/unit/models/AccountIdentityTest.php
Normal file
64
tests/codeception/api/unit/models/AccountIdentityTest.php
Normal file
@ -0,0 +1,64 @@
|
||||
<?php
|
||||
namespace codeception\api\unit\models;
|
||||
|
||||
use api\models\AccountIdentity;
|
||||
use Codeception\Specify;
|
||||
use Exception;
|
||||
use tests\codeception\api\unit\DbTestCase;
|
||||
use tests\codeception\common\fixtures\AccountFixture;
|
||||
use Yii;
|
||||
use yii\web\IdentityInterface;
|
||||
use yii\web\UnauthorizedHttpException;
|
||||
|
||||
/**
|
||||
* @property AccountIdentity $accounts
|
||||
*/
|
||||
class AccountIdentityTest extends DbTestCase {
|
||||
use Specify;
|
||||
|
||||
public function fixtures() {
|
||||
return [
|
||||
'accounts' => [
|
||||
'class' => AccountFixture::class,
|
||||
'dataFile' => '@tests/codeception/common/fixtures/data/accounts.php',
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
public function testFindIdentityByAccessToken() {
|
||||
$this->specify('success validate passed jwt token', function() {
|
||||
$identity = AccountIdentity::findIdentityByAccessToken($this->generateToken());
|
||||
expect($identity)->isInstanceOf(IdentityInterface::class);
|
||||
expect($identity->getId())->equals($this->accounts['admin']['id']);
|
||||
});
|
||||
|
||||
// TODO: нормально оттестить исключение, если токен истёк
|
||||
return;
|
||||
|
||||
$this->specify('get unauthorized with "Token expired message if token valid, but expire"', function() {
|
||||
$originalTimezone = date_default_timezone_get();
|
||||
date_default_timezone_set('America/Los_Angeles');
|
||||
try {
|
||||
$token = $this->generateToken();
|
||||
date_default_timezone_set($originalTimezone);
|
||||
AccountIdentity::findIdentityByAccessToken($token);
|
||||
} catch (Exception $e) {
|
||||
expect($e)->isInstanceOf(UnauthorizedHttpException::class);
|
||||
expect($e->getMessage())->equals('Token expired');
|
||||
return;
|
||||
}
|
||||
|
||||
expect('if test valid, this should not happened', false)->true();
|
||||
});
|
||||
}
|
||||
|
||||
protected function generateToken() {
|
||||
/** @var \api\components\User\Component $component */
|
||||
$component = Yii::$app->user;
|
||||
/** @var AccountIdentity $account */
|
||||
$account = AccountIdentity::findOne($this->accounts['admin']['id']);
|
||||
|
||||
return $component->getJWT($account);
|
||||
}
|
||||
|
||||
}
|
@ -1,9 +1,11 @@
|
||||
<?php
|
||||
namespace tests\codeception\api\models\authentication;
|
||||
|
||||
use api\components\User\LoginResult;
|
||||
use api\models\authentication\ConfirmEmailForm;
|
||||
use Codeception\Specify;
|
||||
use common\models\Account;
|
||||
use common\models\AccountSession;
|
||||
use common\models\EmailActivation;
|
||||
use tests\codeception\api\unit\DbTestCase;
|
||||
use tests\codeception\common\fixtures\EmailActivationFixture;
|
||||
@ -31,7 +33,9 @@ class ConfirmEmailFormTest extends DbTestCase {
|
||||
$fixture = $this->emailActivations['freshRegistrationConfirmation'];
|
||||
$model = $this->createModel($fixture['key']);
|
||||
$this->specify('expect true result', function() use ($model, $fixture) {
|
||||
expect('model return successful result', $model->confirm())->notEquals(false);
|
||||
$result = $model->confirm();
|
||||
expect($result)->isInstanceOf(LoginResult::class);
|
||||
expect('session was generated', $result->getSession())->isInstanceOf(AccountSession::class);
|
||||
$activationExists = EmailActivation::find()->andWhere(['key' => $fixture['key']])->exists();
|
||||
expect('email activation key is not exist', $activationExists)->false();
|
||||
/** @var Account $user */
|
||||
|
@ -1,6 +1,8 @@
|
||||
<?php
|
||||
namespace tests\codeception\api\models\authentication;
|
||||
|
||||
use api\components\User\LoginResult;
|
||||
use api\models\AccountIdentity;
|
||||
use api\models\authentication\LoginForm;
|
||||
use Codeception\Specify;
|
||||
use common\models\Account;
|
||||
@ -14,12 +16,22 @@ use Yii;
|
||||
class LoginFormTest extends DbTestCase {
|
||||
use Specify;
|
||||
|
||||
private $originalRemoteAddr;
|
||||
|
||||
public function setUp() {
|
||||
$this->originalRemoteAddr = $_SERVER['REMOTE_ADDR'] ?? null;
|
||||
$_SERVER['REMOTE_ADDR'] = '127.0.0.1';
|
||||
parent::setUp();
|
||||
}
|
||||
|
||||
public function tearDown() {
|
||||
parent::tearDown();
|
||||
$_SERVER['REMOTE_ADDR'] = $this->originalRemoteAddr;
|
||||
}
|
||||
|
||||
public function fixtures() {
|
||||
return [
|
||||
'accounts' => [
|
||||
'class' => AccountFixture::class,
|
||||
'dataFile' => '@tests/codeception/common/fixtures/data/accounts.php',
|
||||
],
|
||||
'accounts' => AccountFixture::class,
|
||||
];
|
||||
}
|
||||
|
||||
@ -36,7 +48,7 @@ class LoginFormTest extends DbTestCase {
|
||||
$this->specify('no errors if login exists', function () {
|
||||
$model = $this->createModel([
|
||||
'login' => 'mr-test',
|
||||
'account' => new Account(),
|
||||
'account' => new AccountIdentity(),
|
||||
]);
|
||||
$model->validateLogin('login');
|
||||
expect($model->getErrors('login'))->isEmpty();
|
||||
@ -47,7 +59,7 @@ class LoginFormTest extends DbTestCase {
|
||||
$this->specify('error.password_incorrect if password invalid', function () {
|
||||
$model = $this->createModel([
|
||||
'password' => '87654321',
|
||||
'account' => new Account(['password' => '12345678']),
|
||||
'account' => new AccountIdentity(['password' => '12345678']),
|
||||
]);
|
||||
$model->validatePassword('password');
|
||||
expect($model->getErrors('password'))->equals(['error.password_incorrect']);
|
||||
@ -56,7 +68,7 @@ class LoginFormTest extends DbTestCase {
|
||||
$this->specify('no errors if password valid', function () {
|
||||
$model = $this->createModel([
|
||||
'password' => '12345678',
|
||||
'account' => new Account(['password' => '12345678']),
|
||||
'account' => new AccountIdentity(['password' => '12345678']),
|
||||
]);
|
||||
$model->validatePassword('password');
|
||||
expect($model->getErrors('password'))->isEmpty();
|
||||
@ -66,7 +78,7 @@ class LoginFormTest extends DbTestCase {
|
||||
public function testValidateActivity() {
|
||||
$this->specify('error.account_not_activated if account in not activated state', function () {
|
||||
$model = $this->createModel([
|
||||
'account' => new Account(['status' => Account::STATUS_REGISTERED]),
|
||||
'account' => new AccountIdentity(['status' => Account::STATUS_REGISTERED]),
|
||||
]);
|
||||
$model->validateActivity('login');
|
||||
expect($model->getErrors('login'))->equals(['error.account_not_activated']);
|
||||
@ -74,7 +86,7 @@ class LoginFormTest extends DbTestCase {
|
||||
|
||||
$this->specify('no errors if account active', function () {
|
||||
$model = $this->createModel([
|
||||
'account' => new Account(['status' => Account::STATUS_ACTIVE]),
|
||||
'account' => new AccountIdentity(['status' => Account::STATUS_ACTIVE]),
|
||||
]);
|
||||
$model->validateActivity('login');
|
||||
expect($model->getErrors('login'))->isEmpty();
|
||||
@ -86,13 +98,13 @@ class LoginFormTest extends DbTestCase {
|
||||
$model = $this->createModel([
|
||||
'login' => 'erickskrauch',
|
||||
'password' => '12345678',
|
||||
'account' => new Account([
|
||||
'account' => new AccountIdentity([
|
||||
'username' => 'erickskrauch',
|
||||
'password' => '12345678',
|
||||
'status' => Account::STATUS_ACTIVE,
|
||||
]),
|
||||
]);
|
||||
expect('model should login user', $model->login())->notEquals(false);
|
||||
expect('model should login user', $model->login())->isInstanceOf(LoginResult::class);
|
||||
expect('error message should not be set', $model->errors)->isEmpty();
|
||||
});
|
||||
}
|
||||
@ -103,7 +115,7 @@ class LoginFormTest extends DbTestCase {
|
||||
'login' => $this->accounts['user-with-old-password-type']['username'],
|
||||
'password' => '12345678',
|
||||
]);
|
||||
expect($model->login())->notEquals(false);
|
||||
expect($model->login())->isInstanceOf(LoginResult::class);
|
||||
expect($model->errors)->isEmpty();
|
||||
expect($model->getAccount()->password_hash_strategy)->equals(Account::PASS_HASH_STRATEGY_YII2);
|
||||
});
|
||||
|
@ -1,6 +1,7 @@
|
||||
<?php
|
||||
namespace tests\codeception\api\models\authentication;
|
||||
|
||||
use api\components\User\LoginResult;
|
||||
use api\models\authentication\RecoverPasswordForm;
|
||||
use Codeception\Specify;
|
||||
use common\models\Account;
|
||||
@ -29,7 +30,9 @@ class RecoverPasswordFormTest extends DbTestCase {
|
||||
'newPassword' => '12345678',
|
||||
'newRePassword' => '12345678',
|
||||
]);
|
||||
expect($model->recoverPassword())->notEquals(false);
|
||||
$result = $model->recoverPassword();
|
||||
expect($result)->isInstanceOf(LoginResult::class);
|
||||
expect('session was not generated', $result->getSession())->null();
|
||||
$activationExists = EmailActivation::find()->andWhere(['key' => $fixture['key']])->exists();
|
||||
expect($activationExists)->false();
|
||||
/** @var Account $account */
|
||||
|
@ -1,6 +1,7 @@
|
||||
<?php
|
||||
namespace tests\codeception\api\traits;
|
||||
|
||||
use api\models\AccountIdentity;
|
||||
use api\traits\AccountFinder;
|
||||
use Codeception\Specify;
|
||||
use common\models\Account;
|
||||
@ -32,6 +33,19 @@ class AccountFinderTest extends DbTestCase {
|
||||
expect($account->id)->equals($this->accounts['admin']['id']);
|
||||
});
|
||||
|
||||
$this->specify('founded account for passed login data with changed account model class name', function() {
|
||||
/** @var AccountFinderTestTestClass $model */
|
||||
$model = new class extends AccountFinderTestTestClass {
|
||||
protected function getAccountClassName() {
|
||||
return AccountIdentity::class;
|
||||
}
|
||||
};
|
||||
$model->login = $this->accounts['admin']['email'];
|
||||
$account = $model->getAccount();
|
||||
expect($account)->isInstanceOf(AccountIdentity::class);
|
||||
expect($account->id)->equals($this->accounts['admin']['id']);
|
||||
});
|
||||
|
||||
$this->specify('null, if account not founded', function() {
|
||||
$model = new AccountFinderTestTestClass();
|
||||
$model->login = 'unexpected';
|
||||
|
Reference in New Issue
Block a user