mostafamaklad / laravel-permission-mongodb

Associate users with roles and permissions using Laravel and MongoDB
https://maklad.dev
MIT License
112 stars 66 forks source link

Do not throw PermissionDoesNotExist on $role->hasPermissionTo('permission_not_in_db') #125

Closed Pilskalns closed 3 years ago

Pilskalns commented 3 years ago

Is your feature request related to a problem? Please describe. I am making an app where permissions are a bit loose - some permissions might appear in the code before they are assigned and saved to roles in the DB. When roles are edited, then I do handle the missing permissions with Permission::firstOrCreate.

The exception is thrown from a nested call in the Permission model function findByName by where it makes sense. The context for where it is called from is $role->hasPermissionTo("permission_not_in_db") which is supposed to return bool. (screenshot below)

Describe the solution you'd like As already in the documentation in the code the hasPermissionTo function should strictly return a Boolean response - if the permission does not exist, then the $role does not have it. If a backwards-compatible scenario is important, maybe could add a second parameter $failSilently = false. When set to true, it would not throw any exception and return strictly true or false.

Describe alternatives you've considered Pre-checks that would be bad for performance, making odd queries when not needed. I'm kinda new to Laravel, could not find a way how to suppress this error and make it fail silently.

I am using the hasPermissionTo in the blade, so anything multiline is hard to manage.

Additional context Add any other context or screenshots about the feature request here. image

mostafamaklad commented 3 years ago

Are you using the same guard?

Pilskalns commented 3 years ago

Yes, the guard is web. I realised that this context is a kind of edge case when administering the roles vs permissions. In any other place, one should use can(permission)/cannot(permission). Yet still, it would be nice if this could not throw an exception but return boolean.

Pilskalns commented 3 years ago

For clarity, I mean the following function: https://github.com/mostafamaklad/laravel-permission-mongodb/blob/master/src/Models/Role.php#L140

mostafamaklad commented 3 years ago

@Pilskalns Could you please check if calendar_read permission exists on DB (permissions collection)

Pilskalns commented 3 years ago

@mostafamaklad yes, it does not exists in DB. That is the point of the ticket - not throw an exception but return false if permission being checked does not exist in DB.

mostafamaklad commented 3 years ago

the point of threw an exception to differentiate between if the user doesn't have the permission or the permission doesn't exist at all if you want to avoid the exception you can override it using this article Laravel Errors