<?php 
namespace modules\oauth2;

use Yii;
use modules\oauth2\models\OauthUser;
use OAuth2\Storage\Pdo;
use OAuth2\Server;
use OAuth2\GrantType\{AuthorizationCode, ClientCredentials, RefreshToken, UserCredentials};

class Oauth2Module extends \yii\base\Module
{
    public $controllerNamespace = 'modules\\oauth2\\controllers';
    /**
     * @var array Model's map
     */
    public $modelMap = [];
    
    /**
     * @var array Storage's map
     */
    public $storageMap = [];
    
    /**
     * @var array GrantTypes collection
     */
    public $grantTypes = [];
    
    /**
     * @var array server options
     */
    public $options = [];

    /**
     * @var string name of access token parameter
     */
    public $tokenParamName;
    /**
     * @var type max access lifetime
     */
    public $tokenAccessLifetime;
    /**
     * @var whether to use JWT tokens
     */
    public $useJwtToken = false;

    public function getServer(){
        $db = Yii::$app->db;
        $storage = new Pdo(['dsn' => $db->dsn, 'username' => $db->username, 'password' =>  $db->password, 'options' => []]);
        
        // Pass a storage object or array of storage objects to the OAuth2 server class
        $server =  new Server($storage, [
            'allow_implicit' => true,
            'access_lifetime' => 3600 * 24,
            'allow_public_clients' => true,
        ], [
            'password' => new UserCredentials(new OauthUser()),
            'client_credentials' => new ClientCredentials($storage),
            'authorization_code' => new AuthorizationCode($storage),
            'refresh_token' => new RefreshToken($storage),
        ]);    
        return $server;
    }
    /**
     * @inheritdoc
     */
    public function init()
    {
        parent::init();
        Yii::$app->urlManager->addRules([
            'admin/<controller:\w+>/<action:\w+>' => 'oauth2/<controller>/<action>',
        ]);
    }
}
