Is there an easy way to restrict a controller action to the owner/creator of the post without using full blown RBAC?
Right now I'm doing this for every controller:
public function actionUpdate( $id ) {
$model = $this->findModel( $id );
if ( $model->user_id != Yii::$app->user->identity->id ) {
throw new NotFoundHttpException( 'The requested page does not exist.' );
}
}
But I think there must be a better way to restrict certain controllers to the users who created the $model
thats being edited.
We can use
for restricting controller action instead of RBAC. This below code will give access to the actionUpdate if it is only pass the denyCallback.
For your reference https://github.com/yiisoft/yii2/blob/master/docs/guide/security-authorization.md
1) The recommended way is to use RBAC and rules. It's covered well in official docs in according dedicated section.
Example of rule that checks if author id matches current user id passed via params:
Then you need to tie it with existing permission (can be done in migration or with extensions):
Then you can check if you user can update post like this:
Also note that in case you found model first and user has no access to edit it, logically it's better to throw 403 Forbidden exception rather than 404, since it's found, but not allowed for editing.
Don't forget to include rule like that in
AccessControl
behavior:It means that
update
action of this controller can be only accessed by authorized users excluding guests.2) If for some reason you don't want to use RBAC, you can use your approach:
To improve this you can abstract from this check by moving this logic to helper method:
Then call it like that:
It's just an example, method doesn't have to be static, you can construct instance using
$model
.You can just directly create method in
Post
model, but it's better to not pollute model with such logic.3) Another alternative that I can advise is to restrict scope initially to current user when finding model:
This can be improved for site administrators:
Then you only write:
That way in both cases (model not found and not allowed for editing by current user), 404 Not Found exception will be raised. From other side, nothing is wrong with that, because technically for this user this model does not exist (since he is not author of it).