Search code examples
http-redirectyii2rbac

yii2 errorhandler: Redirect to frontend/site/error


When implementing the access control on the backend, I would like to redirect disallowed users to the frontend error page (instead of the backend error page).

The backend controller:

'access' => [
    'class' => AccessControl::className(),
    'rules' => [
        [
            'allow' => true,
            'roles' => ['admin'],
        ],

backend/config/main.php

'components'=>[
        'errorHandler' => [
            'errorAction' => 'site/error',
        ],

How do I redirect non-admin users to frontend/site/error? Everything I try results in an error.

Many thanks


Solution

  • if I understand correctly you want the frontend user if logged in and tries to access the backend's modules or controllers he/she should not be allowed to do so, This was a Session Sharing bug reported earlier, and this was added into Yii 2.0.9 milestones and is already integrated since 2016.

    If you are working on an existing Yii2 project with an older version and haven't migrated or upgraded to the latest version, I would suggest you do the following settings

    /backend/config/main.php:

    return [
        'id' => 'app-backend',
        // ...
        'components' => [
            'user' => [
                'identityClass' => 'common\models\Admin',
                'enableAutoLogin' => true,
                'identityCookie' => [
                    'name' => '_backendUser', // unique for backend
                ]
            ],
            'session' => [
                'name' => 'PHPBACKSESSID',
                'savePath' => sys_get_temp_dir(),
            ],
    // ..
    ];
    

    /frontend/config/main.php:

    return [
        'id' => 'app-frontend',
        'components' => [
            'user' => [
                'identityClass' => 'common\models\User',
                'enableAutoLogin' => true,
                'identityCookie' => [
                    'name' => '_frontendUser',
                ]
            ],
            'session' => [
                'name' => 'PHPFRONTSESSID',
                'savePath' => sys_get_temp_dir(),
            ],
        ///...
        ]
    ];