Skip to content

Instantly share code, notes, and snippets.

@r3verser
Created October 18, 2014 15:08
  • Star 4 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save r3verser/4888b352962dd7de5e3a to your computer and use it in GitHub Desktop.
Yii2 Redirects all users to login page if not logged in
<?php
/*
* In configuration file
* ...
* 'as AccessBehavior' => [
* 'class' => '\app\components\AccessBehavior'
* ]
* ...
* (c) Artem Voitko <r3verser@gmail.com>
*
* 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 <r3verser@gmail.com>
*/
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);
}
}
}
@rvlasenko
Copy link

And now i have not access to sign-up, because AccessBehavior redirects me to login

@r3verser
Copy link
Author

@Exoticness it was just a simple example, if you still need those functionality, check this out!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment