fitness-web/mobileapi/components/ActivatedFilter.php
2022-12-01 20:51:11 +01:00

85 lines
2.5 KiB
PHP

<?php
namespace mobileapi\components;
use common\components\HttpStatus;
use common\models\Card;
use common\models\MobileDevice;
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 device
/** @var MobileDevice $mobileDevice */
$mobileDevice = \Yii::$app->user->getIdentity();
$deviceId = null;
if (isset($mobileDevice)) {
$deviceId = $mobileDevice->id;
$idCard = $mobileDevice->id_card;
// find out if the device is activated
$activated = $mobileDevice->status === MobileDevice::STATUS_ACTIVE;
// override activated to true, if it is a reviewer card
$card = Card::findOne($idCard);
if ( isset($card) ){
if ( isset($card->type) ){
$activated = true;
}
}
}
// if device is not activated, throw exception with http status 412
if ($activated === false) {
throw new HttpException( HttpStatus::PRECONDITION_FAILED,"Device is not activated: " . $deviceId);
}
} 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;
}
}