问题
I am trying to make an application using Loopback as my back-end. I already used loopback before, but right now I want to do something that I never done before.
What I want is simple, I will have 3 types of users, administrator, servicer and default. But, I need to restrict the access controls for each type of user; the administrator can request all my routes, but de default user for example can only request some routes that I will specify. The ACL part I know how to do, but I can't find anything explaining how to make each type of user a role and make it work.
Anyone can post here an example with at least two users and roles?
回答1:
The first step is to persist the 2 new roles into your database, "administrator" and "servicer". You can either do this step manually or create a script you can reuse:
// commands/add_roles.js
let app = require('../server/server')
function createRole(name, description, done) {
app.models.Role.findOrCreate(
{where: {name: name}},
{name, description},
err => {
// TODO handle error
done && done()
}
)
}
createRole('administrator', 'Administrators have more control on the data', () => {
createRole('servicer', 'servicer description', process.exit)
})
Then, you associate a role to a user. Execute the code below whenever you desire, depending on your application.
app.models.Role.findOne({where: {name: 'administrator'}}, (err, role) => {
// TODO handle error
app.models.RoleMapping.findOrCreate({where: {principalId: user.id}}, {
roleId: role.id,
principalType: RoleMapping.USER,
principalId: user.id
}, function (err) {
// TODO handle error
// if no errors, user has now the role administrator
})
})
You can now use the roles "administrator" and "servicer" in your models' ACLs.
来源:https://stackoverflow.com/questions/51697014/multiple-users-roles-loopback