PHP code example of eluhr / yii2-user-auth-token

1. Go to this page and download the library: Download eluhr/yii2-user-auth-token library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

eluhr / yii2-user-auth-token example snippets



return [
    'controllerMap' => [
        'migrate' => [
            'migrationPath' => [
                '@vendor/eluhr/yii2-user-access-token/src/migrations'
            ]
        ]
    ]
]



namespace app\models;

use eluhr\userAccessToken\models\Token;
use yii\base\NotSupportedException;
use yii\filters\auth\QueryParamAuth;
use yii\web\IdentityInterface;

class User extends yii\db\ActiveRecord implements IdentityInterface
{
    /**
     * @param $token
     * @param string $type
     *
     * @throws NotSupportedException
     * @return IdentityInterface|null
     */
    public static function findIdentityByAccessToken($token, $type = null)
    {
        if ($type === QueryParamAuth::class) {
            $token = Token::findValidToken($token); // Change this to your token model if needed
            if ($token instanceof Token) {
                return $token->user;
            }
            return null;
        }

        return parent::findIdentityByAccessToken($token, $type);
    }
}



namespace app\controllers;

use yii\filters\AccessControl;
use yii\filters\auth\QueryParamAuth;
use yii\web\Controller;

class ExampleController extends Controller
{

    public function behaviors()
    {
        $behaviors = parent::behaviors();
        $behaviors['authenticator'] = [
            'class' => QueryParamAuth::class
        ];
        $behaviors['access'] = [
            'class' => AccessControl::class,
            'rules' => [
                [
                    'actions' => ['index'],
                    'allow' => true,
                    'roles' => ['@']
                ]
            ]
        ];
        return $behaviors;
    }

    public function actionIndex()
    {
        return 'Hello World';
    }

}