I’ve spent about a day working on adding permissions to the model. Here are intermediary conclusions:
- We need to pass user session to model’s permission checker method
is_allowed()in order to know session user roles and other data (e.g. company ID).
- We need to check permissions and cache results at the same time we initialize model (or load existing model) so that our sync methods can stay sync (because checking permissions can be asynchronous), methods such as
- Not all models are created during request. In my application, they may be created as a result of Socket.io events, where user is the application itself. Therefore we can’t and don’t have to check permissions unless we have a user session object.
Thus, looks like in the current setup we need to pass
req to model constructor as an option, and if it is not passed, we assume that the model is created by the application, so we do not check permissions.
Second take is that in order to check permissions, all permission checkers should be either plain synchronous functions, or promises, which we can run in async manner using
map() method of an async library, but they can not be a mix of both.
Tomorrow I will refactor generic model constructor to accept options and to map supplied permissions checkers at model initialization.