I have yii2 advance template with RBAC migration applied. I was trying to learn RBAC and followed the Docs 2.0.
I have logged in using database, but the front-end and back-end both get logged in with any account. I have made 2 RBAC roles (admin, user), but can't understand or find how to
restrict back-end to login non-admin user-role.
The following is the code for roles. and database entries:
namespace console\controllers;
use Yii;
use yii\console\Controller;
class RbacController extends Controller
{
public function actionInit()
{
$auth = Yii::$app->authManager;
// add "admin" role
$admin = $auth->createRole('admin');
$auth->add($admin);
// add "user" role
$user = $auth->createRole('user');
$auth->add($user);
$auth->assign($admin, 1);
}
}
User Table:
admin admin@gmail.com 20 10 1421197319 1421197319
user user@gmail.com 10 10 1421198124 1421198124
Current rules:
'rules' => [
[
'actions' => ['login', 'error'],
'allow' => true,
],
[
'actions' => ['logout', 'index'],
'allow' => true,
'roles' => ['@'],
],
Solved - Note: The solution is not exactly RBAC but ACF.
After searching and consulting, I found the solution at This yii2 viki.
I was unclear of RBAC behavior, in that I thought it won't let a role perform specific task before some action(login, submit etc).
Actually, RBAC will let you do whatever you try, and afterwards checks for permission and block if not permitted.
Example
Backend Rules:
The
matchCallback
on True allows the actions to be performed and on False denies the action.isAdmin
is a getter function that needs to be defined inUser
model.I have posted the complete working code of model in This yii2 viki's comments.
You both first login user and then checking his role, there is no need for that. Your LoginForm model has
getUser()
method, find it after callingload()
andvalidate()
, and check role withauthManager
. Smth like this:You also don't want to
validate()
LoginForm twice, so add$runValidation
param to thelogin()
method.You should add behavior to you controller, like this:
or this EDIT: (rule so that anyone is allowed to access login but only admin is allowed to be logged in and access index page):
I have achieved this functionality by changing backend login action. here is my code, i don't know, it is a perfect solution or not, but it is working for me.