Merge branch 'api_identity_info'

This commit is contained in:
ErickSkrauch 2016-08-06 17:26:32 +03:00
commit 9330041b4c
25 changed files with 384 additions and 52 deletions

View File

@ -0,0 +1,8 @@
<?php
namespace api\components\ApiUser;
class AccessControl extends \yii\filters\AccessControl {
public $user = 'apiUser';
}

View File

@ -0,0 +1,22 @@
<?php
namespace api\components\ApiUser;
use common\models\OauthAccessToken;
use yii\rbac\CheckAccessInterface;
class AuthChecker implements CheckAccessInterface {
/**
* @inheritdoc
*/
public function checkAccess($token, $permissionName, $params = []) : bool {
/** @var OauthAccessToken|null $accessToken */
$accessToken = OauthAccessToken::findOne($token);
if ($accessToken === null) {
return false;
}
return $accessToken->getScopes()->exists($permissionName);
}
}

View File

@ -0,0 +1,23 @@
<?php
namespace api\components\ApiUser;
use yii\web\User as YiiUserComponent;
/**
* @property Identity|null $identity
*
* @method Identity|null getIdentity()
*/
class Component extends YiiUserComponent {
public $identityClass = Identity::class;
public $enableSession = false;
public $loginUrl = null;
public function getAccessChecker() {
return new AuthChecker();
}
}

View File

@ -0,0 +1,81 @@
<?php
namespace api\components\ApiUser;
use common\models\Account;
use common\models\OauthAccessToken;
use common\models\OauthClient;
use common\models\OauthSession;
use yii\base\NotSupportedException;
use yii\web\IdentityInterface;
use yii\web\UnauthorizedHttpException;
/**
* @property Account $account
* @property OauthClient $client
* @property OauthSession $session
* @property OauthAccessToken $accessToken
*/
class Identity implements IdentityInterface {
/**
* @var OauthAccessToken
*/
private $_accessToken;
/**
* @inheritdoc
*/
public static function findIdentityByAccessToken($token, $type = null) {
/** @var OauthAccessToken|null $model */
$model = OauthAccessToken::findOne($token);
if ($model === null) {
throw new UnauthorizedHttpException('Incorrect token');
} elseif ($model->isExpired()) {
throw new UnauthorizedHttpException('Token expired');
}
return new static($model);
}
private function __construct(OauthAccessToken $accessToken) {
$this->_accessToken = $accessToken;
}
public function getAccount() : Account {
return $this->getSession()->account;
}
public function getClient() : OauthClient {
return $this->getSession()->client;
}
public function getSession() : OauthSession {
return $this->_accessToken->session;
}
public function getAccessToken() : OauthAccessToken {
return $this->_accessToken;
}
/**
* Этот метод используется для получения пользователя, к которому привязаны права.
* У нас права привязываются к токенам, так что возвращаем именно его id.
* @inheritdoc
*/
public function getId() {
return $this->_accessToken->access_token;
}
public function getAuthKey() {
throw new NotSupportedException('This method used for cookie auth, except we using Bearer auth');
}
public function validateAuthKey($authKey) {
throw new NotSupportedException('This method used for cookie auth, except we using Bearer auth');
}
public static function findIdentity($id) {
throw new NotSupportedException('This method used for cookie auth, except we using Bearer auth');
}
}

View File

@ -26,6 +26,12 @@ use yii\web\User as YiiUserComponent;
*/
class Component extends YiiUserComponent {
public $enableSession = false;
public $loginUrl = null;
public $identityClass = AccountIdentity::class;
public $secret;
public $expirationTimeout = 3600; // 1h

View File

@ -15,11 +15,11 @@ return [
'components' => [
'user' => [
'class' => \api\components\User\Component::class,
'identityClass' => \api\models\AccountIdentity::class,
'enableSession' => false,
'loginUrl' => null,
'secret' => $params['userSecret'],
],
'apiUser' => [
'class' => \api\components\ApiUser\Component::class,
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [

View File

@ -5,4 +5,6 @@ return [
'/accounts/change-email/confirm-new-email' => 'accounts/change-email-confirm-new-email',
'/oauth2/v1/<action>' => 'oauth/<action>',
'/account/v1/info' => 'identity-info/index',
];

View File

@ -0,0 +1,31 @@
<?php
namespace api\controllers;
use Yii;
use yii\filters\auth\HttpBearerAuth;
/**
* Поведения:
* @mixin \yii\filters\ContentNegotiator
* @mixin \yii\filters\VerbFilter
* @mixin HttpBearerAuth
*/
class ApiController extends \yii\rest\Controller {
public function behaviors() {
$parentBehaviors = parent::behaviors();
// Добавляем авторизатор для входа по Bearer токенам
$parentBehaviors['authenticator'] = [
'class' => HttpBearerAuth::class,
'user' => Yii::$app->apiUser,
];
// xml нам не понадобится
unset($parentBehaviors['contentNegotiator']['formats']['application/xml']);
// rate limiter здесь не применяется
unset($parentBehaviors['rateLimiter']);
return $parentBehaviors;
}
}

View File

@ -2,6 +2,7 @@
namespace api\controllers;
use api\traits\ApiNormalize;
use Yii;
use yii\filters\auth\HttpBearerAuth;
/**
@ -18,6 +19,7 @@ class Controller extends \yii\rest\Controller {
// Добавляем авторизатор для входа по jwt токенам
$parentBehaviors['authenticator'] = [
'class' => HttpBearerAuth::class,
'user' => Yii::$app->getUser(),
];
// xml нам не понадобится

View File

@ -0,0 +1,44 @@
<?php
namespace api\controllers;
use api\components\ApiUser\AccessControl;
use common\models\OauthScope as S;
use Yii;
use yii\helpers\ArrayHelper;
class IdentityInfoController extends ApiController {
public function behaviors() {
return ArrayHelper::merge(parent::behaviors(), [
'access' => [
'class' => AccessControl::class,
'rules' => [
[
'actions' => ['index'],
'allow' => true,
'roles' => [S::ACCOUNT_INFO],
],
],
],
]);
}
public function actionIndex() {
$account = Yii::$app->apiUser->getIdentity()->getAccount();
$response = [
'id' => $account->id,
'uuid' => $account->uuid,
'username' => $account->username,
'registeredAt' => $account->created_at,
'profileLink' => $account->getProfileLink(),
'preferredLanguage' => $account->lang,
];
if (Yii::$app->apiUser->can(S::ACCOUNT_EMAIL)) {
$response['email'] = $account->email;
}
return $response;
}
}

View File

@ -28,6 +28,7 @@ abstract class BaseApplication extends yii\base\Application {
* Include only Web application related components here
*
* @property \api\components\User\Component $user User component.
* @property \api\components\ApiUser\Component $apiUser Api User component.
* @property \api\components\ReCaptcha\Component $reCaptcha
* @property \common\components\oauth\Component $oauth
*

View File

@ -3,7 +3,7 @@ namespace common\helpers;
class StringHelper {
public static function getEmailMask($email) {
public static function getEmailMask(string $email) : string {
$username = explode('@', $email)[0];
$usernameLength = mb_strlen($username);
$maskChars = '**';
@ -21,4 +21,16 @@ class StringHelper {
return $mask . mb_substr($email, $usernameLength);
}
/**
* Проверяет на то, что переданная строка является валидным UUID
* Regex найдено на просторах интернета: http://stackoverflow.com/a/6223221
*
* @param string $uuid
* @return bool
*/
public static function isUuid(string $uuid) : bool {
$re = '/[a-f0-9]{8}\-[a-f0-9]{4}\-4[a-f0-9]{3}\-(8|9|a|b)[a-f0-9]{3}\-[a-f0-9]{12}/';
return preg_match($re, $uuid, $matches) === 1;
}
}

View File

@ -25,7 +25,8 @@ use yii\db\ActiveRecord;
* @property integer $password_changed_at
*
* Геттеры-сеттеры:
* @property string $password пароль пользователя (только для записи)
* @property string $password пароль пользователя (только для записи)
* @property string $profileLink ссылка на профиль на Ely без поддержки static url (только для записи)
*
* Отношения:
* @property EmailActivation[] $emailActivations
@ -144,7 +145,7 @@ class Account extends ActiveRecord {
*
* @return bool
*/
public function canAutoApprove(OauthClient $client, array $scopes = []) {
public function canAutoApprove(OauthClient $client, array $scopes = []) : bool {
if ($client->is_trusted) {
return true;
}
@ -165,10 +166,14 @@ class Account extends ActiveRecord {
* Выполняет проверку, принадлежит ли этому нику аккаунт у Mojang
* @return bool
*/
public function hasMojangUsernameCollision() {
public function hasMojangUsernameCollision() : bool {
return MojangUsername::find()
->andWhere(['username' => $this->username])
->exists();
}
public function getProfileLink() : string {
return 'http://ely.by/u' . $this->id;
}
}

View File

@ -2,7 +2,6 @@
namespace common\models;
use common\components\redis\Set;
use Yii;
use yii\db\ActiveRecord;
/**
@ -13,6 +12,8 @@ use yii\db\ActiveRecord;
* @property integer $expire_time
*
* @property Set $scopes
*
* @property OauthSession $session
*/
class OauthAccessToken extends ActiveRecord {
@ -38,4 +39,8 @@ class OauthAccessToken extends ActiveRecord {
return true;
}
public function isExpired() {
return time() > $this->expire_time;
}
}

View File

@ -1,7 +1,6 @@
<?php
namespace common\models;
use Yii;
use yii\db\ActiveRecord;
/**
@ -12,6 +11,8 @@ class OauthScope extends ActiveRecord {
const OFFLINE_ACCESS = 'offline_access';
const MINECRAFT_SERVER_SESSION = 'minecraft_server_session';
const ACCOUNT_INFO = 'account_info';
const ACCOUNT_EMAIL = 'account_email';
public static function tableName() {
return '{{%oauth_scopes}}';

View File

@ -0,0 +1,18 @@
<?php
use console\db\Migration;
class m160803_185857_account_permissions extends Migration {
public function safeUp() {
$this->batchInsert('{{%oauth_scopes}}', ['id'], [
['account_info'],
['account_email'],
]);
}
public function safeDown() {
$this->delete('{{%oauth_scopes}}', ['id' => ['account_info', 'account_email']]);
}
}

View File

@ -0,0 +1,16 @@
<?php
namespace tests\codeception\api\_pages;
use yii\codeception\BasePage;
/**
* @property \tests\codeception\api\FunctionalTester $actor
*/
class IdentityInfoRoute extends BasePage {
public function info() {
$this->route = ['identity-info/index'];
$this->actor->sendGET($this->getUrl());
}
}

View File

@ -0,0 +1,66 @@
<?php
namespace codeception\api\functional;
use common\models\OauthScope as S;
use tests\codeception\api\_pages\IdentityInfoRoute;
use tests\codeception\api\functional\_steps\OauthSteps;
use tests\codeception\api\FunctionalTester;
class IdentityInfoCest {
/**
* @var IdentityInfoRoute
*/
private $route;
public function _before(FunctionalTester $I) {
$this->route = new IdentityInfoRoute($I);
}
public function testGetErrorIfNotEnoughPerms(OauthSteps $I) {
$accessToken = $I->getAccessToken();
$I->amBearerAuthenticated($accessToken);
$this->route->info();
$I->canSeeResponseCodeIs(403);
$I->canSeeResponseIsJson();
$I->canSeeResponseContainsJson([
'name' => 'Forbidden',
'status' => 403,
]);
}
public function testGetInfo(OauthSteps $I) {
$accessToken = $I->getAccessToken([S::ACCOUNT_INFO]);
$I->amBearerAuthenticated($accessToken);
$this->route->info();
$I->canSeeResponseCodeIs(200);
$I->canSeeResponseIsJson();
$I->canSeeResponseContainsJson([
'id' => 1,
'uuid' => 'df936908-b2e1-544d-96f8-2977ec213022',
'username' => 'Admin',
'registeredAt' => 1451775316,
'profileLink' => 'http://ely.by/u1',
'preferredLanguage' => 'en',
]);
$I->cantSeeResponseJsonMatchesJsonPath('$.email');
}
public function testGetInfoWithEmail(OauthSteps $I) {
$accessToken = $I->getAccessToken([S::ACCOUNT_INFO, S::ACCOUNT_EMAIL]);
$I->amBearerAuthenticated($accessToken);
$this->route->info();
$I->canSeeResponseCodeIs(200);
$I->canSeeResponseIsJson();
$I->canSeeResponseContainsJson([
'id' => 1,
'uuid' => 'df936908-b2e1-544d-96f8-2977ec213022',
'username' => 'Admin',
'registeredAt' => 1451775316,
'profileLink' => 'http://ely.by/u1',
'preferredLanguage' => 'en',
'email' => 'admin@ely.by',
]);
}
}

View File

@ -1,9 +1,9 @@
<?php
namespace tests\codeception\api;
use common\models\OauthScope as S;
use tests\codeception\api\_pages\OauthRoute;
use tests\codeception\api\functional\_steps\OauthSteps;
use Yii;
class OauthAccessTokenCest {
@ -55,7 +55,7 @@ class OauthAccessTokenCest {
}
public function testIssueTokenWithRefreshToken(OauthSteps $I) {
$authCode = $I->getAuthCode(false);
$authCode = $I->getAuthCode([S::OFFLINE_ACCESS]);
$this->route->issueToken($this->buildParams(
$authCode,
'ely',

View File

@ -1,10 +1,9 @@
<?php
namespace tests\codeception\api;
use common\models\OauthScope;
use common\models\OauthScope as S;
use tests\codeception\api\_pages\OauthRoute;
use tests\codeception\api\functional\_steps\OauthSteps;
use Yii;
class OauthRefreshTokenCest {
@ -35,12 +34,12 @@ class OauthRefreshTokenCest {
}
public function testRefreshTokenWithSameScopes(OauthSteps $I) {
$refreshToken = $I->getRefreshToken();
$refreshToken = $I->getRefreshToken([S::MINECRAFT_SERVER_SESSION]);
$this->route->issueToken($this->buildParams(
$refreshToken,
'ely',
'ZuM1vGchJz-9_UZ5HC3H3Z9Hg5PzdbkM',
[OauthScope::MINECRAFT_SERVER_SESSION, OauthScope::OFFLINE_ACCESS]
[S::MINECRAFT_SERVER_SESSION, S::OFFLINE_ACCESS]
));
$I->canSeeResponseCodeIs(200);
$I->canSeeResponseIsJson();
@ -53,12 +52,12 @@ class OauthRefreshTokenCest {
}
public function testRefreshTokenWithNewScopes(OauthSteps $I) {
$refreshToken = $I->getRefreshToken();
$refreshToken = $I->getRefreshToken([S::MINECRAFT_SERVER_SESSION]);
$this->route->issueToken($this->buildParams(
$refreshToken,
'ely',
'ZuM1vGchJz-9_UZ5HC3H3Z9Hg5PzdbkM',
[OauthScope::MINECRAFT_SERVER_SESSION, OauthScope::OFFLINE_ACCESS, 'change_skin']
[S::MINECRAFT_SERVER_SESSION, S::OFFLINE_ACCESS, S::ACCOUNT_EMAIL]
));
$I->canSeeResponseCodeIs(400);
$I->canSeeResponseIsJson();

View File

@ -1,11 +1,12 @@
<?php
namespace tests\codeception\api\functional\_steps;
use common\models\OauthScope as S;
use tests\codeception\api\_pages\OauthRoute;
class OauthSteps extends \tests\codeception\api\FunctionalTester {
public function getAuthCode($online = true) {
public function getAuthCode(array $permissions = []) {
// TODO: по идее можно напрямую сделать зпись в базу, что ускорит процесс тестирования
$this->loggedInAsActiveAccount();
$route = new OauthRoute($this);
@ -13,7 +14,7 @@ class OauthSteps extends \tests\codeception\api\FunctionalTester {
'client_id' => 'ely',
'redirect_uri' => 'http://ely.by',
'response_type' => 'code',
'scope' => 'minecraft_server_session' . ($online ? '' : ',offline_access'),
'scope' => implode(',', $permissions),
], ['accept' => true]);
$this->canSeeResponseJsonMatchesJsonPath('$.redirectUri');
$response = json_decode($this->grabResponse(), true);
@ -22,9 +23,22 @@ class OauthSteps extends \tests\codeception\api\FunctionalTester {
return $matches[1];
}
public function getRefreshToken() {
public function getAccessToken(array $permissions = []) {
$authCode = $this->getAuthCode($permissions);
$response = $this->issueToken($authCode);
return $response['access_token'];
}
public function getRefreshToken(array $permissions = []) {
// TODO: по идее можно напрямую сделать зпись в базу, что ускорит процесс тестирования
$authCode = $this->getAuthCode(false);
$authCode = $this->getAuthCode(array_merge([S::OFFLINE_ACCESS], $permissions));
$response = $this->issueToken($authCode);
return $response['refresh_token'];
}
public function issueToken($authCode) {
$route = new OauthRoute($this);
$route->issueToken([
'code' => $authCode,
@ -34,9 +48,7 @@ class OauthSteps extends \tests\codeception\api\FunctionalTester {
'grant_type' => 'authorization_code',
]);
$response = json_decode($this->grabResponse(), true);
return $response['refresh_token'];
return json_decode($this->grabResponse(), true);
}
}

View File

@ -7,7 +7,6 @@ use tests\codeception\common\fixtures\AccountFixture;
use tests\codeception\common\fixtures\AccountSessionFixture;
use tests\codeception\common\fixtures\EmailActivationFixture;
use tests\codeception\common\fixtures\OauthClientFixture;
use tests\codeception\common\fixtures\OauthScopeFixture;
use tests\codeception\common\fixtures\OauthSessionFixture;
use tests\codeception\common\fixtures\UsernameHistoryFixture;
use yii\test\FixtureTrait;
@ -56,10 +55,6 @@ class FixtureHelper extends Module {
'class' => OauthClientFixture::class,
'dataFile' => '@tests/codeception/common/fixtures/data/oauth-clients.php',
],
'oauthScopes' => [
'class' => OauthScopeFixture::class,
'dataFile' => '@tests/codeception/common/fixtures/data/oauth-scopes.php',
],
'oauthSessions' => [
'class' => OauthSessionFixture::class,
'dataFile' => '@tests/codeception/common/fixtures/data/oauth-sessions.php',

View File

@ -1,11 +0,0 @@
<?php
namespace tests\codeception\common\fixtures;
use common\models\OauthScope;
use yii\test\ActiveFixture;
class OauthScopeFixture extends ActiveFixture {
public $modelClass = OauthScope::class;
}

View File

@ -1,12 +0,0 @@
<?php
return [
'minecraft_server_session' => [
'id' => 'minecraft_server_session',
],
'change_skin' => [
'id' => 'change_skin',
],
'offline_access' => [
'id' => 'offline_access',
],
];

View File

@ -13,4 +13,10 @@ class StringHelperTest extends \PHPUnit_Framework_TestCase {
$this->assertEquals('эр**уч@елу.бел', StringHelper::getEmailMask('эрикскрауч@елу.бел'));
}
public function testIsUuid() {
$this->assertTrue(StringHelper::isUuid('a80b4487-a5c6-45a5-9829-373b4a494135'));
$this->assertFalse(StringHelper::isUuid('12345678'));
$this->assertFalse(StringHelper::isUuid('12345678-1234-1234-1234-123456789123'));
}
}