Multiple users roles loopback

前端 未结 1 1065
一生所求
一生所求 2021-01-26 05:57

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 w

相关标签:
1条回答
  • 2021-01-26 06:25

    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.

    0 讨论(0)
提交回复
热议问题