Skip to content

Instantly share code, notes, and snippets.

@ineersa
Last active October 10, 2017 19:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ineersa/0a0492c24e35d6227c7993198b71f755 to your computer and use it in GitHub Desktop.
Save ineersa/0a0492c24e35d6227c7993198b71f755 to your computer and use it in GitHub Desktop.
<?php
class AuthControl extends ActionFilter
{
public $denyCallback;
/**
* @inheritdoc
*/
public function beforeAction($action)
{
$headers = Yii::$app->getRequest()->getHeaders();
$serverSign = md5(PUBLIC_KEY.PRIVATE_KEY.$headers->get('X-Auth-Time'));
$clientSign = $headers->get('X-Auth-Key');
if (Yii::$app->getSecurity()->compareString($serverSign, $clientSign)) {
return true;
}
if ($this->denyCallback !== null) {
call_user_func($this->denyCallback, $action);
} else {
$this->denyAccess($action);
}
return false;
}
/**
* Denies the access.
* The default implementation will display 404 page right away, terminating the program execution.
* You may override this method, creating your own deny access handler. While doing so, make sure you
* avoid usage of the current requested host name, creation of absolute URL links, caching page parts and so on.
* @param \yii\base\Action $action the action to be executed.
* @throws NotFoundHttpException
*/
protected function denyAccess($action)
{
$exception = new ForbiddenHttpException(Yii::t('yii', 'Forbidden'));
// use regular error handling if $this->fallbackHostInfo was set
if (!empty(Yii::$app->getRequest()->hostName)) {
throw $exception;
}
$response = Yii::$app->getResponse();
$errorHandler = Yii::$app->getErrorHandler();
$response->setStatusCode($exception->statusCode, $exception->getMessage());
$response->data = $errorHandler->renderFile($errorHandler->errorView, ['exception' => $exception]);
$response->send();
Yii::$app->end();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment