mirror of
				https://github.com/elyby/accounts.git
				synced 2025-05-31 14:11:46 +05:30 
			
		
		
		
	Merge branch 'account_sessions'
This commit is contained in:
		@@ -53,6 +53,9 @@ RUN chmod a+x /usr/local/bin/composer
 | 
				
			|||||||
 | 
					
 | 
				
			||||||
WORKDIR /var/www/html
 | 
					WORKDIR /var/www/html
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					# Custorm php configuration
 | 
				
			||||||
 | 
					COPY ./docker/php/php.ini /usr/local/etc/php/
 | 
				
			||||||
 | 
					
 | 
				
			||||||
# Copy the working dir to the image's web root
 | 
					# Copy the working dir to the image's web root
 | 
				
			||||||
COPY . /var/www/html
 | 
					COPY . /var/www/html
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 
 | 
				
			|||||||
							
								
								
									
										191
									
								
								api/components/User/Component.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										191
									
								
								api/components/User/Component.php
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,191 @@
 | 
				
			|||||||
 | 
					<?php
 | 
				
			||||||
 | 
					namespace api\components\User;
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					use api\models\AccountIdentity;
 | 
				
			||||||
 | 
					use common\models\AccountSession;
 | 
				
			||||||
 | 
					use Emarref\Jwt\Algorithm\AlgorithmInterface;
 | 
				
			||||||
 | 
					use Emarref\Jwt\Algorithm\Hs256;
 | 
				
			||||||
 | 
					use Emarref\Jwt\Claim;
 | 
				
			||||||
 | 
					use Emarref\Jwt\Encryption\Factory as EncryptionFactory;
 | 
				
			||||||
 | 
					use Emarref\Jwt\Encryption\Factory;
 | 
				
			||||||
 | 
					use Emarref\Jwt\Exception\VerificationException;
 | 
				
			||||||
 | 
					use Emarref\Jwt\Jwt;
 | 
				
			||||||
 | 
					use Emarref\Jwt\Token;
 | 
				
			||||||
 | 
					use Emarref\Jwt\Verification\Context as VerificationContext;
 | 
				
			||||||
 | 
					use Yii;
 | 
				
			||||||
 | 
					use yii\base\ErrorException;
 | 
				
			||||||
 | 
					use yii\base\InvalidConfigException;
 | 
				
			||||||
 | 
					use yii\web\IdentityInterface;
 | 
				
			||||||
 | 
					use yii\web\User as YiiUserComponent;
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					/**
 | 
				
			||||||
 | 
					 * @property AccountSession|null $activeSession
 | 
				
			||||||
 | 
					 */
 | 
				
			||||||
 | 
					class Component extends YiiUserComponent {
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    public $secret;
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    public $expirationTimeout = 3600; // 1h
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    public function init() {
 | 
				
			||||||
 | 
					        parent::init();
 | 
				
			||||||
 | 
					        if (!$this->secret) {
 | 
				
			||||||
 | 
					            throw new InvalidConfigException('secret must be specified');
 | 
				
			||||||
 | 
					        }
 | 
				
			||||||
 | 
					    }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    /**
 | 
				
			||||||
 | 
					     * @param IdentityInterface $identity
 | 
				
			||||||
 | 
					     * @param bool              $rememberMe
 | 
				
			||||||
 | 
					     *
 | 
				
			||||||
 | 
					     * @return LoginResult|bool
 | 
				
			||||||
 | 
					     * @throws ErrorException
 | 
				
			||||||
 | 
					     */
 | 
				
			||||||
 | 
					    public function login(IdentityInterface $identity, $rememberMe = false) {
 | 
				
			||||||
 | 
					        if (!$this->beforeLogin($identity, false, $rememberMe)) {
 | 
				
			||||||
 | 
					            return false;
 | 
				
			||||||
 | 
					        }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					        $this->switchIdentity($identity, 0);
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					        $id = $identity->getId();
 | 
				
			||||||
 | 
					        $ip = Yii::$app->request->userIP;
 | 
				
			||||||
 | 
					        $token = $this->createToken($identity);
 | 
				
			||||||
 | 
					        if ($rememberMe) {
 | 
				
			||||||
 | 
					            $session = new AccountSession();
 | 
				
			||||||
 | 
					            $session->account_id = $id;
 | 
				
			||||||
 | 
					            $session->setIp($ip);
 | 
				
			||||||
 | 
					            $session->generateRefreshToken();
 | 
				
			||||||
 | 
					            if (!$session->save()) {
 | 
				
			||||||
 | 
					                throw new ErrorException('Cannot save account session model');
 | 
				
			||||||
 | 
					            }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					            $token->addClaim(new SessionIdClaim($session->id));
 | 
				
			||||||
 | 
					        } else {
 | 
				
			||||||
 | 
					            $session = null;
 | 
				
			||||||
 | 
					        }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					        $jwt = $this->serializeToken($token);
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					        Yii::info("User '{$id}' logged in from {$ip}.", __METHOD__);
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					        $result = new LoginResult($identity, $jwt, $session);
 | 
				
			||||||
 | 
					        $this->afterLogin($identity, false, $rememberMe);
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					        return $result;
 | 
				
			||||||
 | 
					    }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    public function renew(AccountSession $session) {
 | 
				
			||||||
 | 
					        $account = $session->account;
 | 
				
			||||||
 | 
					        $transaction = Yii::$app->db->beginTransaction();
 | 
				
			||||||
 | 
					        try {
 | 
				
			||||||
 | 
					            $identity = new AccountIdentity($account->attributes);
 | 
				
			||||||
 | 
					            $token = $this->createToken($identity);
 | 
				
			||||||
 | 
					            $jwt = $this->serializeToken($token);
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					            $result = new RenewResult($identity, $jwt);
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					            $session->setIp(Yii::$app->request->userIP);
 | 
				
			||||||
 | 
					            $session->last_refreshed_at = time();
 | 
				
			||||||
 | 
					            if (!$session->save()) {
 | 
				
			||||||
 | 
					                throw new ErrorException('Cannot update session info');
 | 
				
			||||||
 | 
					            }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					            $transaction->commit();
 | 
				
			||||||
 | 
					        } catch (ErrorException $e) {
 | 
				
			||||||
 | 
					            $transaction->rollBack();
 | 
				
			||||||
 | 
					            throw $e;
 | 
				
			||||||
 | 
					        }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					        return $result;
 | 
				
			||||||
 | 
					    }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    /**
 | 
				
			||||||
 | 
					     * @param string $jwtString
 | 
				
			||||||
 | 
					     * @return Token распаршенный токен
 | 
				
			||||||
 | 
					     * @throws VerificationException если один из Claims не пройдёт проверку
 | 
				
			||||||
 | 
					     */
 | 
				
			||||||
 | 
					    public function parseToken(string $jwtString) : Token {
 | 
				
			||||||
 | 
					        $hostInfo = Yii::$app->request->hostInfo;
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					        $jwt = new Jwt();
 | 
				
			||||||
 | 
					        $token = $jwt->deserialize($jwtString);
 | 
				
			||||||
 | 
					        $context = new VerificationContext(Factory::create($this->getAlgorithm()));
 | 
				
			||||||
 | 
					        $context->setAudience($hostInfo);
 | 
				
			||||||
 | 
					        $context->setIssuer($hostInfo);
 | 
				
			||||||
 | 
					        $jwt->verify($token, $context);
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					        return $token;
 | 
				
			||||||
 | 
					    }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    /**
 | 
				
			||||||
 | 
					     * Метод находит AccountSession модель, относительно которой был выдан текущий JWT токен.
 | 
				
			||||||
 | 
					     * В случае, если на пути поиска встретится ошибка, будет возвращено значение null. Возможные кейсы:
 | 
				
			||||||
 | 
					     * - Юзер не авторизован
 | 
				
			||||||
 | 
					     * - Почему-то нет заголовка с токеном
 | 
				
			||||||
 | 
					     * - Во время проверки токена возникла ошибка, что привело к исключению
 | 
				
			||||||
 | 
					     * - В токене не найдено ключа сессии. Такое возможно, если юзер выбрал "не запоминать меня" или просто старые
 | 
				
			||||||
 | 
					     * токены, без поддержки сохранения используемой сессии
 | 
				
			||||||
 | 
					     *
 | 
				
			||||||
 | 
					     * @return AccountSession|null
 | 
				
			||||||
 | 
					     */
 | 
				
			||||||
 | 
					    public function getActiveSession() {
 | 
				
			||||||
 | 
					        if ($this->getIsGuest()) {
 | 
				
			||||||
 | 
					            return null;
 | 
				
			||||||
 | 
					        }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					        $authHeader = Yii::$app->request->getHeaders()->get('Authorization');
 | 
				
			||||||
 | 
					        if ($authHeader === null || !preg_match('/^Bearer\s+(.*?)$/', $authHeader, $matches)) {
 | 
				
			||||||
 | 
					            return null;
 | 
				
			||||||
 | 
					        }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					        $token = $matches[1];
 | 
				
			||||||
 | 
					        try {
 | 
				
			||||||
 | 
					            $token = $this->parseToken($token);
 | 
				
			||||||
 | 
					        } catch (VerificationException $e) {
 | 
				
			||||||
 | 
					            return null;
 | 
				
			||||||
 | 
					        }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					        $sessionId = $token->getPayload()->findClaimByName(SessionIdClaim::NAME);
 | 
				
			||||||
 | 
					        if ($sessionId === null) {
 | 
				
			||||||
 | 
					            return null;
 | 
				
			||||||
 | 
					        }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					        return AccountSession::findOne($sessionId->getValue());
 | 
				
			||||||
 | 
					    }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    public function getAlgorithm() : AlgorithmInterface {
 | 
				
			||||||
 | 
					        return new Hs256($this->secret);
 | 
				
			||||||
 | 
					    }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    protected function serializeToken(Token $token) : string {
 | 
				
			||||||
 | 
					        return (new Jwt())->serialize($token, EncryptionFactory::create($this->getAlgorithm()));
 | 
				
			||||||
 | 
					    }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    protected function createToken(IdentityInterface $identity) : Token {
 | 
				
			||||||
 | 
					        $token = new Token();
 | 
				
			||||||
 | 
					        foreach($this->getClaims($identity) as $claim) {
 | 
				
			||||||
 | 
					            $token->addClaim($claim);
 | 
				
			||||||
 | 
					        }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					        return $token;
 | 
				
			||||||
 | 
					    }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    /**
 | 
				
			||||||
 | 
					     * @param IdentityInterface $identity
 | 
				
			||||||
 | 
					     * @return Claim\AbstractClaim[]
 | 
				
			||||||
 | 
					     */
 | 
				
			||||||
 | 
					    protected function getClaims(IdentityInterface $identity) {
 | 
				
			||||||
 | 
					        $currentTime = time();
 | 
				
			||||||
 | 
					        $hostInfo = Yii::$app->request->hostInfo;
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					        return [
 | 
				
			||||||
 | 
					            new Claim\Audience($hostInfo),
 | 
				
			||||||
 | 
					            new Claim\Issuer($hostInfo),
 | 
				
			||||||
 | 
					            new Claim\IssuedAt($currentTime),
 | 
				
			||||||
 | 
					            new Claim\Expiration($currentTime + $this->expirationTimeout),
 | 
				
			||||||
 | 
					            new Claim\JwtId($identity->getId()),
 | 
				
			||||||
 | 
					        ];
 | 
				
			||||||
 | 
					    }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
							
								
								
									
										61
									
								
								api/components/User/LoginResult.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										61
									
								
								api/components/User/LoginResult.php
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,61 @@
 | 
				
			|||||||
 | 
					<?php
 | 
				
			||||||
 | 
					namespace api\components\User;
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					use common\models\AccountSession;
 | 
				
			||||||
 | 
					use Yii;
 | 
				
			||||||
 | 
					use yii\web\IdentityInterface;
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					class LoginResult {
 | 
				
			||||||
 | 
					    /**
 | 
				
			||||||
 | 
					     * @var IdentityInterface
 | 
				
			||||||
 | 
					     */
 | 
				
			||||||
 | 
					    private $identity;
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    /**
 | 
				
			||||||
 | 
					     * @var string
 | 
				
			||||||
 | 
					     */
 | 
				
			||||||
 | 
					    private $jwt;
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    /**
 | 
				
			||||||
 | 
					     * @var AccountSession|null
 | 
				
			||||||
 | 
					     */
 | 
				
			||||||
 | 
					    private $session;
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    public function __construct(IdentityInterface $identity, string $jwt, AccountSession $session = null) {
 | 
				
			||||||
 | 
					        $this->identity = $identity;
 | 
				
			||||||
 | 
					        $this->jwt = $jwt;
 | 
				
			||||||
 | 
					        $this->session = $session;
 | 
				
			||||||
 | 
					    }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    public function getIdentity() : IdentityInterface {
 | 
				
			||||||
 | 
					        return $this->identity;
 | 
				
			||||||
 | 
					    }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    public function getJwt() : string {
 | 
				
			||||||
 | 
					        return $this->jwt;
 | 
				
			||||||
 | 
					    }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    /**
 | 
				
			||||||
 | 
					     * @return AccountSession|null
 | 
				
			||||||
 | 
					     */
 | 
				
			||||||
 | 
					    public function getSession() {
 | 
				
			||||||
 | 
					        return $this->session;
 | 
				
			||||||
 | 
					    }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    public function getAsResponse() {
 | 
				
			||||||
 | 
					        /** @var Component $component */
 | 
				
			||||||
 | 
					        $component = Yii::$app->user;
 | 
				
			||||||
 | 
					        $response = [
 | 
				
			||||||
 | 
					            'access_token' => $this->getJwt(),
 | 
				
			||||||
 | 
					            'expires_in' => $component->expirationTimeout,
 | 
				
			||||||
 | 
					        ];
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					        $session = $this->getSession();
 | 
				
			||||||
 | 
					        if ($session !== null) {
 | 
				
			||||||
 | 
					            $response['refresh_token'] = $session->refresh_token;
 | 
				
			||||||
 | 
					        }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					        return $response;
 | 
				
			||||||
 | 
					    }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
							
								
								
									
										42
									
								
								api/components/User/RenewResult.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										42
									
								
								api/components/User/RenewResult.php
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,42 @@
 | 
				
			|||||||
 | 
					<?php
 | 
				
			||||||
 | 
					namespace api\components\User;
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					use Yii;
 | 
				
			||||||
 | 
					use yii\web\IdentityInterface;
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					class RenewResult {
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    /**
 | 
				
			||||||
 | 
					     * @var IdentityInterface
 | 
				
			||||||
 | 
					     */
 | 
				
			||||||
 | 
					    private $identity;
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    /**
 | 
				
			||||||
 | 
					     * @var string
 | 
				
			||||||
 | 
					     */
 | 
				
			||||||
 | 
					    private $jwt;
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    public function __construct(IdentityInterface $identity, string $jwt) {
 | 
				
			||||||
 | 
					        $this->identity = $identity;
 | 
				
			||||||
 | 
					        $this->jwt = $jwt;
 | 
				
			||||||
 | 
					    }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    public function getIdentity() : IdentityInterface {
 | 
				
			||||||
 | 
					        return $this->identity;
 | 
				
			||||||
 | 
					    }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    public function getJwt() : string {
 | 
				
			||||||
 | 
					        return $this->jwt;
 | 
				
			||||||
 | 
					    }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    public function getAsResponse() {
 | 
				
			||||||
 | 
					        /** @var Component $component */
 | 
				
			||||||
 | 
					        $component = Yii::$app->user;
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					        return [
 | 
				
			||||||
 | 
					            'access_token' => $this->getJwt(),
 | 
				
			||||||
 | 
					            'expires_in' => $component->expirationTimeout,
 | 
				
			||||||
 | 
					        ];
 | 
				
			||||||
 | 
					    }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
							
								
								
									
										17
									
								
								api/components/User/SessionIdClaim.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										17
									
								
								api/components/User/SessionIdClaim.php
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,17 @@
 | 
				
			|||||||
 | 
					<?php
 | 
				
			||||||
 | 
					namespace api\components\User;
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					use Emarref\Jwt\Claim\AbstractClaim;
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					class SessionIdClaim extends AbstractClaim {
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    const NAME = 'sid';
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    /**
 | 
				
			||||||
 | 
					     * @inheritdoc
 | 
				
			||||||
 | 
					     */
 | 
				
			||||||
 | 
					    public function getName() {
 | 
				
			||||||
 | 
					        return self::NAME;
 | 
				
			||||||
 | 
					    }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
@@ -14,9 +14,11 @@ return [
 | 
				
			|||||||
    'params' => $params,
 | 
					    'params' => $params,
 | 
				
			||||||
    'components' => [
 | 
					    'components' => [
 | 
				
			||||||
        'user' => [
 | 
					        'user' => [
 | 
				
			||||||
 | 
					            'class' => \api\components\User\Component::class,
 | 
				
			||||||
            'identityClass' => \api\models\AccountIdentity::class,
 | 
					            'identityClass' => \api\models\AccountIdentity::class,
 | 
				
			||||||
            'enableSession' => false,
 | 
					            'enableSession' => false,
 | 
				
			||||||
            'loginUrl' => null,
 | 
					            'loginUrl' => null,
 | 
				
			||||||
 | 
					            'secret' => $params['userSecret'],
 | 
				
			||||||
        ],
 | 
					        ],
 | 
				
			||||||
        'log' => [
 | 
					        'log' => [
 | 
				
			||||||
            'traceLevel' => YII_DEBUG ? 3 : 0,
 | 
					            'traceLevel' => YII_DEBUG ? 3 : 0,
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -4,6 +4,7 @@ namespace api\controllers;
 | 
				
			|||||||
use api\models\authentication\ForgotPasswordForm;
 | 
					use api\models\authentication\ForgotPasswordForm;
 | 
				
			||||||
use api\models\authentication\LoginForm;
 | 
					use api\models\authentication\LoginForm;
 | 
				
			||||||
use api\models\authentication\RecoverPasswordForm;
 | 
					use api\models\authentication\RecoverPasswordForm;
 | 
				
			||||||
 | 
					use api\models\authentication\RefreshTokenForm;
 | 
				
			||||||
use common\helpers\StringHelper;
 | 
					use common\helpers\StringHelper;
 | 
				
			||||||
use Yii;
 | 
					use Yii;
 | 
				
			||||||
use yii\filters\AccessControl;
 | 
					use yii\filters\AccessControl;
 | 
				
			||||||
@@ -14,13 +15,13 @@ class AuthenticationController extends Controller {
 | 
				
			|||||||
    public function behaviors() {
 | 
					    public function behaviors() {
 | 
				
			||||||
        return ArrayHelper::merge(parent::behaviors(), [
 | 
					        return ArrayHelper::merge(parent::behaviors(), [
 | 
				
			||||||
            'authenticator' => [
 | 
					            'authenticator' => [
 | 
				
			||||||
                'except' => ['login', 'forgot-password', 'recover-password'],
 | 
					                'except' => ['login', 'forgot-password', 'recover-password', 'refresh-token'],
 | 
				
			||||||
            ],
 | 
					            ],
 | 
				
			||||||
            'access' => [
 | 
					            'access' => [
 | 
				
			||||||
                'class' => AccessControl::class,
 | 
					                'class' => AccessControl::class,
 | 
				
			||||||
                'rules' => [
 | 
					                'rules' => [
 | 
				
			||||||
                    [
 | 
					                    [
 | 
				
			||||||
                        'actions' => ['login', 'forgot-password', 'recover-password'],
 | 
					                        'actions' => ['login', 'forgot-password', 'recover-password', 'refresh-token'],
 | 
				
			||||||
                        'allow' => true,
 | 
					                        'allow' => true,
 | 
				
			||||||
                        'roles' => ['?'],
 | 
					                        'roles' => ['?'],
 | 
				
			||||||
                    ],
 | 
					                    ],
 | 
				
			||||||
@@ -34,13 +35,14 @@ class AuthenticationController extends Controller {
 | 
				
			|||||||
            'login' => ['POST'],
 | 
					            'login' => ['POST'],
 | 
				
			||||||
            'forgot-password' => ['POST'],
 | 
					            'forgot-password' => ['POST'],
 | 
				
			||||||
            'recover-password' => ['POST'],
 | 
					            'recover-password' => ['POST'],
 | 
				
			||||||
 | 
					            'refresh-token' => ['POST'],
 | 
				
			||||||
        ];
 | 
					        ];
 | 
				
			||||||
    }
 | 
					    }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    public function actionLogin() {
 | 
					    public function actionLogin() {
 | 
				
			||||||
        $model = new LoginForm();
 | 
					        $model = new LoginForm();
 | 
				
			||||||
        $model->load(Yii::$app->request->post());
 | 
					        $model->load(Yii::$app->request->post());
 | 
				
			||||||
        if (($jwt = $model->login()) === false) {
 | 
					        if (($result = $model->login()) === false) {
 | 
				
			||||||
            $data = [
 | 
					            $data = [
 | 
				
			||||||
                'success' => false,
 | 
					                'success' => false,
 | 
				
			||||||
                'errors' => $this->normalizeModelErrors($model->getErrors()),
 | 
					                'errors' => $this->normalizeModelErrors($model->getErrors()),
 | 
				
			||||||
@@ -53,10 +55,9 @@ class AuthenticationController extends Controller {
 | 
				
			|||||||
            return $data;
 | 
					            return $data;
 | 
				
			||||||
        }
 | 
					        }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
        return [
 | 
					        return array_merge([
 | 
				
			||||||
            'success' => true,
 | 
					            'success' => true,
 | 
				
			||||||
            'jwt' => $jwt,
 | 
					        ], $result->getAsResponse());
 | 
				
			||||||
        ];
 | 
					 | 
				
			||||||
    }
 | 
					    }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    public function actionForgotPassword() {
 | 
					    public function actionForgotPassword() {
 | 
				
			||||||
@@ -98,17 +99,31 @@ class AuthenticationController extends Controller {
 | 
				
			|||||||
    public function actionRecoverPassword() {
 | 
					    public function actionRecoverPassword() {
 | 
				
			||||||
        $model = new RecoverPasswordForm();
 | 
					        $model = new RecoverPasswordForm();
 | 
				
			||||||
        $model->load(Yii::$app->request->post());
 | 
					        $model->load(Yii::$app->request->post());
 | 
				
			||||||
        if (($jwt = $model->recoverPassword()) === false) {
 | 
					        if (($result = $model->recoverPassword()) === false) {
 | 
				
			||||||
            return [
 | 
					            return [
 | 
				
			||||||
                'success' => false,
 | 
					                'success' => false,
 | 
				
			||||||
                'errors' => $this->normalizeModelErrors($model->getErrors()),
 | 
					                'errors' => $this->normalizeModelErrors($model->getErrors()),
 | 
				
			||||||
            ];
 | 
					            ];
 | 
				
			||||||
        }
 | 
					        }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
        return [
 | 
					        return array_merge([
 | 
				
			||||||
            'success' => true,
 | 
					            'success' => true,
 | 
				
			||||||
            'jwt' => $jwt,
 | 
					        ], $result->getAsResponse());
 | 
				
			||||||
        ];
 | 
					    }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    public function actionRefreshToken() {
 | 
				
			||||||
 | 
					        $model = new RefreshTokenForm();
 | 
				
			||||||
 | 
					        $model->load(Yii::$app->request->post());
 | 
				
			||||||
 | 
					        if (($result = $model->renew()) === false) {
 | 
				
			||||||
 | 
					            return [
 | 
				
			||||||
 | 
					                'success' => false,
 | 
				
			||||||
 | 
					                'errors' => $this->normalizeModelErrors($model->getErrors()),
 | 
				
			||||||
 | 
					            ];
 | 
				
			||||||
 | 
					        }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					        return array_merge([
 | 
				
			||||||
 | 
					            'success' => true,
 | 
				
			||||||
 | 
					        ], $result->getAsResponse());
 | 
				
			||||||
    }
 | 
					    }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -7,6 +7,11 @@ use yii\filters\auth\HttpBearerAuth;
 | 
				
			|||||||
 | 
					
 | 
				
			||||||
/**
 | 
					/**
 | 
				
			||||||
 * @property \common\models\Account|null $account
 | 
					 * @property \common\models\Account|null $account
 | 
				
			||||||
 | 
					 *
 | 
				
			||||||
 | 
					 * Поведения:
 | 
				
			||||||
 | 
					 * @mixin \yii\filters\ContentNegotiator
 | 
				
			||||||
 | 
					 * @mixin \yii\filters\VerbFilter
 | 
				
			||||||
 | 
					 * @mixin \yii\filters\auth\CompositeAuth
 | 
				
			||||||
 */
 | 
					 */
 | 
				
			||||||
class Controller extends \yii\rest\Controller {
 | 
					class Controller extends \yii\rest\Controller {
 | 
				
			||||||
    use ApiNormalize;
 | 
					    use ApiNormalize;
 | 
				
			||||||
@@ -15,7 +20,7 @@ class Controller extends \yii\rest\Controller {
 | 
				
			|||||||
        $parentBehaviors = parent::behaviors();
 | 
					        $parentBehaviors = parent::behaviors();
 | 
				
			||||||
        // Добавляем авторизатор для входа по jwt токенам
 | 
					        // Добавляем авторизатор для входа по jwt токенам
 | 
				
			||||||
        $parentBehaviors['authenticator'] = [
 | 
					        $parentBehaviors['authenticator'] = [
 | 
				
			||||||
            'class' => HttpBearerAuth::className(),
 | 
					            'class' => HttpBearerAuth::class,
 | 
				
			||||||
        ];
 | 
					        ];
 | 
				
			||||||
 | 
					
 | 
				
			||||||
        // xml нам не понадобится
 | 
					        // xml нам не понадобится
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -79,17 +79,16 @@ class SignupController extends Controller {
 | 
				
			|||||||
    public function actionConfirm() {
 | 
					    public function actionConfirm() {
 | 
				
			||||||
        $model = new ConfirmEmailForm();
 | 
					        $model = new ConfirmEmailForm();
 | 
				
			||||||
        $model->load(Yii::$app->request->post());
 | 
					        $model->load(Yii::$app->request->post());
 | 
				
			||||||
        if (!($jwt = $model->confirm())) {
 | 
					        if (!($result = $model->confirm())) {
 | 
				
			||||||
            return [
 | 
					            return [
 | 
				
			||||||
                'success' => false,
 | 
					                'success' => false,
 | 
				
			||||||
                'errors' => $this->normalizeModelErrors($model->getErrors()),
 | 
					                'errors' => $this->normalizeModelErrors($model->getErrors()),
 | 
				
			||||||
            ];
 | 
					            ];
 | 
				
			||||||
        }
 | 
					        }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
        return [
 | 
					        return array_merge([
 | 
				
			||||||
            'success' => true,
 | 
					            'success' => true,
 | 
				
			||||||
            'jwt' => $jwt,
 | 
					        ], $result->getAsResponse());
 | 
				
			||||||
        ];
 | 
					 | 
				
			||||||
    }
 | 
					    }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -2,16 +2,51 @@
 | 
				
			|||||||
namespace api\models;
 | 
					namespace api\models;
 | 
				
			||||||
 | 
					
 | 
				
			||||||
use common\models\Account;
 | 
					use common\models\Account;
 | 
				
			||||||
 | 
					use Emarref\Jwt\Claim\JwtId;
 | 
				
			||||||
 | 
					use Emarref\Jwt\Exception\VerificationException;
 | 
				
			||||||
 | 
					use Emarref\Jwt\Token;
 | 
				
			||||||
 | 
					use Yii;
 | 
				
			||||||
use yii\base\NotSupportedException;
 | 
					use yii\base\NotSupportedException;
 | 
				
			||||||
 | 
					use yii\helpers\StringHelper;
 | 
				
			||||||
use yii\web\IdentityInterface;
 | 
					use yii\web\IdentityInterface;
 | 
				
			||||||
 | 
					use yii\web\UnauthorizedHttpException;
 | 
				
			||||||
 | 
					
 | 
				
			||||||
/**
 | 
					 | 
				
			||||||
 * @method static findIdentityByAccessToken($token, $type = null) этот метод реализуется в UserTrait, который
 | 
					 | 
				
			||||||
 * подключён в родительском Account и позволяет выполнить условия интерфейса
 | 
					 | 
				
			||||||
 * @method string getId() метод реализован в родительском классе, т.к. UserTrait требует, чтобы этот метод
 | 
					 | 
				
			||||||
 * присутствовал обязательно, но при этом не навязывает его как абстрактный
 | 
					 | 
				
			||||||
 */
 | 
					 | 
				
			||||||
class AccountIdentity extends Account implements IdentityInterface {
 | 
					class AccountIdentity extends Account implements IdentityInterface {
 | 
				
			||||||
 | 
					    /**
 | 
				
			||||||
 | 
					     * @inheritdoc
 | 
				
			||||||
 | 
					     */
 | 
				
			||||||
 | 
					    public static function findIdentityByAccessToken($token, $type = null) {
 | 
				
			||||||
 | 
					        /** @var \api\components\User\Component $component */
 | 
				
			||||||
 | 
					        $component = Yii::$app->user;
 | 
				
			||||||
 | 
					        try {
 | 
				
			||||||
 | 
					            $token = $component->parseToken($token);
 | 
				
			||||||
 | 
					        } catch (VerificationException $e) {
 | 
				
			||||||
 | 
					            if (StringHelper::startsWith($e->getMessage(), 'Token expired at')) {
 | 
				
			||||||
 | 
					                $message = 'Token expired';
 | 
				
			||||||
 | 
					            } else {
 | 
				
			||||||
 | 
					                $message = 'Incorrect token';
 | 
				
			||||||
 | 
					            }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					            throw new UnauthorizedHttpException($message);
 | 
				
			||||||
 | 
					        }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					        // Если исключение выше не случилось, то значит всё оке
 | 
				
			||||||
 | 
					        /** @var JwtId $jti */
 | 
				
			||||||
 | 
					        $jti = $token->getPayload()->findClaimByName(JwtId::NAME);
 | 
				
			||||||
 | 
					        $account = static::findOne($jti->getValue());
 | 
				
			||||||
 | 
					        if ($account === null) {
 | 
				
			||||||
 | 
					            throw new UnauthorizedHttpException('Invalid token');
 | 
				
			||||||
 | 
					        }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					        return $account;
 | 
				
			||||||
 | 
					    }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    /**
 | 
				
			||||||
 | 
					     * @inheritdoc
 | 
				
			||||||
 | 
					     */
 | 
				
			||||||
 | 
					    public function getId() {
 | 
				
			||||||
 | 
					        return $this->id;
 | 
				
			||||||
 | 
					    }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    /**
 | 
					    /**
 | 
				
			||||||
     * @inheritdoc
 | 
					     * @inheritdoc
 | 
				
			||||||
@@ -31,7 +66,7 @@ class AccountIdentity extends Account implements IdentityInterface {
 | 
				
			|||||||
     * @inheritdoc
 | 
					     * @inheritdoc
 | 
				
			||||||
     */
 | 
					     */
 | 
				
			||||||
    public function validateAuthKey($authKey) {
 | 
					    public function validateAuthKey($authKey) {
 | 
				
			||||||
        return $this->getAuthKey() === $authKey;
 | 
					        throw new NotSupportedException('This method used for cookie auth, except we using JWT tokens');
 | 
				
			||||||
    }
 | 
					    }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -1,6 +1,7 @@
 | 
				
			|||||||
<?php
 | 
					<?php
 | 
				
			||||||
namespace api\models\authentication;
 | 
					namespace api\models\authentication;
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					use api\models\AccountIdentity;
 | 
				
			||||||
use api\models\base\KeyConfirmationForm;
 | 
					use api\models\base\KeyConfirmationForm;
 | 
				
			||||||
use common\models\Account;
 | 
					use common\models\Account;
 | 
				
			||||||
use common\models\EmailActivation;
 | 
					use common\models\EmailActivation;
 | 
				
			||||||
@@ -43,7 +44,10 @@ class ConfirmEmailForm extends KeyConfirmationForm {
 | 
				
			|||||||
            }
 | 
					            }
 | 
				
			||||||
        }
 | 
					        }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
        return $account->getJWT();
 | 
					        /** @var \api\components\User\Component $component */
 | 
				
			||||||
 | 
					        $component = Yii::$app->user;
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					        return $component->login(new AccountIdentity($account->attributes), true);
 | 
				
			||||||
    }
 | 
					    }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -1,17 +1,21 @@
 | 
				
			|||||||
<?php
 | 
					<?php
 | 
				
			||||||
namespace api\models\authentication;
 | 
					namespace api\models\authentication;
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					use api\models\AccountIdentity;
 | 
				
			||||||
use api\models\base\ApiForm;
 | 
					use api\models\base\ApiForm;
 | 
				
			||||||
use api\traits\AccountFinder;
 | 
					use api\traits\AccountFinder;
 | 
				
			||||||
use common\models\Account;
 | 
					use common\models\Account;
 | 
				
			||||||
use Yii;
 | 
					use Yii;
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					/**
 | 
				
			||||||
 | 
					 * @method AccountIdentity|null getAccount()
 | 
				
			||||||
 | 
					 */
 | 
				
			||||||
class LoginForm extends ApiForm {
 | 
					class LoginForm extends ApiForm {
 | 
				
			||||||
    use AccountFinder;
 | 
					    use AccountFinder;
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    public $login;
 | 
					    public $login;
 | 
				
			||||||
    public $password;
 | 
					    public $password;
 | 
				
			||||||
    public $rememberMe = true;
 | 
					    public $rememberMe = false;
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    public function rules() {
 | 
					    public function rules() {
 | 
				
			||||||
        return [
 | 
					        return [
 | 
				
			||||||
@@ -31,7 +35,7 @@ class LoginForm extends ApiForm {
 | 
				
			|||||||
 | 
					
 | 
				
			||||||
    public function validateLogin($attribute) {
 | 
					    public function validateLogin($attribute) {
 | 
				
			||||||
        if (!$this->hasErrors()) {
 | 
					        if (!$this->hasErrors()) {
 | 
				
			||||||
            if (!$this->getAccount()) {
 | 
					            if ($this->getAccount() === null) {
 | 
				
			||||||
                $this->addError($attribute, 'error.' . $attribute . '_not_exist');
 | 
					                $this->addError($attribute, 'error.' . $attribute . '_not_exist');
 | 
				
			||||||
            }
 | 
					            }
 | 
				
			||||||
        }
 | 
					        }
 | 
				
			||||||
@@ -40,7 +44,7 @@ class LoginForm extends ApiForm {
 | 
				
			|||||||
    public function validatePassword($attribute) {
 | 
					    public function validatePassword($attribute) {
 | 
				
			||||||
        if (!$this->hasErrors()) {
 | 
					        if (!$this->hasErrors()) {
 | 
				
			||||||
            $account = $this->getAccount();
 | 
					            $account = $this->getAccount();
 | 
				
			||||||
            if (!$account || !$account->validatePassword($this->password)) {
 | 
					            if ($account === null || !$account->validatePassword($this->password)) {
 | 
				
			||||||
                $this->addError($attribute, 'error.' . $attribute . '_incorrect');
 | 
					                $this->addError($attribute, 'error.' . $attribute . '_incorrect');
 | 
				
			||||||
            }
 | 
					            }
 | 
				
			||||||
        }
 | 
					        }
 | 
				
			||||||
@@ -60,24 +64,27 @@ class LoginForm extends ApiForm {
 | 
				
			|||||||
    }
 | 
					    }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    /**
 | 
					    /**
 | 
				
			||||||
     * @return bool|string JWT с информацией об аккаунте
 | 
					     * @return \api\components\User\LoginResult|bool
 | 
				
			||||||
     */
 | 
					     */
 | 
				
			||||||
    public function login() {
 | 
					    public function login() {
 | 
				
			||||||
        if (!$this->validate()) {
 | 
					        if (!$this->validate()) {
 | 
				
			||||||
            return false;
 | 
					            return false;
 | 
				
			||||||
        }
 | 
					        }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
        if ($this->rememberMe) {
 | 
					 | 
				
			||||||
            // TODO: здесь нужно записать какую-то
 | 
					 | 
				
			||||||
        }
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
        $account = $this->getAccount();
 | 
					        $account = $this->getAccount();
 | 
				
			||||||
        if ($account->password_hash_strategy === Account::PASS_HASH_STRATEGY_OLD_ELY) {
 | 
					        if ($account->password_hash_strategy === Account::PASS_HASH_STRATEGY_OLD_ELY) {
 | 
				
			||||||
            $account->setPassword($this->password);
 | 
					            $account->setPassword($this->password);
 | 
				
			||||||
            $account->save();
 | 
					            $account->save();
 | 
				
			||||||
        }
 | 
					        }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
        return $account->getJWT();
 | 
					        /** @var \api\components\User\Component $component */
 | 
				
			||||||
 | 
					        $component = Yii::$app->user;
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					        return $component->login($account, $this->rememberMe);
 | 
				
			||||||
 | 
					    }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    protected function getAccountClassName() {
 | 
				
			||||||
 | 
					        return AccountIdentity::class;
 | 
				
			||||||
    }
 | 
					    }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -1,6 +1,7 @@
 | 
				
			|||||||
<?php
 | 
					<?php
 | 
				
			||||||
namespace api\models\authentication;
 | 
					namespace api\models\authentication;
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					use api\models\AccountIdentity;
 | 
				
			||||||
use api\models\base\KeyConfirmationForm;
 | 
					use api\models\base\KeyConfirmationForm;
 | 
				
			||||||
use common\models\EmailActivation;
 | 
					use common\models\EmailActivation;
 | 
				
			||||||
use common\validators\PasswordValidate;
 | 
					use common\validators\PasswordValidate;
 | 
				
			||||||
@@ -63,9 +64,12 @@ class RecoverPasswordForm extends KeyConfirmationForm {
 | 
				
			|||||||
            }
 | 
					            }
 | 
				
			||||||
        }
 | 
					        }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
        // TODO: ещё было бы неплохо уведомить пользователя о том, что его E-mail изменился
 | 
					        // TODO: ещё было бы неплохо уведомить пользователя о том, что его пароль изменился
 | 
				
			||||||
 | 
					
 | 
				
			||||||
        return $account->getJWT();
 | 
					        /** @var \api\components\User\Component $component */
 | 
				
			||||||
 | 
					        $component = Yii::$app->user;
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					        return $component->login(new AccountIdentity($account->attributes), false);
 | 
				
			||||||
    }
 | 
					    }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 
 | 
				
			|||||||
							
								
								
									
										58
									
								
								api/models/authentication/RefreshTokenForm.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										58
									
								
								api/models/authentication/RefreshTokenForm.php
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,58 @@
 | 
				
			|||||||
 | 
					<?php
 | 
				
			||||||
 | 
					namespace api\models\authentication;
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					use api\models\base\ApiForm;
 | 
				
			||||||
 | 
					use common\models\AccountSession;
 | 
				
			||||||
 | 
					use Yii;
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					class RefreshTokenForm extends ApiForm {
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    public $refresh_token;
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    /**
 | 
				
			||||||
 | 
					     * @var AccountSession|null
 | 
				
			||||||
 | 
					     */
 | 
				
			||||||
 | 
					    private $session;
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    public function rules() {
 | 
				
			||||||
 | 
					        return [
 | 
				
			||||||
 | 
					            ['refresh_token', 'required'],
 | 
				
			||||||
 | 
					            ['refresh_token', 'validateRefreshToken'],
 | 
				
			||||||
 | 
					        ];
 | 
				
			||||||
 | 
					    }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    public function validateRefreshToken() {
 | 
				
			||||||
 | 
					        if (!$this->hasErrors()) {
 | 
				
			||||||
 | 
					            /** @var AccountSession|null $token */
 | 
				
			||||||
 | 
					            if ($this->getSession() === null) {
 | 
				
			||||||
 | 
					                $this->addError('refresh_token', 'error.refresh_token_not_exist');
 | 
				
			||||||
 | 
					            }
 | 
				
			||||||
 | 
					        }
 | 
				
			||||||
 | 
					    }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    /**
 | 
				
			||||||
 | 
					     * @return \api\components\User\RenewResult|bool
 | 
				
			||||||
 | 
					     */
 | 
				
			||||||
 | 
					    public function renew() {
 | 
				
			||||||
 | 
					        if (!$this->validate()) {
 | 
				
			||||||
 | 
					            return false;
 | 
				
			||||||
 | 
					        }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					        /** @var \api\components\User\Component $component */
 | 
				
			||||||
 | 
					        $component = Yii::$app->user;
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					        return $component->renew($this->getSession());
 | 
				
			||||||
 | 
					    }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    /**
 | 
				
			||||||
 | 
					     * @return AccountSession|null
 | 
				
			||||||
 | 
					     */
 | 
				
			||||||
 | 
					    public function getSession() {
 | 
				
			||||||
 | 
					        if ($this->session === null) {
 | 
				
			||||||
 | 
					            $this->session = AccountSession::findOne(['refresh_token' => $this->refresh_token]);
 | 
				
			||||||
 | 
					        }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					        return $this->session;
 | 
				
			||||||
 | 
					    }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
@@ -5,6 +5,7 @@ use api\models\base\PasswordProtectedForm;
 | 
				
			|||||||
use common\models\Account;
 | 
					use common\models\Account;
 | 
				
			||||||
use common\validators\PasswordValidate;
 | 
					use common\validators\PasswordValidate;
 | 
				
			||||||
use Yii;
 | 
					use Yii;
 | 
				
			||||||
 | 
					use yii\base\ErrorException;
 | 
				
			||||||
use yii\helpers\ArrayHelper;
 | 
					use yii\helpers\ArrayHelper;
 | 
				
			||||||
 | 
					
 | 
				
			||||||
class ChangePasswordForm extends PasswordProtectedForm {
 | 
					class ChangePasswordForm extends PasswordProtectedForm {
 | 
				
			||||||
@@ -20,6 +21,11 @@ class ChangePasswordForm extends PasswordProtectedForm {
 | 
				
			|||||||
     */
 | 
					     */
 | 
				
			||||||
    private $_account;
 | 
					    private $_account;
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    public function __construct(Account $account, array $config = []) {
 | 
				
			||||||
 | 
					        $this->_account = $account;
 | 
				
			||||||
 | 
					        parent::__construct($config);
 | 
				
			||||||
 | 
					    }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    /**
 | 
					    /**
 | 
				
			||||||
     * @inheritdoc
 | 
					     * @inheritdoc
 | 
				
			||||||
     */
 | 
					     */
 | 
				
			||||||
@@ -41,34 +47,40 @@ class ChangePasswordForm extends PasswordProtectedForm {
 | 
				
			|||||||
    }
 | 
					    }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    /**
 | 
					    /**
 | 
				
			||||||
     * @return boolean if password was changed.
 | 
					     * @return boolean
 | 
				
			||||||
     */
 | 
					     */
 | 
				
			||||||
    public function changePassword() {
 | 
					    public function changePassword() {
 | 
				
			||||||
        if (!$this->validate()) {
 | 
					        if (!$this->validate()) {
 | 
				
			||||||
            return false;
 | 
					            return false;
 | 
				
			||||||
        }
 | 
					        }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					        $transaction = Yii::$app->db->beginTransaction();
 | 
				
			||||||
        $account = $this->_account;
 | 
					        $account = $this->_account;
 | 
				
			||||||
        $account->setPassword($this->newPassword);
 | 
					        $account->setPassword($this->newPassword);
 | 
				
			||||||
 | 
					
 | 
				
			||||||
        if ($this->logoutAll) {
 | 
					        if ($this->logoutAll) {
 | 
				
			||||||
            // TODO: реализовать процесс разлогинивания всех авторизованных устройств и дописать под это всё тесты
 | 
					            /** @var \api\components\User\Component $userComponent */
 | 
				
			||||||
 | 
					            $userComponent = Yii::$app->user;
 | 
				
			||||||
 | 
					            $sessions = $account->sessions;
 | 
				
			||||||
 | 
					            $activeSession = $userComponent->getActiveSession();
 | 
				
			||||||
 | 
					            foreach ($sessions as $session) {
 | 
				
			||||||
 | 
					                if (!$activeSession || $activeSession->id !== $session->id) {
 | 
				
			||||||
 | 
					                    $session->delete();
 | 
				
			||||||
 | 
					                }
 | 
				
			||||||
 | 
					            }
 | 
				
			||||||
        }
 | 
					        }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
        return $account->save();
 | 
					        if (!$account->save()) {
 | 
				
			||||||
 | 
					            throw new ErrorException('Cannot save user model');
 | 
				
			||||||
 | 
					        }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					        $transaction->commit();
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					        return true;
 | 
				
			||||||
    }
 | 
					    }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    protected function getAccount() {
 | 
					    protected function getAccount() {
 | 
				
			||||||
        return $this->_account;
 | 
					        return $this->_account;
 | 
				
			||||||
    }
 | 
					    }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    /**
 | 
					 | 
				
			||||||
     * @param Account $account
 | 
					 | 
				
			||||||
     * @param array  $config
 | 
					 | 
				
			||||||
     */
 | 
					 | 
				
			||||||
    public function __construct(Account $account, array $config = []) {
 | 
					 | 
				
			||||||
        $this->_account = $account;
 | 
					 | 
				
			||||||
        parent::__construct($config);
 | 
					 | 
				
			||||||
    }
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -14,7 +14,8 @@ trait AccountFinder {
 | 
				
			|||||||
     */
 | 
					     */
 | 
				
			||||||
    public function getAccount() {
 | 
					    public function getAccount() {
 | 
				
			||||||
        if ($this->account === null) {
 | 
					        if ($this->account === null) {
 | 
				
			||||||
            $this->account = Account::findOne([$this->getLoginAttribute() => $this->getLogin()]);
 | 
					            $className = $this->getAccountClassName();
 | 
				
			||||||
 | 
					            $this->account = $className::findOne([$this->getLoginAttribute() => $this->getLogin()]);
 | 
				
			||||||
        }
 | 
					        }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
        return $this->account;
 | 
					        return $this->account;
 | 
				
			||||||
@@ -24,4 +25,11 @@ trait AccountFinder {
 | 
				
			|||||||
        return strpos($this->getLogin(), '@') ? 'email' : 'username';
 | 
					        return strpos($this->getLogin(), '@') ? 'email' : 'username';
 | 
				
			||||||
    }
 | 
					    }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    /**
 | 
				
			||||||
 | 
					     * @return Account|string
 | 
				
			||||||
 | 
					     */
 | 
				
			||||||
 | 
					    protected function getAccountClassName() {
 | 
				
			||||||
 | 
					        return Account::class;
 | 
				
			||||||
 | 
					    }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -3,7 +3,6 @@ namespace common\models;
 | 
				
			|||||||
 | 
					
 | 
				
			||||||
use common\components\UserPass;
 | 
					use common\components\UserPass;
 | 
				
			||||||
use common\validators\LanguageValidator;
 | 
					use common\validators\LanguageValidator;
 | 
				
			||||||
use damirka\JWT\UserTrait as UserJWTTrait;
 | 
					 | 
				
			||||||
use Ely\Yii2\TempmailValidator;
 | 
					use Ely\Yii2\TempmailValidator;
 | 
				
			||||||
use Yii;
 | 
					use Yii;
 | 
				
			||||||
use yii\base\InvalidConfigException;
 | 
					use yii\base\InvalidConfigException;
 | 
				
			||||||
@@ -29,15 +28,14 @@ use yii\db\ActiveRecord;
 | 
				
			|||||||
 *
 | 
					 *
 | 
				
			||||||
 * Отношения:
 | 
					 * Отношения:
 | 
				
			||||||
 * @property EmailActivation[] $emailActivations
 | 
					 * @property EmailActivation[] $emailActivations
 | 
				
			||||||
 * @property OauthSession[]    $sessions
 | 
					 * @property OauthSession[]    $oauthSessions
 | 
				
			||||||
 * @property UsernameHistory[] $usernameHistory
 | 
					 * @property UsernameHistory[] $usernameHistory
 | 
				
			||||||
 | 
					 * @property AccountSession[]  $sessions
 | 
				
			||||||
 *
 | 
					 *
 | 
				
			||||||
 * Поведения:
 | 
					 * Поведения:
 | 
				
			||||||
 * @mixin TimestampBehavior
 | 
					 * @mixin TimestampBehavior
 | 
				
			||||||
 */
 | 
					 */
 | 
				
			||||||
class Account extends ActiveRecord {
 | 
					class Account extends ActiveRecord {
 | 
				
			||||||
    use UserJWTTrait;
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
    const STATUS_DELETED = -10;
 | 
					    const STATUS_DELETED = -10;
 | 
				
			||||||
    const STATUS_REGISTERED = 0;
 | 
					    const STATUS_REGISTERED = 0;
 | 
				
			||||||
    const STATUS_ACTIVE = 10;
 | 
					    const STATUS_ACTIVE = 10;
 | 
				
			||||||
@@ -121,7 +119,7 @@ class Account extends ActiveRecord {
 | 
				
			|||||||
        return $this->hasMany(EmailActivation::class, ['account_id' => 'id']);
 | 
					        return $this->hasMany(EmailActivation::class, ['account_id' => 'id']);
 | 
				
			||||||
    }
 | 
					    }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    public function getSessions() {
 | 
					    public function getOauthSessions() {
 | 
				
			||||||
        return $this->hasMany(OauthSession::class, ['owner_id' => 'id']);
 | 
					        return $this->hasMany(OauthSession::class, ['owner_id' => 'id']);
 | 
				
			||||||
    }
 | 
					    }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@@ -129,6 +127,10 @@ class Account extends ActiveRecord {
 | 
				
			|||||||
        return $this->hasMany(UsernameHistory::class, ['account_id' => 'id']);
 | 
					        return $this->hasMany(UsernameHistory::class, ['account_id' => 'id']);
 | 
				
			||||||
    }
 | 
					    }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    public function getSessions() {
 | 
				
			||||||
 | 
					        return $this->hasMany(AccountSession::class, ['account_id' => 'id']);
 | 
				
			||||||
 | 
					    }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    /**
 | 
					    /**
 | 
				
			||||||
     * Метод проверяет, может ли текущий пользователь быть автоматически авторизован
 | 
					     * Метод проверяет, может ли текущий пользователь быть автоматически авторизован
 | 
				
			||||||
     * для указанного клиента без запроса доступа к необходимому списку прав
 | 
					     * для указанного клиента без запроса доступа к необходимому списку прав
 | 
				
			||||||
@@ -144,7 +146,7 @@ class Account extends ActiveRecord {
 | 
				
			|||||||
        }
 | 
					        }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
        /** @var OauthSession|null $session */
 | 
					        /** @var OauthSession|null $session */
 | 
				
			||||||
        $session = $this->getSessions()->andWhere(['client_id' => $client->id])->one();
 | 
					        $session = $this->getOauthSessions()->andWhere(['client_id' => $client->id])->one();
 | 
				
			||||||
        if ($session !== null) {
 | 
					        if ($session !== null) {
 | 
				
			||||||
            $existScopes = $session->getScopes()->members();
 | 
					            $existScopes = $session->getScopes()->members();
 | 
				
			||||||
            if (empty(array_diff(array_keys($scopes), $existScopes))) {
 | 
					            if (empty(array_diff(array_keys($scopes), $existScopes))) {
 | 
				
			||||||
 
 | 
				
			|||||||
							
								
								
									
										54
									
								
								common/models/AccountSession.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										54
									
								
								common/models/AccountSession.php
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,54 @@
 | 
				
			|||||||
 | 
					<?php
 | 
				
			||||||
 | 
					namespace common\models;
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					use Yii;
 | 
				
			||||||
 | 
					use yii\behaviors\TimestampBehavior;
 | 
				
			||||||
 | 
					use yii\db\ActiveRecord;
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					/**
 | 
				
			||||||
 | 
					 * Поля модели:
 | 
				
			||||||
 | 
					 * @property integer $id
 | 
				
			||||||
 | 
					 * @property integer $account_id
 | 
				
			||||||
 | 
					 * @property string  $refresh_token
 | 
				
			||||||
 | 
					 * @property integer $last_used_ip
 | 
				
			||||||
 | 
					 * @property integer $created_at
 | 
				
			||||||
 | 
					 * @property integer $last_refreshed_at
 | 
				
			||||||
 | 
					 *
 | 
				
			||||||
 | 
					 * Отношения:
 | 
				
			||||||
 | 
					 * @property Account $account
 | 
				
			||||||
 | 
					 *
 | 
				
			||||||
 | 
					 * Поведения:
 | 
				
			||||||
 | 
					 * @mixin TimestampBehavior
 | 
				
			||||||
 | 
					 */
 | 
				
			||||||
 | 
					class AccountSession extends ActiveRecord {
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    public static function tableName() {
 | 
				
			||||||
 | 
					        return '{{%accounts_sessions}}';
 | 
				
			||||||
 | 
					    }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    public function behaviors() {
 | 
				
			||||||
 | 
					        return [
 | 
				
			||||||
 | 
					            [
 | 
				
			||||||
 | 
					                'class' => TimestampBehavior::class,
 | 
				
			||||||
 | 
					                'updatedAtAttribute' => 'last_refreshed_at',
 | 
				
			||||||
 | 
					            ]
 | 
				
			||||||
 | 
					        ];
 | 
				
			||||||
 | 
					    }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    public function getAccount() {
 | 
				
			||||||
 | 
					        return $this->hasOne(Account::class, ['id' => 'account_id']);
 | 
				
			||||||
 | 
					    }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    public function generateRefreshToken() {
 | 
				
			||||||
 | 
					        $this->refresh_token = Yii::$app->security->generateRandomString(96);
 | 
				
			||||||
 | 
					    }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    public function setIp($ip) {
 | 
				
			||||||
 | 
					        $this->last_used_ip = ip2long($ip);
 | 
				
			||||||
 | 
					    }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    public function getReadableIp() {
 | 
				
			||||||
 | 
					        return long2ip($this->last_used_ip);
 | 
				
			||||||
 | 
					    }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
@@ -16,15 +16,14 @@
 | 
				
			|||||||
    "require": {
 | 
					    "require": {
 | 
				
			||||||
        "php": "~7.0.6",
 | 
					        "php": "~7.0.6",
 | 
				
			||||||
        "yiisoft/yii2": "~2.0.8",
 | 
					        "yiisoft/yii2": "~2.0.8",
 | 
				
			||||||
        "yiisoft/yii2-bootstrap": "*",
 | 
					 | 
				
			||||||
        "yiisoft/yii2-swiftmailer": "*",
 | 
					        "yiisoft/yii2-swiftmailer": "*",
 | 
				
			||||||
        "ramsey/uuid": "~3.1",
 | 
					        "ramsey/uuid": "~3.1",
 | 
				
			||||||
        "league/oauth2-server": "~4.1.5",
 | 
					        "league/oauth2-server": "~4.1.5",
 | 
				
			||||||
        "yiisoft/yii2-redis": "~2.0.0",
 | 
					        "yiisoft/yii2-redis": "~2.0.0",
 | 
				
			||||||
        "damirka/yii2-jwt": "~0.1.0",
 | 
					 | 
				
			||||||
        "guzzlehttp/guzzle": "~5.3.0",
 | 
					        "guzzlehttp/guzzle": "~5.3.0",
 | 
				
			||||||
        "php-amqplib/php-amqplib": "~2.6.2",
 | 
					        "php-amqplib/php-amqplib": "~2.6.2",
 | 
				
			||||||
        "ely/yii2-tempmail-validator": "~1.0.0"
 | 
					        "ely/yii2-tempmail-validator": "~1.0.0",
 | 
				
			||||||
 | 
					        "emarref/jwt": "~1.0.0"
 | 
				
			||||||
    },
 | 
					    },
 | 
				
			||||||
    "require-dev": {
 | 
					    "require-dev": {
 | 
				
			||||||
        "yiisoft/yii2-codeception": "*",
 | 
					        "yiisoft/yii2-codeception": "*",
 | 
				
			||||||
 
 | 
				
			|||||||
							
								
								
									
										24
									
								
								console/migrations/m160517_151805_account_sessions.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										24
									
								
								console/migrations/m160517_151805_account_sessions.php
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,24 @@
 | 
				
			|||||||
 | 
					<?php
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					use console\db\Migration;
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					class m160517_151805_account_sessions extends Migration {
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    public function safeUp() {
 | 
				
			||||||
 | 
					        $this->createTable('{{%accounts_sessions}}', [
 | 
				
			||||||
 | 
					            'id' => $this->primaryKey(),
 | 
				
			||||||
 | 
					            'account_id' => $this->db->getTableSchema('{{%accounts}}')->getColumn('id')->dbType . ' NOT NULL',
 | 
				
			||||||
 | 
					            'refresh_token' => $this->string()->notNull()->unique(),
 | 
				
			||||||
 | 
					            'last_used_ip' => $this->integer()->unsigned()->notNull(),
 | 
				
			||||||
 | 
					            'created_at' => $this->integer()->notNull(),
 | 
				
			||||||
 | 
					            'last_refreshed_at' => $this->integer()->notNull(),
 | 
				
			||||||
 | 
					        ], $this->tableOptions);
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					        $this->addForeignKey('FK_account_session_to_account', '{{%accounts_sessions}}', 'account_id', '{{%accounts}}', 'id', 'CASCADE', 'CASCADE');
 | 
				
			||||||
 | 
					    }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    public function safeDown() {
 | 
				
			||||||
 | 
					        $this->dropTable('{{%accounts_sessions}}');
 | 
				
			||||||
 | 
					    }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
							
								
								
									
										2
									
								
								docker/php/php.ini
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										2
									
								
								docker/php/php.ini
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,2 @@
 | 
				
			|||||||
 | 
					error_reporting = E_ALL;
 | 
				
			||||||
 | 
					display_errors = On;
 | 
				
			||||||
@@ -1,4 +1,4 @@
 | 
				
			|||||||
<?php
 | 
					<?php
 | 
				
			||||||
return [
 | 
					return [
 | 
				
			||||||
    'jwtSecret' => 'some-long-secret-key',
 | 
					    'userSecret' => 'some-long-secret-key',
 | 
				
			||||||
];
 | 
					];
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -1,4 +1,4 @@
 | 
				
			|||||||
<?php
 | 
					<?php
 | 
				
			||||||
return [
 | 
					return [
 | 
				
			||||||
    'jwtSecret' => 'some-long-secret-key',
 | 
					    'userSecret' => 'some-long-secret-key',
 | 
				
			||||||
];
 | 
					];
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -1,4 +1,4 @@
 | 
				
			|||||||
<?php
 | 
					<?php
 | 
				
			||||||
return [
 | 
					return [
 | 
				
			||||||
    'jwtSecret' => 'some-long-secret-key',
 | 
					    'userSecret' => 'some-long-secret-key',
 | 
				
			||||||
];
 | 
					];
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -8,12 +8,18 @@ use yii\codeception\BasePage;
 | 
				
			|||||||
 */
 | 
					 */
 | 
				
			||||||
class AuthenticationRoute extends BasePage {
 | 
					class AuthenticationRoute extends BasePage {
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    public function login($login = '', $password = '') {
 | 
					    public function login($login = '', $password = '', $rememberMe = false) {
 | 
				
			||||||
        $this->route = ['authentication/login'];
 | 
					        $this->route = ['authentication/login'];
 | 
				
			||||||
        $this->actor->sendPOST($this->getUrl(), [
 | 
					        $params = [
 | 
				
			||||||
            'login' => $login,
 | 
					            'login' => $login,
 | 
				
			||||||
            'password' => $password,
 | 
					            'password' => $password,
 | 
				
			||||||
        ]);
 | 
					        ];
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					        if ($rememberMe) {
 | 
				
			||||||
 | 
					            $params['rememberMe'] = 1;
 | 
				
			||||||
 | 
					        }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					        $this->actor->sendPOST($this->getUrl(), $params);
 | 
				
			||||||
    }
 | 
					    }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    public function forgotPassword($login = '') {
 | 
					    public function forgotPassword($login = '') {
 | 
				
			||||||
@@ -32,4 +38,11 @@ class AuthenticationRoute extends BasePage {
 | 
				
			|||||||
        ]);
 | 
					        ]);
 | 
				
			||||||
    }
 | 
					    }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    public function refreshToken($refreshToken = null) {
 | 
				
			||||||
 | 
					        $this->route = ['authentication/refresh-token'];
 | 
				
			||||||
 | 
					        $this->actor->sendPOST($this->getUrl(), [
 | 
				
			||||||
 | 
					            'refresh_token' => $refreshToken,
 | 
				
			||||||
 | 
					        ]);
 | 
				
			||||||
 | 
					    }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -34,8 +34,8 @@ class FunctionalTester extends Actor {
 | 
				
			|||||||
        }
 | 
					        }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
        $this->canSeeResponseIsJson();
 | 
					        $this->canSeeResponseIsJson();
 | 
				
			||||||
        $this->canSeeResponseJsonMatchesJsonPath('$.jwt');
 | 
					        $this->canSeeAuthCredentials(false);
 | 
				
			||||||
        $jwt = $this->grabDataFromResponseByJsonPath('$.jwt')[0];
 | 
					        $jwt = $this->grabDataFromResponseByJsonPath('$.access_token')[0];
 | 
				
			||||||
        $this->amBearerAuthenticated($jwt);
 | 
					        $this->amBearerAuthenticated($jwt);
 | 
				
			||||||
    }
 | 
					    }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@@ -43,4 +43,14 @@ class FunctionalTester extends Actor {
 | 
				
			|||||||
        $this->haveHttpHeader('Authorization', null);
 | 
					        $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');
 | 
				
			||||||
 | 
					        }
 | 
				
			||||||
 | 
					    }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -34,4 +34,22 @@ class AccountsCurrentCest {
 | 
				
			|||||||
        $I->canSeeResponseJsonMatchesJsonPath('$.passwordChangedAt');
 | 
					        $I->canSeeResponseJsonMatchesJsonPath('$.passwordChangedAt');
 | 
				
			||||||
    }
 | 
					    }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    public function testExpiredCurrent(FunctionalTester $I) {
 | 
				
			||||||
 | 
					        // Устанавливаем заведомо истёкший токен
 | 
				
			||||||
 | 
					        $I->amBearerAuthenticated(
 | 
				
			||||||
 | 
					            'eyJhbGciOiJIUzI1NiJ9.eyJhdWQiOiJodHRwOlwvXC9sb2NhbGhvc3QiLCJpc3MiOiJodHRwOlwvXC9sb2NhbGhvc3QiLCJpYXQiO' .
 | 
				
			||||||
 | 
					            'jE0NjQ2Mjc1NDUsImV4cCI6MTQ2NDYzMTE0NSwianRpIjoxfQ.9c1mm0BK-cuW1qh15F12s2Fh37IN43YeeZeU4DFtlrE'
 | 
				
			||||||
 | 
					        );
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					        $this->route->current();
 | 
				
			||||||
 | 
					        $I->canSeeResponseCodeIs(401);
 | 
				
			||||||
 | 
					        $I->canSeeResponseIsJson();
 | 
				
			||||||
 | 
					        $I->canSeeResponseContainsJson([
 | 
				
			||||||
 | 
					            'name' => 'Unauthorized',
 | 
				
			||||||
 | 
					            'message' => 'Token expired',
 | 
				
			||||||
 | 
					            'code' => 0,
 | 
				
			||||||
 | 
					            'status' => 401,
 | 
				
			||||||
 | 
					        ]);
 | 
				
			||||||
 | 
					    }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -36,7 +36,7 @@ class EmailConfirmationCest {
 | 
				
			|||||||
            'success' => true,
 | 
					            'success' => true,
 | 
				
			||||||
        ]);
 | 
					        ]);
 | 
				
			||||||
        $I->cantSeeResponseJsonMatchesJsonPath('$.errors');
 | 
					        $I->cantSeeResponseJsonMatchesJsonPath('$.errors');
 | 
				
			||||||
        $I->canSeeResponseJsonMatchesJsonPath('$.jwt');
 | 
					        $I->canSeeAuthCredentials(true);
 | 
				
			||||||
    }
 | 
					    }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -111,8 +111,8 @@ class LoginCest {
 | 
				
			|||||||
        $I->canSeeResponseContainsJson([
 | 
					        $I->canSeeResponseContainsJson([
 | 
				
			||||||
            'success' => true,
 | 
					            'success' => true,
 | 
				
			||||||
        ]);
 | 
					        ]);
 | 
				
			||||||
        $I->canSeeResponseJsonMatchesJsonPath('$.jwt');
 | 
					 | 
				
			||||||
        $I->cantSeeResponseJsonMatchesJsonPath('$.errors');
 | 
					        $I->cantSeeResponseJsonMatchesJsonPath('$.errors');
 | 
				
			||||||
 | 
					        $I->canSeeAuthCredentials(false);
 | 
				
			||||||
    }
 | 
					    }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    public function testLoginByEmailCorrect(FunctionalTester $I) {
 | 
					    public function testLoginByEmailCorrect(FunctionalTester $I) {
 | 
				
			||||||
@@ -124,6 +124,7 @@ class LoginCest {
 | 
				
			|||||||
            'success' => true,
 | 
					            'success' => true,
 | 
				
			||||||
        ]);
 | 
					        ]);
 | 
				
			||||||
        $I->cantSeeResponseJsonMatchesJsonPath('$.errors');
 | 
					        $I->cantSeeResponseJsonMatchesJsonPath('$.errors');
 | 
				
			||||||
 | 
					        $I->canSeeAuthCredentials(false);
 | 
				
			||||||
    }
 | 
					    }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    public function testLoginInAccWithPasswordMethod(FunctionalTester $I) {
 | 
					    public function testLoginInAccWithPasswordMethod(FunctionalTester $I) {
 | 
				
			||||||
@@ -134,8 +135,20 @@ class LoginCest {
 | 
				
			|||||||
        $I->canSeeResponseContainsJson([
 | 
					        $I->canSeeResponseContainsJson([
 | 
				
			||||||
            'success' => true,
 | 
					            'success' => true,
 | 
				
			||||||
        ]);
 | 
					        ]);
 | 
				
			||||||
        $I->canSeeResponseJsonMatchesJsonPath('$.jwt');
 | 
					 | 
				
			||||||
        $I->cantSeeResponseJsonMatchesJsonPath('$.errors');
 | 
					        $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([
 | 
					        $I->canSeeResponseContainsJson([
 | 
				
			||||||
            'success' => true,
 | 
					            'success' => true,
 | 
				
			||||||
        ]);
 | 
					        ]);
 | 
				
			||||||
        $I->canSeeResponseJsonMatchesJsonPath('$.jwt');
 | 
					        $I->canSeeAuthCredentials(false);
 | 
				
			||||||
 | 
					
 | 
				
			||||||
        $I->wantTo('ensure, that jwt token is valid');
 | 
					        $I->wantTo('ensure, that jwt token is valid');
 | 
				
			||||||
        $jwt = $I->grabDataFromResponseByJsonPath('$.jwt')[0];
 | 
					        $jwt = $I->grabDataFromResponseByJsonPath('$.access_token')[0];
 | 
				
			||||||
        $I->amBearerAuthenticated($jwt);
 | 
					        $I->amBearerAuthenticated($jwt);
 | 
				
			||||||
        $accountRoute = new AccountsRoute($I);
 | 
					        $accountRoute = new AccountsRoute($I);
 | 
				
			||||||
        $accountRoute->current();
 | 
					        $accountRoute->current();
 | 
				
			||||||
 
 | 
				
			|||||||
							
								
								
									
										32
									
								
								tests/codeception/api/functional/RefreshTokenCest.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										32
									
								
								tests/codeception/api/functional/RefreshTokenCest.php
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,32 @@
 | 
				
			|||||||
 | 
					<?php
 | 
				
			||||||
 | 
					namespace codeception\api\functional;
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					use tests\codeception\api\_pages\AuthenticationRoute;
 | 
				
			||||||
 | 
					use tests\codeception\api\FunctionalTester;
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					class RefreshTokenCest {
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    public function testRefreshInvalidToken(FunctionalTester $I) {
 | 
				
			||||||
 | 
					        $route = new AuthenticationRoute($I);
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					        $I->wantTo('get error.refresh_token_not_exist if passed token is invalid');
 | 
				
			||||||
 | 
					        $route->refreshToken('invalid-token');
 | 
				
			||||||
 | 
					        $I->canSeeResponseCodeIs(200);
 | 
				
			||||||
 | 
					        $I->canSeeResponseContainsJson([
 | 
				
			||||||
 | 
					            'success' => false,
 | 
				
			||||||
 | 
					            'errors' => [
 | 
				
			||||||
 | 
					                'refresh_token' => 'error.refresh_token_not_exist',
 | 
				
			||||||
 | 
					            ],
 | 
				
			||||||
 | 
					        ]);
 | 
				
			||||||
 | 
					    }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    public function testRefreshToken(FunctionalTester $I) {
 | 
				
			||||||
 | 
					        $route = new AuthenticationRoute($I);
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					        $I->wantTo('get new access_token by my refresh_token');
 | 
				
			||||||
 | 
					        $route->refreshToken('SOutIr6Seeaii3uqMVy3Wan8sKFVFrNz');
 | 
				
			||||||
 | 
					        $I->canSeeResponseCodeIs(200);
 | 
				
			||||||
 | 
					        $I->canSeeAuthCredentials(false);
 | 
				
			||||||
 | 
					    }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
							
								
								
									
										194
									
								
								tests/codeception/api/unit/components/User/ComponentTest.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										194
									
								
								tests/codeception/api/unit/components/User/ComponentTest.php
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,194 @@
 | 
				
			|||||||
 | 
					<?php
 | 
				
			||||||
 | 
					namespace codeception\api\unit\components\User;
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					use api\components\User\Component;
 | 
				
			||||||
 | 
					use api\components\User\LoginResult;
 | 
				
			||||||
 | 
					use api\components\User\RenewResult;
 | 
				
			||||||
 | 
					use api\models\AccountIdentity;
 | 
				
			||||||
 | 
					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
 | 
				
			||||||
 | 
					 * @property AccountSessionFixture $sessions
 | 
				
			||||||
 | 
					 */
 | 
				
			||||||
 | 
					class ComponentTest extends DbTestCase {
 | 
				
			||||||
 | 
					    use Specify;
 | 
				
			||||||
 | 
					    use ProtectedCaller;
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    /**
 | 
				
			||||||
 | 
					     * @var Component
 | 
				
			||||||
 | 
					     */
 | 
				
			||||||
 | 
					    private $component;
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    public function _before() {
 | 
				
			||||||
 | 
					        parent::_before();
 | 
				
			||||||
 | 
					        $this->component = new Component($this->getComponentArguments());
 | 
				
			||||||
 | 
					    }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    public function fixtures() {
 | 
				
			||||||
 | 
					        return [
 | 
				
			||||||
 | 
					            'accounts' => AccountFixture::class,
 | 
				
			||||||
 | 
					            'sessions' => AccountSessionFixture::class,
 | 
				
			||||||
 | 
					        ];
 | 
				
			||||||
 | 
					    }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    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);
 | 
				
			||||||
 | 
					            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 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();
 | 
				
			||||||
 | 
					            $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($userIP);
 | 
				
			||||||
 | 
					        });
 | 
				
			||||||
 | 
					    }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    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() {
 | 
				
			||||||
 | 
					            $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);
 | 
				
			||||||
 | 
					        });
 | 
				
			||||||
 | 
					    }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    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();
 | 
				
			||||||
 | 
					        });
 | 
				
			||||||
 | 
					    }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    /**
 | 
				
			||||||
 | 
					     * @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',
 | 
				
			||||||
 | 
					        ];
 | 
				
			||||||
 | 
					    }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
							
								
								
									
										61
									
								
								tests/codeception/api/unit/models/AccountIdentityTest.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										61
									
								
								tests/codeception/api/unit/models/AccountIdentityTest.php
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,61 @@
 | 
				
			|||||||
 | 
					<?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\_support\ProtectedCaller;
 | 
				
			||||||
 | 
					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;
 | 
				
			||||||
 | 
					    use ProtectedCaller;
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    public function fixtures() {
 | 
				
			||||||
 | 
					        return [
 | 
				
			||||||
 | 
					            'accounts' => AccountFixture::class,
 | 
				
			||||||
 | 
					        ];
 | 
				
			||||||
 | 
					    }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    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']);
 | 
				
			||||||
 | 
					        });
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					        $this->specify('get unauthorized exception with "Token expired" message if token valid, but expire', function() {
 | 
				
			||||||
 | 
					            $expiredToken = 'eyJhbGciOiJIUzI1NiJ9.eyJhdWQiOiJodHRwOlwvXC9sb2NhbGhvc3Q6ODA4MCIsImlzcyI6Imh0d' .
 | 
				
			||||||
 | 
					                            'HA6XC9cL2xvY2FsaG9zdDo4MDgwIiwiaWF0IjoxNDY0NTkzMTkzLCJleHAiOjE0NjQ1OTY3OTN9.DV' .
 | 
				
			||||||
 | 
					                            '8uwh0OQhBYXkrNvxwJeO-kEjb9MQeLr3-6GoHM7RY';
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					            try {
 | 
				
			||||||
 | 
					                AccountIdentity::findIdentityByAccessToken($expiredToken);
 | 
				
			||||||
 | 
					            } 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']);
 | 
				
			||||||
 | 
					        $token = $this->callProtected($component, 'createToken', $account);
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					        return $this->callProtected($component, 'serializeToken', $token);
 | 
				
			||||||
 | 
					    }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
@@ -1,9 +1,11 @@
 | 
				
			|||||||
<?php
 | 
					<?php
 | 
				
			||||||
namespace tests\codeception\api\models\authentication;
 | 
					namespace tests\codeception\api\models\authentication;
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					use api\components\User\LoginResult;
 | 
				
			||||||
use api\models\authentication\ConfirmEmailForm;
 | 
					use api\models\authentication\ConfirmEmailForm;
 | 
				
			||||||
use Codeception\Specify;
 | 
					use Codeception\Specify;
 | 
				
			||||||
use common\models\Account;
 | 
					use common\models\Account;
 | 
				
			||||||
 | 
					use common\models\AccountSession;
 | 
				
			||||||
use common\models\EmailActivation;
 | 
					use common\models\EmailActivation;
 | 
				
			||||||
use tests\codeception\api\unit\DbTestCase;
 | 
					use tests\codeception\api\unit\DbTestCase;
 | 
				
			||||||
use tests\codeception\common\fixtures\EmailActivationFixture;
 | 
					use tests\codeception\common\fixtures\EmailActivationFixture;
 | 
				
			||||||
@@ -31,7 +33,9 @@ class ConfirmEmailFormTest extends DbTestCase {
 | 
				
			|||||||
        $fixture = $this->emailActivations['freshRegistrationConfirmation'];
 | 
					        $fixture = $this->emailActivations['freshRegistrationConfirmation'];
 | 
				
			||||||
        $model = $this->createModel($fixture['key']);
 | 
					        $model = $this->createModel($fixture['key']);
 | 
				
			||||||
        $this->specify('expect true result', function() use ($model, $fixture) {
 | 
					        $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();
 | 
					            $activationExists = EmailActivation::find()->andWhere(['key' => $fixture['key']])->exists();
 | 
				
			||||||
            expect('email activation key is not exist', $activationExists)->false();
 | 
					            expect('email activation key is not exist', $activationExists)->false();
 | 
				
			||||||
            /** @var Account $user */
 | 
					            /** @var Account $user */
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -1,6 +1,8 @@
 | 
				
			|||||||
<?php
 | 
					<?php
 | 
				
			||||||
namespace tests\codeception\api\models\authentication;
 | 
					namespace tests\codeception\api\models\authentication;
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					use api\components\User\LoginResult;
 | 
				
			||||||
 | 
					use api\models\AccountIdentity;
 | 
				
			||||||
use api\models\authentication\LoginForm;
 | 
					use api\models\authentication\LoginForm;
 | 
				
			||||||
use Codeception\Specify;
 | 
					use Codeception\Specify;
 | 
				
			||||||
use common\models\Account;
 | 
					use common\models\Account;
 | 
				
			||||||
@@ -14,12 +16,22 @@ use Yii;
 | 
				
			|||||||
class LoginFormTest extends DbTestCase {
 | 
					class LoginFormTest extends DbTestCase {
 | 
				
			||||||
    use Specify;
 | 
					    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() {
 | 
					    public function fixtures() {
 | 
				
			||||||
        return [
 | 
					        return [
 | 
				
			||||||
            'accounts' => [
 | 
					            'accounts' => AccountFixture::class,
 | 
				
			||||||
                'class' => AccountFixture::class,
 | 
					 | 
				
			||||||
                'dataFile' => '@tests/codeception/common/fixtures/data/accounts.php',
 | 
					 | 
				
			||||||
            ],
 | 
					 | 
				
			||||||
        ];
 | 
					        ];
 | 
				
			||||||
    }
 | 
					    }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@@ -36,7 +48,7 @@ class LoginFormTest extends DbTestCase {
 | 
				
			|||||||
        $this->specify('no errors if login exists', function () {
 | 
					        $this->specify('no errors if login exists', function () {
 | 
				
			||||||
            $model = $this->createModel([
 | 
					            $model = $this->createModel([
 | 
				
			||||||
                'login' => 'mr-test',
 | 
					                'login' => 'mr-test',
 | 
				
			||||||
                'account' => new Account(),
 | 
					                'account' => new AccountIdentity(),
 | 
				
			||||||
            ]);
 | 
					            ]);
 | 
				
			||||||
            $model->validateLogin('login');
 | 
					            $model->validateLogin('login');
 | 
				
			||||||
            expect($model->getErrors('login'))->isEmpty();
 | 
					            expect($model->getErrors('login'))->isEmpty();
 | 
				
			||||||
@@ -47,7 +59,7 @@ class LoginFormTest extends DbTestCase {
 | 
				
			|||||||
        $this->specify('error.password_incorrect if password invalid', function () {
 | 
					        $this->specify('error.password_incorrect if password invalid', function () {
 | 
				
			||||||
            $model = $this->createModel([
 | 
					            $model = $this->createModel([
 | 
				
			||||||
                'password' => '87654321',
 | 
					                'password' => '87654321',
 | 
				
			||||||
                'account' => new Account(['password' => '12345678']),
 | 
					                'account' => new AccountIdentity(['password' => '12345678']),
 | 
				
			||||||
            ]);
 | 
					            ]);
 | 
				
			||||||
            $model->validatePassword('password');
 | 
					            $model->validatePassword('password');
 | 
				
			||||||
            expect($model->getErrors('password'))->equals(['error.password_incorrect']);
 | 
					            expect($model->getErrors('password'))->equals(['error.password_incorrect']);
 | 
				
			||||||
@@ -56,7 +68,7 @@ class LoginFormTest extends DbTestCase {
 | 
				
			|||||||
        $this->specify('no errors if password valid', function () {
 | 
					        $this->specify('no errors if password valid', function () {
 | 
				
			||||||
            $model = $this->createModel([
 | 
					            $model = $this->createModel([
 | 
				
			||||||
                'password' => '12345678',
 | 
					                'password' => '12345678',
 | 
				
			||||||
                'account' => new Account(['password' => '12345678']),
 | 
					                'account' => new AccountIdentity(['password' => '12345678']),
 | 
				
			||||||
            ]);
 | 
					            ]);
 | 
				
			||||||
            $model->validatePassword('password');
 | 
					            $model->validatePassword('password');
 | 
				
			||||||
            expect($model->getErrors('password'))->isEmpty();
 | 
					            expect($model->getErrors('password'))->isEmpty();
 | 
				
			||||||
@@ -66,7 +78,7 @@ class LoginFormTest extends DbTestCase {
 | 
				
			|||||||
    public function testValidateActivity() {
 | 
					    public function testValidateActivity() {
 | 
				
			||||||
        $this->specify('error.account_not_activated if account in not activated state', function () {
 | 
					        $this->specify('error.account_not_activated if account in not activated state', function () {
 | 
				
			||||||
            $model = $this->createModel([
 | 
					            $model = $this->createModel([
 | 
				
			||||||
                'account' => new Account(['status' => Account::STATUS_REGISTERED]),
 | 
					                'account' => new AccountIdentity(['status' => Account::STATUS_REGISTERED]),
 | 
				
			||||||
            ]);
 | 
					            ]);
 | 
				
			||||||
            $model->validateActivity('login');
 | 
					            $model->validateActivity('login');
 | 
				
			||||||
            expect($model->getErrors('login'))->equals(['error.account_not_activated']);
 | 
					            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 () {
 | 
					        $this->specify('no errors if account active', function () {
 | 
				
			||||||
            $model = $this->createModel([
 | 
					            $model = $this->createModel([
 | 
				
			||||||
                'account' => new Account(['status' => Account::STATUS_ACTIVE]),
 | 
					                'account' => new AccountIdentity(['status' => Account::STATUS_ACTIVE]),
 | 
				
			||||||
            ]);
 | 
					            ]);
 | 
				
			||||||
            $model->validateActivity('login');
 | 
					            $model->validateActivity('login');
 | 
				
			||||||
            expect($model->getErrors('login'))->isEmpty();
 | 
					            expect($model->getErrors('login'))->isEmpty();
 | 
				
			||||||
@@ -86,13 +98,13 @@ class LoginFormTest extends DbTestCase {
 | 
				
			|||||||
            $model = $this->createModel([
 | 
					            $model = $this->createModel([
 | 
				
			||||||
                'login' => 'erickskrauch',
 | 
					                'login' => 'erickskrauch',
 | 
				
			||||||
                'password' => '12345678',
 | 
					                'password' => '12345678',
 | 
				
			||||||
                'account' => new Account([
 | 
					                'account' => new AccountIdentity([
 | 
				
			||||||
                    'username' => 'erickskrauch',
 | 
					                    'username' => 'erickskrauch',
 | 
				
			||||||
                    'password' => '12345678',
 | 
					                    'password' => '12345678',
 | 
				
			||||||
                    'status' => Account::STATUS_ACTIVE,
 | 
					                    '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();
 | 
					            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'],
 | 
					                'login' => $this->accounts['user-with-old-password-type']['username'],
 | 
				
			||||||
                'password' => '12345678',
 | 
					                'password' => '12345678',
 | 
				
			||||||
            ]);
 | 
					            ]);
 | 
				
			||||||
            expect($model->login())->notEquals(false);
 | 
					            expect($model->login())->isInstanceOf(LoginResult::class);
 | 
				
			||||||
            expect($model->errors)->isEmpty();
 | 
					            expect($model->errors)->isEmpty();
 | 
				
			||||||
            expect($model->getAccount()->password_hash_strategy)->equals(Account::PASS_HASH_STRATEGY_YII2);
 | 
					            expect($model->getAccount()->password_hash_strategy)->equals(Account::PASS_HASH_STRATEGY_YII2);
 | 
				
			||||||
        });
 | 
					        });
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -1,6 +1,7 @@
 | 
				
			|||||||
<?php
 | 
					<?php
 | 
				
			||||||
namespace tests\codeception\api\models\authentication;
 | 
					namespace tests\codeception\api\models\authentication;
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					use api\components\User\LoginResult;
 | 
				
			||||||
use api\models\authentication\RecoverPasswordForm;
 | 
					use api\models\authentication\RecoverPasswordForm;
 | 
				
			||||||
use Codeception\Specify;
 | 
					use Codeception\Specify;
 | 
				
			||||||
use common\models\Account;
 | 
					use common\models\Account;
 | 
				
			||||||
@@ -29,7 +30,9 @@ class RecoverPasswordFormTest extends DbTestCase {
 | 
				
			|||||||
                'newPassword' => '12345678',
 | 
					                'newPassword' => '12345678',
 | 
				
			||||||
                'newRePassword' => '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();
 | 
					            $activationExists = EmailActivation::find()->andWhere(['key' => $fixture['key']])->exists();
 | 
				
			||||||
            expect($activationExists)->false();
 | 
					            expect($activationExists)->false();
 | 
				
			||||||
            /** @var Account $account */
 | 
					            /** @var Account $account */
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -0,0 +1,55 @@
 | 
				
			|||||||
 | 
					<?php
 | 
				
			||||||
 | 
					namespace codeception\api\unit\models\authentication;
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					use api\components\User\RenewResult;
 | 
				
			||||||
 | 
					use api\models\authentication\RefreshTokenForm;
 | 
				
			||||||
 | 
					use Codeception\Specify;
 | 
				
			||||||
 | 
					use common\models\AccountSession;
 | 
				
			||||||
 | 
					use tests\codeception\api\unit\DbTestCase;
 | 
				
			||||||
 | 
					use tests\codeception\common\fixtures\AccountSessionFixture;
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					/**
 | 
				
			||||||
 | 
					 * @property AccountSessionFixture $sessions
 | 
				
			||||||
 | 
					 */
 | 
				
			||||||
 | 
					class RefreshTokenFormTest extends DbTestCase {
 | 
				
			||||||
 | 
					    use Specify;
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    public function fixtures() {
 | 
				
			||||||
 | 
					        return [
 | 
				
			||||||
 | 
					            'sessions' => AccountSessionFixture::class,
 | 
				
			||||||
 | 
					        ];
 | 
				
			||||||
 | 
					    }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    public function testValidateRefreshToken() {
 | 
				
			||||||
 | 
					        $this->specify('error.refresh_token_not_exist if passed token not exists', function() {
 | 
				
			||||||
 | 
					            /** @var RefreshTokenForm $model */
 | 
				
			||||||
 | 
					            $model = new class extends RefreshTokenForm {
 | 
				
			||||||
 | 
					                public function getSession() {
 | 
				
			||||||
 | 
					                    return null;
 | 
				
			||||||
 | 
					                }
 | 
				
			||||||
 | 
					            };
 | 
				
			||||||
 | 
					            $model->validateRefreshToken();
 | 
				
			||||||
 | 
					            expect($model->getErrors('refresh_token'))->equals(['error.refresh_token_not_exist']);
 | 
				
			||||||
 | 
					        });
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					        $this->specify('no errors if token exists', function() {
 | 
				
			||||||
 | 
					            /** @var RefreshTokenForm $model */
 | 
				
			||||||
 | 
					            $model = new class extends RefreshTokenForm {
 | 
				
			||||||
 | 
					                public function getSession() {
 | 
				
			||||||
 | 
					                    return new AccountSession();
 | 
				
			||||||
 | 
					                }
 | 
				
			||||||
 | 
					            };
 | 
				
			||||||
 | 
					            $model->validateRefreshToken();
 | 
				
			||||||
 | 
					            expect($model->getErrors('refresh_token'))->isEmpty();
 | 
				
			||||||
 | 
					        });
 | 
				
			||||||
 | 
					    }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    public function testRenew() {
 | 
				
			||||||
 | 
					        $this->specify('success renew token', function() {
 | 
				
			||||||
 | 
					            $model = new RefreshTokenForm();
 | 
				
			||||||
 | 
					            $model->refresh_token = $this->sessions['admin']['refresh_token'];
 | 
				
			||||||
 | 
					            expect($model->renew())->isInstanceOf(RenewResult::class);
 | 
				
			||||||
 | 
					        });
 | 
				
			||||||
 | 
					    }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
@@ -1,25 +1,28 @@
 | 
				
			|||||||
<?php
 | 
					<?php
 | 
				
			||||||
namespace tests\codeception\api\models\profile;
 | 
					namespace tests\codeception\api\models\profile;
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					use api\components\User\Component;
 | 
				
			||||||
 | 
					use api\models\AccountIdentity;
 | 
				
			||||||
use api\models\profile\ChangePasswordForm;
 | 
					use api\models\profile\ChangePasswordForm;
 | 
				
			||||||
use Codeception\Specify;
 | 
					use Codeception\Specify;
 | 
				
			||||||
use common\models\Account;
 | 
					use common\models\Account;
 | 
				
			||||||
 | 
					use common\models\AccountSession;
 | 
				
			||||||
use tests\codeception\api\unit\DbTestCase;
 | 
					use tests\codeception\api\unit\DbTestCase;
 | 
				
			||||||
use tests\codeception\common\fixtures\AccountFixture;
 | 
					use tests\codeception\common\fixtures\AccountFixture;
 | 
				
			||||||
 | 
					use tests\codeception\common\fixtures\AccountSessionFixture;
 | 
				
			||||||
use Yii;
 | 
					use Yii;
 | 
				
			||||||
 | 
					
 | 
				
			||||||
/**
 | 
					/**
 | 
				
			||||||
 * @property AccountFixture $accounts
 | 
					 * @property AccountFixture $accounts
 | 
				
			||||||
 | 
					 * @property AccountSessionFixture $accountSessions
 | 
				
			||||||
 */
 | 
					 */
 | 
				
			||||||
class ChangePasswordFormTest extends DbTestCase {
 | 
					class ChangePasswordFormTest extends DbTestCase {
 | 
				
			||||||
    use Specify;
 | 
					    use Specify;
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    public function fixtures() {
 | 
					    public function fixtures() {
 | 
				
			||||||
        return [
 | 
					        return [
 | 
				
			||||||
            'accounts' => [
 | 
					            'accounts' => AccountFixture::class,
 | 
				
			||||||
                'class' => AccountFixture::class,
 | 
					            'accountSessions' => AccountSessionFixture::class,
 | 
				
			||||||
                'dataFile' => '@tests/codeception/common/fixtures/data/accounts.php',
 | 
					 | 
				
			||||||
            ],
 | 
					 | 
				
			||||||
        ];
 | 
					        ];
 | 
				
			||||||
    }
 | 
					    }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@@ -63,32 +66,73 @@ class ChangePasswordFormTest extends DbTestCase {
 | 
				
			|||||||
    }
 | 
					    }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    public function testChangePassword() {
 | 
					    public function testChangePassword() {
 | 
				
			||||||
        /** @var Account $account */
 | 
					        $this->specify('successfully change password with modern hash strategy', function() {
 | 
				
			||||||
        $account = Account::findOne($this->accounts['admin']['id']);
 | 
					            /** @var Account $account */
 | 
				
			||||||
        $model = new ChangePasswordForm($account, [
 | 
					            $account = Account::findOne($this->accounts['admin']['id']);
 | 
				
			||||||
            'password' => 'password_0',
 | 
					            $model = new ChangePasswordForm($account, [
 | 
				
			||||||
            'newPassword' => 'my-new-password',
 | 
					                'password' => 'password_0',
 | 
				
			||||||
            'newRePassword' => 'my-new-password',
 | 
					                'newPassword' => 'my-new-password',
 | 
				
			||||||
        ]);
 | 
					                'newRePassword' => 'my-new-password',
 | 
				
			||||||
        $this->specify('successfully change password with modern hash strategy', function() use ($model, $account) {
 | 
					            ]);
 | 
				
			||||||
 | 
					
 | 
				
			||||||
            $callTime = time();
 | 
					            $callTime = time();
 | 
				
			||||||
            expect('form should return true', $model->changePassword())->true();
 | 
					            expect('form should return true', $model->changePassword())->true();
 | 
				
			||||||
            expect('new password should be successfully stored into account', $account->validatePassword('my-new-password'))->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('password change time updated', $account->password_changed_at)->greaterOrEquals($callTime);
 | 
				
			||||||
        });
 | 
					        });
 | 
				
			||||||
 | 
					
 | 
				
			||||||
        /** @var Account $account */
 | 
					        $this->specify('successfully change password with legacy hash strategy', function() {
 | 
				
			||||||
        $account = Account::findOne($this->accounts['user-with-old-password-type']['id']);
 | 
					            /** @var Account $account */
 | 
				
			||||||
        $model = new ChangePasswordForm($account, [
 | 
					            $account = Account::findOne($this->accounts['user-with-old-password-type']['id']);
 | 
				
			||||||
            'password' => '12345678',
 | 
					            $model = new ChangePasswordForm($account, [
 | 
				
			||||||
            'newPassword' => 'my-new-password',
 | 
					                'password' => '12345678',
 | 
				
			||||||
            'newRePassword' => 'my-new-password',
 | 
					                'newPassword' => 'my-new-password',
 | 
				
			||||||
        ]);
 | 
					                'newRePassword' => 'my-new-password',
 | 
				
			||||||
        $this->specify('successfully change password with legacy hash strategy', function() use ($model, $account) {
 | 
					            ]);
 | 
				
			||||||
 | 
					
 | 
				
			||||||
            $callTime = time();
 | 
					            $callTime = time();
 | 
				
			||||||
            expect('form should return true', $model->changePassword())->true();
 | 
					            expect($model->changePassword())->true();
 | 
				
			||||||
            expect('new password should be successfully stored into account', $account->validatePassword('my-new-password'))->true();
 | 
					            expect($account->validatePassword('my-new-password'))->true();
 | 
				
			||||||
            expect('password change time updated', $account->password_changed_at)->greaterOrEquals($callTime);
 | 
					            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);
 | 
				
			||||||
        });
 | 
					        });
 | 
				
			||||||
    }
 | 
					    }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -1,6 +1,7 @@
 | 
				
			|||||||
<?php
 | 
					<?php
 | 
				
			||||||
namespace tests\codeception\api\traits;
 | 
					namespace tests\codeception\api\traits;
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					use api\models\AccountIdentity;
 | 
				
			||||||
use api\traits\AccountFinder;
 | 
					use api\traits\AccountFinder;
 | 
				
			||||||
use Codeception\Specify;
 | 
					use Codeception\Specify;
 | 
				
			||||||
use common\models\Account;
 | 
					use common\models\Account;
 | 
				
			||||||
@@ -32,6 +33,19 @@ class AccountFinderTest extends DbTestCase {
 | 
				
			|||||||
            expect($account->id)->equals($this->accounts['admin']['id']);
 | 
					            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() {
 | 
					        $this->specify('null, if account not founded', function() {
 | 
				
			||||||
            $model = new AccountFinderTestTestClass();
 | 
					            $model = new AccountFinderTestTestClass();
 | 
				
			||||||
            $model->login = 'unexpected';
 | 
					            $model->login = 'unexpected';
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -4,6 +4,7 @@ namespace tests\codeception\common\_support;
 | 
				
			|||||||
use Codeception\Module;
 | 
					use Codeception\Module;
 | 
				
			||||||
use Codeception\TestCase;
 | 
					use Codeception\TestCase;
 | 
				
			||||||
use tests\codeception\common\fixtures\AccountFixture;
 | 
					use tests\codeception\common\fixtures\AccountFixture;
 | 
				
			||||||
 | 
					use tests\codeception\common\fixtures\AccountSessionFixture;
 | 
				
			||||||
use tests\codeception\common\fixtures\EmailActivationFixture;
 | 
					use tests\codeception\common\fixtures\EmailActivationFixture;
 | 
				
			||||||
use tests\codeception\common\fixtures\OauthClientFixture;
 | 
					use tests\codeception\common\fixtures\OauthClientFixture;
 | 
				
			||||||
use tests\codeception\common\fixtures\OauthScopeFixture;
 | 
					use tests\codeception\common\fixtures\OauthScopeFixture;
 | 
				
			||||||
@@ -46,10 +47,8 @@ class FixtureHelper extends Module {
 | 
				
			|||||||
 | 
					
 | 
				
			||||||
    public function fixtures() {
 | 
					    public function fixtures() {
 | 
				
			||||||
        return [
 | 
					        return [
 | 
				
			||||||
            'accounts' => [
 | 
					            'accounts' => AccountFixture::class,
 | 
				
			||||||
                'class' => AccountFixture::class,
 | 
					            'accountSessions' => AccountSessionFixture::class,
 | 
				
			||||||
                'dataFile' => '@tests/codeception/common/fixtures/data/accounts.php',
 | 
					 | 
				
			||||||
            ],
 | 
					 | 
				
			||||||
            'emailActivations' => EmailActivationFixture::class,
 | 
					            'emailActivations' => EmailActivationFixture::class,
 | 
				
			||||||
            'oauthClients' => [
 | 
					            'oauthClients' => [
 | 
				
			||||||
                'class' => OauthClientFixture::class,
 | 
					                'class' => OauthClientFixture::class,
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -8,4 +8,6 @@ class AccountFixture extends ActiveFixture {
 | 
				
			|||||||
 | 
					
 | 
				
			||||||
    public $modelClass = Account::class;
 | 
					    public $modelClass = Account::class;
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    public $dataFile = '@tests/codeception/common/fixtures/data/accounts.php';
 | 
				
			||||||
 | 
					
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 
 | 
				
			|||||||
							
								
								
									
										17
									
								
								tests/codeception/common/fixtures/AccountSessionFixture.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										17
									
								
								tests/codeception/common/fixtures/AccountSessionFixture.php
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,17 @@
 | 
				
			|||||||
 | 
					<?php
 | 
				
			||||||
 | 
					namespace tests\codeception\common\fixtures;
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					use common\models\AccountSession;
 | 
				
			||||||
 | 
					use yii\test\ActiveFixture;
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					class AccountSessionFixture extends ActiveFixture {
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    public $modelClass = AccountSession::class;
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    public $dataFile = '@tests/codeception/common/fixtures/data/account-sessions.php';
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    public $depends = [
 | 
				
			||||||
 | 
					        AccountFixture::class,
 | 
				
			||||||
 | 
					    ];
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
							
								
								
									
										19
									
								
								tests/codeception/common/fixtures/data/account-sessions.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										19
									
								
								tests/codeception/common/fixtures/data/account-sessions.php
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,19 @@
 | 
				
			|||||||
 | 
					<?php
 | 
				
			||||||
 | 
					return [
 | 
				
			||||||
 | 
					    'admin' => [
 | 
				
			||||||
 | 
					        'id' => 1,
 | 
				
			||||||
 | 
					        'account_id' => 1,
 | 
				
			||||||
 | 
					        'refresh_token' => 'SOutIr6Seeaii3uqMVy3Wan8sKFVFrNz',
 | 
				
			||||||
 | 
					        'last_used_ip' => ip2long('127.0.0.1'),
 | 
				
			||||||
 | 
					        'created_at' => time(),
 | 
				
			||||||
 | 
					        'last_refreshed_at' => time(),
 | 
				
			||||||
 | 
					    ],
 | 
				
			||||||
 | 
					    'admin2' => [
 | 
				
			||||||
 | 
					        'id' => 2,
 | 
				
			||||||
 | 
					        'account_id' => 1,
 | 
				
			||||||
 | 
					        'refresh_token' => 'RI5CdxTama2ZijwYw03rJAq84M2JzPM3gDeIDGI8',
 | 
				
			||||||
 | 
					        'last_used_ip' => ip2long('136.243.88.97'),
 | 
				
			||||||
 | 
					        'created_at' => time(),
 | 
				
			||||||
 | 
					        'last_refreshed_at' => time(),
 | 
				
			||||||
 | 
					    ],
 | 
				
			||||||
 | 
					];
 | 
				
			||||||
							
								
								
									
										35
									
								
								tests/codeception/common/unit/models/AccountSessionTest.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										35
									
								
								tests/codeception/common/unit/models/AccountSessionTest.php
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,35 @@
 | 
				
			|||||||
 | 
					<?php
 | 
				
			||||||
 | 
					namespace codeception\common\unit\models;
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					use Codeception\Specify;
 | 
				
			||||||
 | 
					use common\models\AccountSession;
 | 
				
			||||||
 | 
					use tests\codeception\common\unit\TestCase;
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					class AccountSessionTest extends TestCase {
 | 
				
			||||||
 | 
					    use Specify;
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    public function testGenerateRefreshToken() {
 | 
				
			||||||
 | 
					        $this->specify('method call will set refresh_token value', function() {
 | 
				
			||||||
 | 
					            $model = new AccountSession();
 | 
				
			||||||
 | 
					            $model->generateRefreshToken();
 | 
				
			||||||
 | 
					            expect($model->refresh_token)->notNull();
 | 
				
			||||||
 | 
					        });
 | 
				
			||||||
 | 
					    }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    public function testSetIp() {
 | 
				
			||||||
 | 
					        $this->specify('method should convert passed ip string to long', function() {
 | 
				
			||||||
 | 
					            $model = new AccountSession();
 | 
				
			||||||
 | 
					            $model->setIp('127.0.0.1');
 | 
				
			||||||
 | 
					            expect($model->last_used_ip)->equals(2130706433);
 | 
				
			||||||
 | 
					        });
 | 
				
			||||||
 | 
					    }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    public function testGetReadableIp() {
 | 
				
			||||||
 | 
					        $this->specify('method should convert stored ip long into readable ip string', function() {
 | 
				
			||||||
 | 
					            $model = new AccountSession();
 | 
				
			||||||
 | 
					            $model->last_used_ip = 2130706433;
 | 
				
			||||||
 | 
					            expect($model->getReadableIp())->equals('127.0.0.1');
 | 
				
			||||||
 | 
					        });
 | 
				
			||||||
 | 
					    }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
@@ -1,5 +1,8 @@
 | 
				
			|||||||
<?php
 | 
					<?php
 | 
				
			||||||
/**
 | 
					return [
 | 
				
			||||||
 * Application configuration for all api test types
 | 
					    'components' => [
 | 
				
			||||||
 */
 | 
					        'user' => [
 | 
				
			||||||
return [];
 | 
					            'secret' => 'tests-secret-key',
 | 
				
			||||||
 | 
					        ],
 | 
				
			||||||
 | 
					    ],
 | 
				
			||||||
 | 
					];
 | 
				
			||||||
 
 | 
				
			|||||||
		Reference in New Issue
	
	Block a user