What is the reason for having authorization rules in the database?
题
In my Yii application, I want my authorization hierarchy and business rules to be written in code and I want my users, roles and permissions to be stored in the database. This separates my business logic (which should be code) from the information it should use (which should be data). It appears that Yii does not support this.
In Yii you have the option of either putting your business logic into files (CPhpAuthManager) or into the database (CdbAuthManager). Either way, you are treating your business logic as data; Yii will actually retrieve your business logic as strings and then run it via an eval
, which seems like a terrible way to do this.
What is the reason for this?
How can I achieve the outcome I want?
解决方案
You can put as many logic as you want into your PHP code for your business logic. Yii supports many ways of adding this logic, eg. LoginForm.php, UserIdentity.php, SiteController.php, ... you are not limited here.
What Yii also supports is adding a snippet of logic to your RBAC. A common use case is, that you assign the two rules 'Authenticated' and 'Guest' to all users of your site by default, but with bizRules. While 'Authenticated' has a bizRule like
return !Yii::app()->user->isGuest;
'Guest' has
return Yii::app()->user->isGuest;
The outcome is, that your logged in users are not longer 'Guests' but 'Authenticated'. Another example would be edit views for user profiles, which are only editable by current user, like
return $model->id === Yii::app()->user->id;
其他提示
Why would you put anything in a database vs code?
One good reason is so that non-developers can edit it.
In our app, we allow users to manage their permissions on their own users and items.
You don't have to use yii's rbac business rules. You could allow say a few different roles and tasks, and have the rest of the auth logic in code.