fitness-web/customerapi/controllers/RestController.php
Roland Schneider f9c845f722 bug fixing
2021-09-28 19:48:07 +02:00

79 lines
1.9 KiB
PHP

<?php
namespace customerapi\controllers;
use common\helpers\CorsCustom;
use common\models\Customer;
use Exception;
use Lcobucci\JWT\Token;
use sizeg\jwt\JwtHttpBearerAuth;
use Yii;
use yii\filters\auth\AuthMethod;
use yii\filters\Cors;
use yii\rest\Controller;
class RestController extends Controller
{
public function behaviors()
{
$behaviors = parent::behaviors();
// $auth = $behaviors['authenticator'];
// unset($behaviors['authenticator']);
// $behaviors['corsFilter'] = [
// 'class' => CorsCustom::class,
// 'cors' => [
// // restrict access to
// 'Origin' => ['https://botondfitness.hu'],
// // Allow credentials (cookies, authorization headers, etc.) to be exposed to the browser
// 'Access-Control-Allow-Credentials' => true,
// ]
// ];
// $behaviors['authenticator'] = $auth;
$behaviors['authenticator'] = [
'class' => JwtHttpBearerAuth::class,
'auth' => [$this, 'auth'],
'optional' => $this->getOptionalActions(),
];
return $behaviors;
}
/**
* This method will check the token
* @param Token $token
* @return Customer|null
*/
public function auth($token)
{
if ( !isset($token ) ) {
return null;
}
try {
$uid = (string) $token->getClaim('uid');
$customer = Customer::findOne(['id_customer' => $uid]);
if (isset($customer)) {
\Yii::$app->user->setIdentity($customer);
return $customer;
}
} catch (Exception $e) {
Yii::error('Failed to load customer: ' . $e->getMessage());
}
return null;
}
/**
* @see AuthMethod::$optional
* @return array
*/
protected function getOptionalActions(){
return [];
}
}