@mac
To implement authorization in Yii, you need to follow these steps:
'components' => [ ... 'user' => [ 'identityClass' => 'appmodelsUser', 'enableAutoLogin' => true, ], 'authManager' => [ 'class' => 'yii bacDbManager', ], ... ],
use Yii; use yiiwebController;
class SiteController extends Controller { public function actionIndex() { $user = Yii::$app->user->identity;
1 2 3 4 5 6 7 8 9 |
// Check if the user has the "admin" role if (Yii::$app->authManager->checkAccess($user->id, 'admin')) { echo "You have admin rights!"; } // Check if the user has the "updatePost" permission if (Yii::$app->authManager->checkAccess($user->id, 'updatePost')) { echo "You can update posts!"; } } |
}
use yiiiltersAccessControl;
class PostController extends Controller { public function behaviors() { return [ 'access' => [ 'class' => AccessControl::className(), 'rules' => [ [ 'actions' => ['create', 'update'], 'allow' => true, 'roles' => ['editor'], ], [ 'actions' => ['delete'], 'allow' => true, 'roles' => ['admin'], ], ], ], ]; } }
This code restricts the "create" and "update" actions to users with the "editor" role, and the "delete" action to users with the "admin" role.
use Yii;
if (Yii::$app->user->can('updatePost', ['post' => $post])) { echo Html::a('Update Post', ['post/update', 'id' => $post->id]); }
This code checks if the current user has the "updatePost" permission for a specific post and displays the "Update Post" link accordingly.