Created
February 13, 2015 18:25
-
-
Save agjunior/3fef94034b7e7165c8e8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
* In configuration file | |
* ... | |
* 'as AccessBehavior' => [ | |
* 'class' => '\app\components\AccessBehavior' | |
* ] | |
* ... | |
* (c) Artem Voitko <[email protected]> | |
* | |
* For the full copyright and license information, please view the LICENSE | |
* file that was distributed with this source code. | |
*/ | |
namespace app\components; | |
use yii\base\Behavior; | |
use yii\console\Controller; | |
use yii\helpers\Url; | |
/** | |
* Redirects all users to login page if not logged in | |
* | |
* Class AccessBehavior | |
* @package app\components | |
* @author Artem Voitko <[email protected]> | |
*/ | |
class AccessBehavior extends Behavior | |
{ | |
/** | |
* Subscribe for events | |
* @return array | |
*/ | |
public function events() | |
{ | |
return [ | |
Controller::EVENT_BEFORE_ACTION => 'beforeAction' | |
]; | |
} | |
/** | |
* On event callback | |
*/ | |
public function beforeAction() | |
{ | |
if (\Yii::$app->getUser()->isGuest && | |
\Yii::$app->getRequest()->url !== Url::to(\Yii::$app->getUser()->loginUrl) | |
) { | |
\Yii::$app->getResponse()->redirect(\Yii::$app->getUser()->loginUrl); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment