Отрефакторен компонент User\Component

Добавлен метод getActiveSession
Добавлена логика для функции "Разлогинить всех" в форме смены пароля
This commit is contained in:
ErickSkrauch
2016-06-05 17:01:35 +03:00
parent e18f6a08b0
commit 113b9f98d8
9 changed files with 301 additions and 89 deletions

View File

@@ -9,10 +9,14 @@ use Codeception\Specify;
use common\models\AccountSession;
use Emarref\Jwt\Algorithm\AlgorithmInterface;
use Emarref\Jwt\Claim\ClaimInterface;
use Emarref\Jwt\Token;
use tests\codeception\api\unit\DbTestCase;
use tests\codeception\common\_support\ProtectedCaller;
use tests\codeception\common\fixtures\AccountFixture;
use tests\codeception\common\fixtures\AccountSessionFixture;
use Yii;
use yii\web\HeaderCollection;
use yii\web\Request;
/**
* @property AccountFixture $accounts
@@ -22,29 +26,14 @@ 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;
$this->component = new Component($this->getComponentArguments());
}
public function fixtures() {
@@ -55,6 +44,7 @@ class ComponentTest extends DbTestCase {
}
public function testLogin() {
$this->mockRequest();
$this->specify('success get LoginResult object without session value', function() {
$account = new AccountIdentity(['id' => 1]);
$result = $this->component->login($account, false);
@@ -78,29 +68,84 @@ class ComponentTest extends DbTestCase {
public function testRenew() {
$this->specify('success get RenewResult object', function() {
$userIP = '192.168.0.1';
$this->mockRequest($userIP);
/** @var AccountSession $session */
$session = AccountSession::findOne($this->sessions['admin']['id']);
$callTime = time();
$usedRemoteAddr = $_SERVER['REMOTE_ADDR'] ?? null;
$_SERVER['REMOTE_ADDR'] = '192.168.0.1';
$result = $this->component->renew($session);
expect($result)->isInstanceOf(RenewResult::class);
expect(is_string($result->getJwt()))->true();
expect($result->getIdentity()->getId())->equals($session->account_id);
$session->refresh();
expect($session->last_refreshed_at)->greaterOrEquals($callTime);
expect($session->getReadableIp())->equals($_SERVER['REMOTE_ADDR']);
$_SERVER['REMOTE_ADDR'] = $usedRemoteAddr;
expect($session->getReadableIp())->equals($userIP);
});
}
public function testGetJWT() {
public function testParseToken() {
$this->mockRequest();
$this->specify('success get RenewResult object', function() {
$identity = new AccountIdentity(['id' => 1]);
$token = $this->callProtected($this->component, 'createToken', $identity);
$jwt = $this->callProtected($this->component, 'serializeToken', $token);
expect($this->component->parseToken($jwt))->isInstanceOf(Token::class);
});
}
public function testGetActiveSession() {
$this->specify('get used account session', function() {
/** @var AccountIdentity $identity */
$identity = AccountIdentity::findOne($this->accounts['admin']['id']);
$result = $this->component->login($identity, true);
$this->component->logout();
/** @var Component|\PHPUnit_Framework_MockObject_MockObject $component */
$component = $this->getMock(Component::class, ['getIsGuest'], [$this->getComponentArguments()]);
$component
->expects($this->any())
->method('getIsGuest')
->will($this->returnValue(false));
/** @var HeaderCollection|\PHPUnit_Framework_MockObject_MockObject $headersCollection */
$headersCollection = $this->getMock(HeaderCollection::class, ['get']);
$headersCollection
->expects($this->any())
->method('get')
->with($this->equalTo('Authorization'))
->will($this->returnValue('Bearer ' . $result->getJwt()));
/** @var Request|\PHPUnit_Framework_MockObject_MockObject $request */
$request = $this->getMock(Request::class, ['getHeaders']);
$request
->expects($this->any())
->method('getHeaders')
->will($this->returnValue($headersCollection));
Yii::$app->set('request', $request);
$session = $component->getActiveSession();
expect($session)->isInstanceOf(AccountSession::class);
expect($session->id)->equals($result->getSession()->id);
});
}
public function testSerializeToken() {
$this->specify('get string, contained jwt token', function() {
expect($this->component->getJWT(new AccountIdentity(['id' => 1])))
$token = new Token();
expect($this->callProtected($this->component, 'serializeToken', $token))
->regExp('/^[A-Za-z0-9-_=]+\.[A-Za-z0-9-_=]+\.?[A-Za-z0-9-_.+\/=]*$/');
});
}
public function testCreateToken() {
$this->specify('create token', function() {
expect($this->callProtected($this->component, 'createToken', new AccountIdentity(['id' => 1])))
->isInstanceOf(Token::class);
});
}
public function testGetAlgorithm() {
$this->specify('get expected hash algorithm object', function() {
expect($this->component->getAlgorithm())->isInstanceOf(AlgorithmInterface::class);
@@ -117,4 +162,33 @@ class ComponentTest extends DbTestCase {
});
}
/**
* @return \PHPUnit_Framework_MockObject_MockObject
*/
private function mockRequest($userIP = '127.0.0.1') {
$request = $this->getMock(Request::class, ['getHostInfo', 'getUserIP']);
$request
->expects($this->any())
->method('getHostInfo')
->will($this->returnValue('http://localhost'));
$request
->expects($this->any())
->method('getUserIP')
->will($this->returnValue($userIP));
Yii::$app->set('request', $request);
return $request;
}
private function getComponentArguments() {
return [
'identityClass' => AccountIdentity::class,
'enableSession' => false,
'loginUrl' => null,
'secret' => 'secret',
];
}
}

View File

@@ -5,6 +5,7 @@ use api\models\AccountIdentity;
use Codeception\Specify;
use Exception;
use tests\codeception\api\unit\DbTestCase;
use tests\codeception\common\_support\ProtectedCaller;
use tests\codeception\common\fixtures\AccountFixture;
use Yii;
use yii\web\IdentityInterface;
@@ -15,6 +16,7 @@ use yii\web\UnauthorizedHttpException;
*/
class AccountIdentityTest extends DbTestCase {
use Specify;
use ProtectedCaller;
public function fixtures() {
return [
@@ -51,8 +53,9 @@ class AccountIdentityTest extends DbTestCase {
$component = Yii::$app->user;
/** @var AccountIdentity $account */
$account = AccountIdentity::findOne($this->accounts['admin']['id']);
$token = $this->callProtected($component, 'createToken', $account);
return $component->getJWT($account);
return $this->callProtected($component, 'serializeToken', $token);
}
}

View File

@@ -1,25 +1,28 @@
<?php
namespace tests\codeception\api\models\profile;
use api\components\User\Component;
use api\models\AccountIdentity;
use api\models\profile\ChangePasswordForm;
use Codeception\Specify;
use common\models\Account;
use common\models\AccountSession;
use tests\codeception\api\unit\DbTestCase;
use tests\codeception\common\fixtures\AccountFixture;
use tests\codeception\common\fixtures\AccountSessionFixture;
use Yii;
/**
* @property AccountFixture $accounts
* @property AccountSessionFixture $accountSessions
*/
class ChangePasswordFormTest extends DbTestCase {
use Specify;
public function fixtures() {
return [
'accounts' => [
'class' => AccountFixture::class,
'dataFile' => '@tests/codeception/common/fixtures/data/accounts.php',
],
'accounts' => AccountFixture::class,
'accountSessions' => AccountSessionFixture::class,
];
}
@@ -63,32 +66,73 @@ class ChangePasswordFormTest extends DbTestCase {
}
public function testChangePassword() {
/** @var Account $account */
$account = Account::findOne($this->accounts['admin']['id']);
$model = new ChangePasswordForm($account, [
'password' => 'password_0',
'newPassword' => 'my-new-password',
'newRePassword' => 'my-new-password',
]);
$this->specify('successfully change password with modern hash strategy', function() use ($model, $account) {
$this->specify('successfully change password with modern hash strategy', function() {
/** @var Account $account */
$account = Account::findOne($this->accounts['admin']['id']);
$model = new ChangePasswordForm($account, [
'password' => 'password_0',
'newPassword' => 'my-new-password',
'newRePassword' => 'my-new-password',
]);
$callTime = time();
expect('form should return true', $model->changePassword())->true();
expect('new password should be successfully stored into account', $account->validatePassword('my-new-password'))->true();
expect('password change time updated', $account->password_changed_at)->greaterOrEquals($callTime);
});
/** @var Account $account */
$account = Account::findOne($this->accounts['user-with-old-password-type']['id']);
$model = new ChangePasswordForm($account, [
'password' => '12345678',
'newPassword' => 'my-new-password',
'newRePassword' => 'my-new-password',
]);
$this->specify('successfully change password with legacy hash strategy', function() use ($model, $account) {
$this->specify('successfully change password with legacy hash strategy', function() {
/** @var Account $account */
$account = Account::findOne($this->accounts['user-with-old-password-type']['id']);
$model = new ChangePasswordForm($account, [
'password' => '12345678',
'newPassword' => 'my-new-password',
'newRePassword' => 'my-new-password',
]);
$callTime = time();
expect('form should return true', $model->changePassword())->true();
expect('new password should be successfully stored into account', $account->validatePassword('my-new-password'))->true();
expect('password change time updated', $account->password_changed_at)->greaterOrEquals($callTime);
expect($model->changePassword())->true();
expect($account->validatePassword('my-new-password'))->true();
expect($account->password_changed_at)->greaterOrEquals($callTime);
expect($account->password_hash_strategy)->equals(Account::PASS_HASH_STRATEGY_YII2);
});
}
public function testChangePasswordWithLogout() {
/** @var Component|\PHPUnit_Framework_MockObject_MockObject $component */
$component = $this->getMock(Component::class, ['getActiveSession'], [[
'identityClass' => AccountIdentity::class,
'enableSession' => false,
'loginUrl' => null,
'secret' => 'secret',
]]);
/** @var AccountSession $session */
$session = AccountSession::findOne($this->accountSessions['admin2']['id']);
$component
->expects($this->any())
->method('getActiveSession')
->will($this->returnValue($session));
Yii::$app->set('user', $component);
$this->specify('change password with removing all session, except current', function() use ($session) {
/** @var Account $account */
$account = Account::findOne($this->accounts['admin']['id']);
$model = new ChangePasswordForm($account, [
'password' => 'password_0',
'newPassword' => 'my-new-password',
'newRePassword' => 'my-new-password',
'logoutAll' => true,
]);
expect($model->changePassword())->true();
/** @var AccountSession[] $sessions */
$sessions = $account->getSessions()->all();
expect(count($sessions))->equals(1);
expect($sessions[0]->id)->equals($session->id);
});
}