<?php

namespace PortalPeople\oauth2\filters\auth;
use Yii;
use PortalPeople\oauth2\Module;
use yii\web\UnauthorizedHttpException;

class CompositeAuth extends \yii\filters\auth\CompositeAuth
{
    /**
     * @inheritdoc
     */
    public function beforeAction($action)
    {
        $module = Yii::$app->getModule('oauth2');
        $request = \OAuth2\Request::createFromGlobals();
        $response = new \OAuth2\Response();
        $server = $module->server;
        if ($server->verifyResourceRequest($request, $response)) {
            $user = \common\models\User::find()->where(['user_id' => $server->getAccessTokenData($request)['user_id']])->one();
            Yii::$app->user->login($user);
            return parent::beforeAction($action);            
        }
        throw new UnauthorizedHttpException($response->getStatusText(), $response->getStatusCode());
    }
}
