Go [[step_3_-_install_amnah_yii2_user|Back]]

*How do I check user permissions?*\\
This package contains a custom permissions system. Every user has a role, and that role has permissions in the form of database columns. It should follow the format: ''can_{permission name}''.\\

For example, the role table has a column named ''can_admin'' by default. To check if the user can perform admin actions:
<code php>
if (!Yii::$app->user->can("admin")) {
    throw new \yii\web\HttpException(403, 'You are not allowed to perform this action.');
}
// --- or ----
$user = User::findOne(1);
if ($user->can("admin")) {
    // do something
};
</code>

For the basic template, modify the ''views/layout/main.php'' ''Nav::widget'' to put a different link for the admin user and the guest user\\
<code php>
            (Yii::$app->user->can("admin")!= null) ?            
                ['label' => 'User', 'url' => ['/user']] : 
                ['label' => 'User', 'url' => ['/user/account']],
            Yii::$app->user->isGuest ?
                ['label' => 'Login', 'url' => ['/user/login']] : // or ['/user/login-email']
                ['label' => 'Logout (' . Yii::$app->user->displayName . ')',
                'url' => ['/user/logout'],
                'linkOptions' => ['data-method' => 'post']]
</code>

This does not prohibit the quest from going straight to the ''user'' page and executing the create, update and delete functions. We need to target this in the ''/controllers/GuitarsController.php'' file.\\
In the ''actionCreate()'', ''actionUpdate($id)'' and the ''actionDelete($id)'' sections, put this
<code php>
        if (!Yii::$app->user->can("admin")) {
            throw new \yii\web\HttpException(403, 'You are not allowed to perform this action.');
        } else {
        .....
        }
</code>
I modified it to redirect to the ''Login'' page.
<code php>
        if (!Yii::$app->user->can("admin")) {
            $this->redirect(Yii::$app->urlManager->createUrl(['/user/login']));
        } else {
</code>

[[Step 5 - Further permissions]]\\

Back to [[yii|Yii Main Index]]