Restrict users to only their records

I touched upon this once before in my question Recognize the User

but wanted to see if I understood properly. This got put on hold and now I am back on the subject.

So the idea is to restrict normal users to only be able to see/access/edit their own entries, but admins can see/access/edit them all.

So I need to add a column to my tables to indicate who created the record.

Then do I edit the search model so it filters by user if it is a normal user, and doesn’t filter if it is an admin user.

How do I ensure someone doesn’t try to directly access a record (bypass the gridview and directly enter a URL with a different record ID)?

Thank you for your advice on this.

I’m working through Security: Authorization | The Definitive Guide to Yii 2.0 | Yii PHP Framework hopefully it will get me where I need to go. I’ll post back.

You may want to look at this thread: Dynamic yii\db\ActiveRecord::find()
May have the solution to your problem.

I still haven’t managed to get this functional.

I was trying

                    [
                        'allow' => true,
                        'actions' => ['index'],
                        'roles' => ['User'],
                        'roleParams' => function () {
                            return ['TicketId' => Tickets::find()
                                ->where(['=', 'UserId', Yii::$app->user->getId()])
                                ->all()];
                        }
                    ],

where I thought I could restrict the tickets returned, used, in the index data provider. But then I also need to have rules in place for view, update, delete, so the user can’t access others tickets if he tries to edit the URL directly.

Is the Controller rule the best place for this? If so, what am I doing wrong? If not, what would you recommend?

Thank you.

You can add condition to dataProvider query to load specific user records only. For other actions with single model you can add condition to findModel function for current user.

2 Likes

I was making my life much more complicated then it ever needed to be. I’ve updated the dataprovider and findmodel and everything is working perfectly.

I was stuck on thinking this was RBAC related, but was much more straightforward. Thank you.

It can be done by RBAC as well with customization but depends on use case, for multi level access we need RBAC but for 1 or 2 level access we can handle it by query.

1 Like