i want to create an application where only admin can perform all the crud operations but other users can only create and update posts. I did find tutorials based on rbac but only for advanced template but i am using the basic template. I also followed the yii2 guide but i did not understood it very well like executing ./yii rbac/init console command. How do i do it?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
first of all create a Helper Class called PermissionHelpers in your model folder:
namespace app\models;
use Yii;
class PermissionHelpers {
public static function requireAdmin() {
if(Yii::$app->user->identity->role == 100)
{
return true;
}
else return false;
}
}
Then update your controller with:
// at top with your other use
use yii\filters\AccessControl;
use app\models\PermissionHelpers;
// first function inside the class
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'only' => ['privateaction1', 'privateaction2'],
'rules' => [
[
'actions' => ['privateaction1', 'privateaction2'],
'allow' => true,
'roles' => ['@'],
'matchCallback' => function($rule, $action) {
return PermissionHelpers::requireAdmin();
}
],
],
],
}
And now you need to update yourself in the DB with role = 100, and you're set.
I'm using Advanced template myself, so there might be small changes to the namespaces and such. But it should be fairly easy to figure out. Good luck!