简体   繁体   中英

Yii2 Dektrium User, make login required for all actions and all controllers

To make login necessary for all controllers and actions I did as said in Yii2 require all Controller and Action to login and added the below code to web.php

'as beforeRequest' => [
        'class' => 'yii\filters\AccessControl',
        'rules' => [
                [
                        'allow' => true,
                        'actions' => ['login', 'forgot'],
                ],
                [
                        'allow' => true,
                        'roles' => ['@'],
                ],

        ],
        'denyCallback' => function () {
                return Yii::$app->response->redirect(['user/login']);
        },
],

but the problem is that ALL other actions like Forgot password are redirected to login page, I want to exclude user/forgot route from the login required condition. please help!

Thanks

I know I'm 3-years late, but it could be useful for other people searching for this answer :)

In config/web.php

$config => [
/* ... */
    'as AccessBehavior' => [
    'class' => 'app\components\AccessBehavior',
    'allowedRoutes' => [
        '/auth/register',
        '/auth/forgot',
        '/auth/resend',
    ],
    'redirectUri' => '/auth/login',
],
/* ... */

Then create a "components" folder in your root project and create a "components\\AccessBehavior.php" file with the following code:

<?php

namespace app\components;

use Yii;
use yii\base\Behavior;
use yii\console\Controller;
use yii\helpers\Url;

class AccessBehavior extends Behavior
{
    protected $redirectUri;
    protected $allowedRoutes = [];
    protected $allowedUrls = [];

    public function setRedirectUri($uri)
    {
        $this->redirectUri = $uri;
    }    
    public function setAllowedRoutes(array $routes)
    {
        if (count($routes)) {
            foreach ($routes as $route) {
                $this->allowedUrls[] = Url::to($route);
            }
        }
        $this->allowedRoutes = $routes;
    }
    public function init()
    {
        if (empty($this->redirectUri)) {
            $this->redirectUri = Yii::$app->getUser()->loginUrl;
        }
    }   
    private function removeParams()
    {
        //enabled pretty url
        if (strpos(Yii::$app->getRequest()->url, "?") === false) 
        {
            $requestUrl = explode('/', Yii::$app->getRequest()->url);
            $params = array_values(Yii::$app->getRequest()->queryParams);
            $result = implode('/', array_diff($requestUrl, $params));
        } 
        else 
        {//not enabled pretty url
            $result = explode("?", \Yii::$app->getRequest()->url);
        }
        return $result;
    }    
    public function events()
    {
        return [Controller::EVENT_BEFORE_ACTION => 'beforeAction'];
    }

    public function beforeAction()
    {
        $requestUrl = $this->removeParams();
        if (Yii::$app->user->isGuest)
        {
            if ($requestUrl !== Url::to($this->redirectUri) && !in_array($requestUrl, $this->allowedUrls))
            {
                Yii::$app->getResponse()->redirect($this->redirectUri)->send();  
                exit(0);
            }
        }
    }
}

This code simply checks if user is logged and checks the route requested. If guest user is accessing to allowed routes (you can add allowed routes in the config) does nothing, else redirects user to the login page :) In the code above, I set the dektrium prefix route as "auth". Of course in the allowed route, you have to set the route you actually use to make the user register, confirm, change password..

Haven't tested it but it should work.

'denyCallback'=>function() {
          if($this->action->id == 'forgot')
                return Yii::$app->response->redirect(['whatever/whatever']);
          else
                return Yii::$app->response->redirect(['user/login']);
},...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM