Return specific user-created data

I created a crud and am using the webvimark / user-management extension to manage user creation and permissions. I would like to display only the data created by the users that is currently logged in, that is, that each user only has access to the data entered by himself. I thank you all.

Hi @rafawrm,

You need to use RBAC (Role Based Access Control) in order to do that.

Guide > Security > Autorization > RBAC

Specifically Using Rules section describes how to restrict access based on the ownership of the data.

And for listing data, you can set a filter using some attribute that represents the owner of the data. This won’t require RBAC.

I’m a beginner and would like to know if there are any examples (template or extension) of a CRUD implemented using these rules. Thank you very much for your attention.

I don’t know what “webvimark/user-management” extension does, so I can’t give you a working example using it. So I can only give you some general examples and hints.

    public function actionIndex()
    {
        $searchModel = new ItemSearch();
        if (!Yii::$app->user->can('item.manage')) {
            $searchModel->created_by = Yii::$app->user->id;
        }
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

In the above, we set the user’s id to the created_by attribute of the search model, if the user has no “item.manage” permission. Then a user with “item.manage” permission will see all the items, while an ordinary user can see only the items created by himself, because “search” method will filter the items by “created_by” attribute.

And this is a typical actionView:

    public function actionView($id)
    {
        $model = $this->findModel($id);

        if (!Yii::$app->user->can('item.view', ['id' => $model->created_by] )) {
            throw new ForbiddenHttpException('You have no permission to view this item.');
        }

        return $this->render('view', [
            'model' => $model,
        ]);
    }

Here we are checking “item.view” permission. If the user is a manager, then he will be able to view all the items but an ordinary user may see only the items created by himself. Behind this simple code, you have to have established an RBAC structure and rules that define the authorization policy.

Please read the RBAC section of the guide. Without understanding RBAC system, you may not be able to use webvimark/user-management extension to its full extent.