75 lines
1.8 KiB
PHP
75 lines
1.8 KiB
PHP
<?php
|
|
|
|
namespace mobileapi\controllers;
|
|
|
|
|
|
use common\models\Customer;
|
|
use common\models\MobileDevice;
|
|
use Exception;
|
|
use Lcobucci\JWT\Token;
|
|
use mobileapi\components\ActivatedFilter;
|
|
use sizeg\jwt\JwtHttpBearerAuth;
|
|
use Yii;
|
|
use yii\filters\auth\AuthMethod;
|
|
use yii\rest\Controller;
|
|
|
|
class RestController extends Controller
|
|
{
|
|
|
|
public function behaviors()
|
|
{
|
|
$behaviors = parent::behaviors();
|
|
$behaviors['authenticator'] = [
|
|
'class' => JwtHttpBearerAuth::class,
|
|
'auth' => [$this, 'auth'],
|
|
'optional' => $this->getOptionalActions(),
|
|
];
|
|
$behaviors['activatedChecker'] = [
|
|
'class' => ActivatedFilter::class,
|
|
'optional' => $this->getOptionalActivatedActions()
|
|
];
|
|
return $behaviors;
|
|
}
|
|
|
|
/**
|
|
* This method will check the token
|
|
* @param Token $token
|
|
* @return MobileDevice|null
|
|
*/
|
|
public function auth($token)
|
|
{
|
|
if ( !isset($token ) ) {
|
|
return null;
|
|
}
|
|
try {
|
|
$uid = (string) $token->getClaim('uid');
|
|
$mobileDevice = MobileDevice::findOne(['id' => $uid]);
|
|
if (isset($mobileDevice)) {
|
|
\Yii::$app->user->setIdentity($mobileDevice);
|
|
return $mobileDevice;
|
|
}
|
|
} catch (Exception $e) {
|
|
Yii::error('Failed to load mobile device: ' . $e->getMessage());
|
|
}
|
|
return null;
|
|
}
|
|
|
|
/**
|
|
* @see AuthMethod::$optional
|
|
* @return array
|
|
*/
|
|
protected function getOptionalActions(){
|
|
return [];
|
|
}
|
|
|
|
/**
|
|
* Make the activated filter optional for the actions listed here
|
|
* @return array
|
|
*/
|
|
protected function getOptionalActivatedActions(){
|
|
return [];
|
|
}
|
|
|
|
|
|
}
|