Объединены сущности для авторизации посредством JWT токенов и токенов, выданных через oAuth2.

Все действия, связанные с аккаунтами, теперь вызываются через url `/api/v1/accounts/<id>/<action>`.
Добавлена вменяемая система разграничения прав на основе RBAC.
Теперь oAuth2 токены генерируются как случайная строка в 40 символов длинной, а не UUID.
Исправлен баг с неправильным временем жизни токена в ответе успешного запроса аутентификации.
Теперь все unit тесты можно успешно прогнать без наличия интернета.
This commit is contained in:
ErickSkrauch
2017-09-19 20:06:16 +03:00
parent 928b3aa7fc
commit dd2c4bc413
173 changed files with 2719 additions and 2748 deletions

View File

@@ -51,27 +51,18 @@ class Account extends ActiveRecord {
const PASS_HASH_STRATEGY_OLD_ELY = 0;
const PASS_HASH_STRATEGY_YII2 = 1;
public static function tableName() {
public static function tableName(): string {
return '{{%accounts}}';
}
public function behaviors() {
public function behaviors(): array {
return [
TimestampBehavior::class,
];
}
/**
* Validates password
*
* @param string $password password to validate
* @param integer $passwordHashStrategy
*
* @return bool if password provided is valid for current user
* @throws InvalidConfigException
*/
public function validatePassword($password, $passwordHashStrategy = NULL) : bool {
if ($passwordHashStrategy === NULL) {
public function validatePassword(string $password, int $passwordHashStrategy = null): bool {
if ($passwordHashStrategy === null) {
$passwordHashStrategy = $this->password_hash_strategy;
}
@@ -88,17 +79,13 @@ class Account extends ActiveRecord {
}
}
/**
* @param string $password
* @throws InvalidConfigException
*/
public function setPassword($password) {
public function setPassword(string $password): void {
$this->password_hash_strategy = self::PASS_HASH_STRATEGY_YII2;
$this->password_hash = Yii::$app->security->generatePasswordHash($password);
$this->password_changed_at = time();
}
public function getEmailActivations() {
public function getEmailActivations(): ActiveQuery {
return $this->hasMany(EmailActivation::class, ['account_id' => 'id']);
}
@@ -106,15 +93,15 @@ class Account extends ActiveRecord {
return $this->hasMany(OauthSession::class, ['owner_id' => 'id'])->andWhere(['owner_type' => 'user']);
}
public function getUsernameHistory() {
public function getUsernameHistory(): ActiveQuery {
return $this->hasMany(UsernameHistory::class, ['account_id' => 'id']);
}
public function getSessions() {
public function getSessions(): ActiveQuery {
return $this->hasMany(AccountSession::class, ['account_id' => 'id']);
}
public function getMinecraftAccessKeys() {
public function getMinecraftAccessKeys(): ActiveQuery {
return $this->hasMany(MinecraftAccessKey::class, ['account_id' => 'id']);
}
@@ -123,7 +110,7 @@ class Account extends ActiveRecord {
*
* @return bool
*/
public function hasMojangUsernameCollision() : bool {
public function hasMojangUsernameCollision(): bool {
return MojangUsername::find()
->andWhere(['username' => $this->username])
->exists();
@@ -136,7 +123,7 @@ class Account extends ActiveRecord {
*
* @return string
*/
public function getProfileLink() : string {
public function getProfileLink(): string {
return 'http://ely.by/u' . $this->id;
}
@@ -148,15 +135,15 @@ class Account extends ActiveRecord {
*
* @return bool
*/
public function isAgreedWithActualRules() : bool {
public function isAgreedWithActualRules(): bool {
return $this->rules_agreement_version === LATEST_RULES_VERSION;
}
public function setRegistrationIp($ip) {
public function setRegistrationIp($ip): void {
$this->registration_ip = $ip === null ? null : inet_pton($ip);
}
public function getRegistrationIp() {
public function getRegistrationIp(): ?string {
return $this->registration_ip === null ? null : inet_ntop($this->registration_ip);
}

View File

@@ -0,0 +1,23 @@
<?php
namespace common\models;
final class OauthOwnerType {
/**
* Используется для сессий, принадлежащих непосредственно пользователям account.ely.by,
* выполнивших парольную авторизацию и использующих web интерфейс
*/
public const ACCOUNT = 'accounts';
/**
* Используется когда пользователь по протоколу oAuth2 authorization_code
* разрешает приложению получить доступ и выполнять действия от своего имени
*/
public const USER = 'user';
/**
* Используется для авторизованных по протоколу oAuth2 client_credentials
*/
public const CLIENT = 'client';
}

View File

@@ -1,67 +0,0 @@
<?php
namespace common\models;
use common\components\Annotations\Reader;
use ReflectionClass;
use Yii;
class OauthScope {
/**
* @owner user
*/
const OFFLINE_ACCESS = 'offline_access';
/**
* @owner user
*/
const MINECRAFT_SERVER_SESSION = 'minecraft_server_session';
/**
* @owner user
*/
const ACCOUNT_INFO = 'account_info';
/**
* @owner user
*/
const ACCOUNT_EMAIL = 'account_email';
/**
* @internal
* @owner machine
*/
const ACCOUNT_BLOCK = 'account_block';
/**
* @internal
* @owner machine
*/
const INTERNAL_ACCOUNT_INFO = 'internal_account_info';
public static function find(): OauthScopeQuery {
return new OauthScopeQuery(static::queryScopes());
}
private static function queryScopes(): array {
$cacheKey = 'oauth-scopes-list';
$scopes = false;
if ($scopes === false) {
$scopes = [];
$reflection = new ReflectionClass(static::class);
$constants = $reflection->getConstants();
$reader = Reader::createFromDefaults();
foreach ($constants as $constName => $value) {
$annotations = $reader->getConstantAnnotations(static::class, $constName);
$isInternal = $annotations->get('internal', false);
$owner = $annotations->get('owner', 'user');
$keyValue = [
'value' => $value,
'internal' => $isInternal,
'owner' => $owner,
];
$scopes[$constName] = $keyValue;
}
Yii::$app->cache->set($cacheKey, $scopes, 3600);
}
return $scopes;
}
}

View File

@@ -3,14 +3,15 @@ namespace common\models;
use common\components\Redis\Set;
use Yii;
use yii\base\ErrorException;
use yii\base\NotSupportedException;
use yii\db\ActiveQuery;
use yii\db\ActiveRecord;
/**
* Поля:
* @property integer $id
* @property string $owner_type
* @property string $owner_id
* @property string $owner_type содержит одну из констант OauthOwnerType
* @property string|null $owner_id
* @property string $client_id
* @property string $client_redirect_uri
*
@@ -21,42 +22,50 @@ use yii\db\ActiveRecord;
*/
class OauthSession extends ActiveRecord {
public static function tableName() {
public static function tableName(): string {
return '{{%oauth_sessions}}';
}
public function getAccessTokens() {
throw new ErrorException('This method is possible, but not implemented');
}
public function getClient() {
public function getClient(): ActiveQuery {
return $this->hasOne(OauthClient::class, ['id' => 'client_id']);
}
public function getAccount() {
public function getAccount(): ActiveQuery {
return $this->hasOne(Account::class, ['id' => 'owner_id']);
}
public function getScopes() {
public function getScopes(): Set {
return new Set(static::getDb()->getSchema()->getRawTableName(static::tableName()), $this->id, 'scopes');
}
public function beforeDelete() {
public function getAccessTokens() {
throw new NotSupportedException('This method is possible, but not implemented');
}
public function beforeDelete(): bool {
if (!$result = parent::beforeDelete()) {
return $result;
}
$this->getScopes()->delete();
$this->clearScopes();
$this->removeRefreshToken();
return true;
}
public function removeRefreshToken(): void {
/** @var \api\components\OAuth2\Storage\RefreshTokenStorage $refreshTokensStorage */
$refreshTokensStorage = Yii::$app->oauth->getAuthServer()->getRefreshTokenStorage();
$refreshTokensStorage = Yii::$app->oauth->getRefreshTokenStorage();
$refreshTokensSet = $refreshTokensStorage->sessionHash($this->id);
foreach ($refreshTokensSet->members() as $refreshTokenId) {
$refreshTokensStorage->delete($refreshTokensStorage->get($refreshTokenId));
}
$refreshTokensSet->delete();
}
return true;
public function clearScopes(): void {
$this->getScopes()->delete();
}
}