if (\Yii::$app->user->can('createPost')) {
// create post
}
if the user doesn’t have permission, shouldn’t this “can” function automatically throw a ForbiddenHttpException or something like that? Or am I using this function wrong? Or do I have to manually put this:
else {
throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
}
into all actions of all controllers?
Interesting, that if I’m right by ACF this functionality is already included.
To throw automatically a forbidden or similar you can use the behaviors section (which allow callbacks to check if allowed or not, or, if using rbac you can put the required permissions in [ ] directly).
For other cases this code worked in yii 1, dont know if work work anymore:
throw new CHttpException(404,'The specified post cannot be found.'); // as example from stackoverflow
As I see, we have to define always an else statement, where we throw a new e.g. ForbiddenHttpException. But I think, it should be already included somehow in this "user->can()" function, or am I wrong?
I don’t think so. Yii\web\User::can() can be used for several different purposes e.g.for displaying view parts like menu items or form fields conditionally depending on user’s permissions.
Also , most developers probably don’t call this method directly in their controller actions but delegate the job to yii\filters\AccessControl or a custom filter class.
Yeah, can be that I’m wrong, but for me, it seems the simplest to include this can() functionality right at the action, and I think it should only check if the user is authorised or not. If yes, he can get what he wants, if not he gets a ForbiddenHttpException. What you say, seems to me a little bit more complicated yet, but maybe you are right and in long terms it’s better. As I said I’m only a beginner yet so it would be absolutely no surprise if I would be wrong.