Asked  7 Months ago    Answers:  5   Viewed   57 times

In my sitecontroller I write like this

    'access' => [
        'class' => AccessControl::className(),
        'rules' => [
            [
                'actions' => ['login', 'error'],
                'allow' => true,
            ],
            [
                'actions' => ['logout', 'index' ,'call-back'], // add all actions to take guest to login page
                'allow' => true,
                'roles' => ['@'],
            ],
        ],
    ],

so If I go to index or call-back action,I'll redirected to login page. but I have to do it for all action to each controller. Could you tell me the best way to do it?

 Answers

55

Place this rule in the beginning of the rules section:

[
    'allow' => true,
    'roles' => ['@'],
],

Omitting the actions means all actions.

So your AccessControl config will be like this:

public function behaviors()
{
    return [
        'access' => [
            'class' => AccessControl::className(),
            'rules' => [
                [
                    'allow' => true,
                    'roles' => ['@'],
                ],

                // ...
            ],
        ],
    ];
}

Keep in mind that rules are applied in order they are declared.

To do it globally without inheritance, add the as beforeRequest array below (not inside!) the components declaration in your application config:

'components' => [ ... ],
'as beforeRequest' => [
    'class' => 'yiifiltersAccessControl',
    'rules' => [
        [
            'allow' => true,
            'actions' => ['login'],
        ],
        [
            'allow' => true,
            'roles' => ['@'],
        ],
    ],
    'denyCallback' => function () {
        return Yii::$app->response->redirect(['site/login']);
    },
],

This code will run before each request and block all actions except login for guests.

Make sure that there is no login action in other controllers than SiteController. If there are (and for example they are for different purposes), block them explicitly in according controllers. But it's pretty rare case.

Wednesday, March 31, 2021
 
Hugo
answered 7 Months ago
22

While other topics here on SO offer a chincy hack solution, or to simply fetch it through Yii::$app->user->identity, I am going to show you how to do it properly. You can bend Yii2 to your will, by virtually extending everything!

I normally work in the "advanced" app, but I am going to just use the "basic" app as a reference for everyone. I assume those who are using the "advanced" app know the differences and understand namespaces.

Namespace Crash Course: In basic, you have namespace apppathto. This is where the file is located. For example, you have ContactForm.php located in the app root models directory, so it's namespace is appmodels. In advanced, you have multiple apps (frontend & backend), so the app root is different, thus you have frontend as one app root, and backend as another. The models directory in the advanced app is at "frontend/models" and it's namespace is frontendmodels. -- So anywhere you see "app" in the namespace, you can replace it with frontend or backend for the "advanced" template.


Solution

First, we need to modify our app's config file to override the default User component's class. I will leave out anything not related, so you keep your identityClass defined, I just am not showing it. We are simply adding to, not replacing, the config. Also, where I show frontend/something, the same can be done for backend/something. I just am not going to repeat both over and over again...

Basic (config/web.php) -or- Advanced (frontend/config/main.php)

'components' => [
    'user' => [
        'class' => 'appcomponentsUser', // extend User component
    ],
],

Remember: If you are using the advanced template, replace app with frontend or backend!

I also want to point out, that you will need to create the "components" directory if you haven't done so. This is where many people add their custom Classes. Whether it be your own helper class, or extending a base Yii component (such as extending yiiwebController).

Create a new file in your components directory named User.php. In that file, place the following code:

<?php
namespace appcomponents;

use Yii;

/**
 * Extended yiiwebUser
 *
 * This allows us to do "Yii::$app->user->something" by adding getters
 * like "public function getSomething()"
 *
 * So we can use variables and functions directly in `Yii::$app->user`
 */
class User extends yiiwebUser
{
    public function getUsername()
    {
        return Yii::$app->user->identity->username;
    }

    public function getName()
    {
        return Yii::$app->user->identity->name;
    }
}

Note: username and name must be valid column names in your database's user table!

So now we can use this in our controller, view, anywhere.. Let's test it out. In views/site/index.php, add this to the bottom of the page:

<?= Yii::$app->user->name ?>
<?= Yii::$app->user->username ?>

If all is good, and you have values in the user table for name and username, they should be printed on to the page :)

Wednesday, March 31, 2021
 
ramdemon
answered 7 Months ago
39

Console application does not have Yii->$app->user. So, you need to configure user component in configconsole.php.

like as,

configconsole.php

 'components' => [
 .........
 ......
        'user' => [
            'class' => 'yiiwebUser',
            'identityClass' => 'appmodelsUser',
            //'enableAutoLogin' => true,
        ],
        'session' => [ // for use session in console application
            'class' => 'yiiwebSession'
        ],
 .......
]

More info about your problem see this : Link

OR

Visit following link : Yii2 isGuest giving exception in console application

Note : There's no session in console application.

Saturday, May 29, 2021
 
ChronoFish
answered 5 Months ago
99

try this:

    private static final String PACKAGE_PREFIX =
            VpnManager.class.getPackage().getName() + ".";
    private static final String ACTION_VPN_SETTINGS =
            PACKAGE_PREFIX + "SETTINGS";
    Intent intent = new Intent(ACTION_VPN_SETTINGS);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    mContext.startActivity(intent);
Saturday, August 14, 2021
 
Kumar112
answered 3 Months ago
32

You need to add below code in common/main.php after components part.

'as beforeRequest' => [  //if guest user access site so, redirect to login page.
        'class' => 'yiifiltersAccessControl',
        'rules' => [
            [
                'actions' => ['login', 'error'],
                'allow' => true,
            ],
            [
                'allow' => true,
                'roles' => ['@'],
            ],
        ],
    ],
Sunday, August 29, 2021
 
Addev
answered 2 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :