Search code examples
node.jsloopbackjsstrongloop

Strongloop - add fields to returned user model


Any way to strongloop's /User/login responce can be extended by UserRoles field?

By default strongloop return user object with "firstName, lastName, email, id and userName", i also need userRoles.


Solution

  • You can create a remote hook for the built-in login method.

    in user.js

    module.exports = User => {
      User.afterRemote('login', async (ctx, usr, next) => {
        let roleMaps = await User.app.models.RoleMapping.find({ where: { principalId: usr.userId } })
        let roleIds = roleMaps.map(roleMap => { return roleMap.roleId })
        let roles = await User.app.models.Role.find({ where: { id: { inq: roleIds } } })
        usr.roles = roles
        next()
      })
    }
    

    Note: I'm using ES6 and partially ES7 (async/await), but you can easily rewrite it to ES5.

    Another option would be to create a relationship between your User and Role models and then use include filter or scopes.