add ActivatedFilter
This commit is contained in:
74
mobileapi/components/ActivatedFilter.php
Normal file
74
mobileapi/components/ActivatedFilter.php
Normal file
@@ -0,0 +1,74 @@
|
||||
<?php
|
||||
|
||||
namespace mobileapi\components;
|
||||
|
||||
use common\components\HttpStatus;
|
||||
use common\manager\MobileDeviceManager;
|
||||
use Yii;
|
||||
|
||||
use yii\base\Action;
|
||||
use yii\base\ActionFilter;
|
||||
use yii\helpers\StringHelper;
|
||||
use yii\web\HttpException;
|
||||
|
||||
|
||||
class ActivatedFilter extends ActionFilter
|
||||
{
|
||||
/**
|
||||
* @var array list of action IDs that this filter will be applied to, but auth failure will not lead to error.
|
||||
* It may be used for actions, that are allowed for public, but return some additional data for authenticated users.
|
||||
* Defaults to empty, meaning authentication is not optional for any action.
|
||||
* @see isOptional()
|
||||
* @since 2.0.7
|
||||
*/
|
||||
public $optional = [];
|
||||
|
||||
public function beforeAction($action)
|
||||
{
|
||||
try {
|
||||
$activated = false;
|
||||
|
||||
// get the customer
|
||||
$customer = \Yii::$app->user->getIdentity();
|
||||
if (isset($customer)) {
|
||||
$idCard = $customer->id_customer_card;
|
||||
// find out if the device is activated
|
||||
$mobileDeviceManager = new MobileDeviceManager();
|
||||
$activated = $mobileDeviceManager->isMobileDeviceActivatedByIdCard($idCard);
|
||||
}
|
||||
|
||||
// if device is not activated, throw exception with http status 412
|
||||
if ($activated === false) {
|
||||
throw new HttpException( HttpStatus::PRECONDITION_FAILED,"Card not activated");
|
||||
}
|
||||
} catch (HttpException $e) {
|
||||
if ($e->statusCode === HttpStatus::PRECONDITION_FAILED && $this->isOptional($action)) {
|
||||
return true;
|
||||
}
|
||||
throw $e;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks, whether authentication is optional for the given action.
|
||||
*
|
||||
* @param Action $action action to be checked.
|
||||
* @return bool whether authentication is optional or not.
|
||||
* @see optional
|
||||
* @since 2.0.7
|
||||
*/
|
||||
protected function isOptional($action)
|
||||
{
|
||||
$id = $this->getActionId($action);
|
||||
foreach ($this->optional as $pattern) {
|
||||
if (StringHelper::matchWildcard($pattern, $id)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user