Skip to content

Seems there is no way to access Roles from User Object/API #1441

Closed

Description

@valllabh

It seems there is no way to access User Roles in user query.

I tried to create relation roles in User

"relations": {
    "roles": {
      "type": "hasAndBelongsToMany",
      "model": "Role",
      "through": "RoleMapping",
      "polymorphic": "principal"
    }
}

adding roles to user userObj.roles.add(roleObj) works and create following entry in RoleMapping

{
    "_id" : ObjectId("5576deca062655136bdb154c"),
    "principalType" : "user",
    "principalId" : "5576dec9062655136bdb154a",
    "roleId" : ObjectId("5576deca062655136bdb154b")
}

but when I try to query in user/{id}/roles output comes blank/empty array.
I also tried updating "principalType" : "user" to "principalType" : "USER" but nothing works.

Activity

  1. mneil commented on Jul 7, 2015

    @mneil

    I just ran into this issue as well. Roles are always empty when using include on users with Mongo DB. Might be related to #274.

  2. faridnsh commented on Aug 13, 2015

    @faridnsh
    Contributor

    I followed this gist and it works perfectly for me.

  3. superkhau commented on Aug 13, 2015

    @superkhau
    Contributor

    Can you provide a link to a test project on Github? See https://github.com/strongloop/loopback/wiki/Issues#bug-report

  4. valllabh commented on Aug 18, 2015

    @valllabh
    Author

    @superkhau is this for me?

  5. superkhau commented on Aug 18, 2015

    @superkhau
    Contributor

    @valllabh Yes please, I would like to try to reproduce the issue on my end to confirm the bug.

  6. valllabh commented on Aug 19, 2015

    @valllabh
    Author

    @superkhau alright give me some time to extract and prepare test project.

  7. superkhau commented on Aug 19, 2015

    @superkhau
    Contributor

    Thanks.

  8. khashayar commented on Oct 23, 2015

    @khashayar

    It only happens with MongoDB as a datasource.

    @superkhau

    1. Create a custom 'user' model based on 'User' model
    2. Add following relation to it:
      "relations": {
        "roles": {
          "type": "hasMany",
          "model": "Role",
          "foreignKey": "principalId",
          "through": "RoleMapping"
        }
      }
    1. Create a boot script with following code
    module.exports = function(server) {
      var User = server.models.user;
      var Role = server.models.Role;
      var RoleMapping = server.models.RoleMapping;
    
      var users = [
        {email: 'john@example.com', password: 'opensesame'},
        {email: 'jane@example.com', password: 'opensesame'},
        {email: 'bob@example.com', password: 'opensesame'}
      ];
    
      User.create(users, function(err, users) {
          if (err) {return console.log(err);}
    
          //create the admin role
          Role.create({
            name: 'admin'
          }, function(err, role) {
            if (err) {console.log(err);}
    
            //make bob an admin
            role.principals.create({
              principalType: RoleMapping.USER,
              principalId: users[0].id
            }, function(err, principal) {
              console.log(err, principal);
            });
          });
        });
    };

    Now check the [GET} /users result with {include: "roles"}, the roles array for first user is empty!

    Adding the following lines inside the boot script would solve the problem:

    RoleMapping.belongsTo(User);
    User.hasMany(RoleMapping, {foreignKey: 'principalId'});
    Role.hasMany(User, {through: RoleMapping, foreignKey: 'roleId'});
  9. faridnsh commented on Oct 23, 2015

    @faridnsh
    Contributor

    @khashayar that happens because you're using th e built in User model which doesn't have the relationships defined for it and not your custom built user model I believe.

  10. khashayar commented on Oct 23, 2015

    @khashayar

    @alFReD-NSH Actually I'm using my custom user model. It was a typo once I entered the sample code here on Github. I updated the actual sample code.

  11. AurelieV commented on Jan 30, 2016

    @AurelieV

    OK @jannyHou let's continue the discussion here.
    I have try this on my production server which have an other mongodb version, and still not working

    db version v3.2.1
    node version: v4.2.4
    system: Ubuntu 15.04

  12. 38 remaining items

  13. AurelieV commented on Apr 7, 2016

    @AurelieV

    @jannyHou but if one time I run it with the workaround, all the time after, even without workaround; it works

  14. AurelieV commented on Apr 7, 2016

    @AurelieV

    @jannyHou And this is because with the workaround, a new RoleMapping is created in the database, with an ObjectId rather than a string for principalID. When you see RoleMapping, two objects exist, and the role is retrieved by the one with an objectId as principalId

  15. jannyHou commented on Apr 7, 2016

    @jannyHou
    Contributor

    @AurelieV nice it makes sense! thank you

  16. younes0x53 commented on Jun 17, 2016

    @younes0x53

    Hi,
    Any updates on this issue ? the related #128 issue on loopback-connector-mongodb was fixed but the bug remains.
    Thank you.

  17. sschimmel commented on Aug 19, 2016

    @sschimmel

    Even with the workaround and a fresh database I can't get this to work. Looking at the security debug output it seems that no RoleMapping can be found.

    There is a role and a user present and the role mapping record contains the corrects id's as an Object() instead of as string.

    Debug output:

    2016-08-19 12:21:29.555   loopback:security:access-context ---AccessContext--- +0ms
    2016-08-19 12:21:29.555   loopback:security:access-context principals: +0ms
    2016-08-19 12:21:29.556   loopback:security:access-context principal: {"type":"USER","id":"123456789a00000000000000"} +1ms
    2016-08-19 12:21:29.556   loopback:security:access-context modelName InviteRequest +0ms
    2016-08-19 12:21:29.557   loopback:security:access-context modelId undefined +1ms
    2016-08-19 12:21:29.557   loopback:security:access-context property find +0ms
    2016-08-19 12:21:29.557   loopback:security:access-context method find +0ms
    2016-08-19 12:21:29.557   loopback:security:access-context accessType READ +0ms
    2016-08-19 12:21:29.557   loopback:security:access-context accessToken: +0ms
    2016-08-19 12:21:29.558   loopback:security:access-context   id "V9ya2rC9u3vmTknJ5ZrCIl8puFNTQWCDMJo9VZA9WjzXKT1tMmunpY5zziorLFhG" +1ms
    2016-08-19 12:21:29.558   loopback:security:access-context   ttl 1209600 +0ms
    2016-08-19 12:21:29.558   loopback:security:access-context getUserId() 123456789a00000000000000 +0ms
    2016-08-19 12:21:29.558   loopback:security:access-context isAuthenticated() true +0ms
    2016-08-19 12:21:29.558   loopback:security:role Custom resolver found for role $everyone +0ms
    2016-08-19 12:21:29.558   loopback:security:role isInRole(): admin +0ms
    2016-08-19 12:21:29.558   loopback:security:access-context ---AccessContext--- +0ms
    2016-08-19 12:21:29.558   loopback:security:access-context principals: +0ms
    2016-08-19 12:21:29.558   loopback:security:access-context principal: {"type":"USER","id":"123456789a00000000000000"} +0ms
    2016-08-19 12:21:29.559   loopback:security:access-context modelName InviteRequest +0ms
    2016-08-19 12:21:29.559   loopback:security:access-context modelId undefined +1ms
    2016-08-19 12:21:29.559   loopback:security:access-context property find +0ms
    2016-08-19 12:21:29.559   loopback:security:access-context method find +0ms
    2016-08-19 12:21:29.559   loopback:security:access-context accessType READ +0ms
    2016-08-19 12:21:29.559   loopback:security:access-context accessToken: +0ms
    2016-08-19 12:21:29.559   loopback:security:access-context   id "V9ya2rC9u3vmTknJ5ZrCIl8puFNTQWCDMJo9VZA9WjzXKT1tMmunpY5zziorLFhG" +0ms
    2016-08-19 12:21:29.560   loopback:security:access-context   ttl 1209600 +1ms
    2016-08-19 12:21:29.560   loopback:security:access-context getUserId() 123456789a00000000000000 +0ms
    2016-08-19 12:21:29.560   loopback:security:access-context isAuthenticated() true +0ms
    2016-08-19 12:21:29.562   loopback:security:role Role found: {"id":"57b6d236fe6478355e180818","name":"admin","created":"2016-08-19T09:32:37.599Z","modified":"2016-08-19T09:32:37.599Z"} +2ms
    2016-08-19 12:21:29.564   loopback:security:role Role mapping found: null +2ms
    2016-08-19 12:21:29.564   loopback:security:role isInRole() returns: false +0ms
    

    User database record:

    {
        "_id" : ObjectId("123456789a00000000000000"),
        "name" : "admin",
        "locale" : "nl-NL",
        "emailVerified" : true
    }

    Roles:

    {
        "_id" : ObjectId("57b6d236fe6478355e180818"),
        "name" : "admin",
        "created" : ISODate("2016-08-19T09:32:37.599Z"),
        "modified" : ISODate("2016-08-19T09:32:37.599Z")
    }

    RoleMapping:

    {
        "_id" : ObjectId("57b6d237fe6478355e180846"),
        "principalType" : "USER",
        "principalId" : ObjectId("123456789a00000000000000"),
        "roleId" : ObjectId("57b6d236fe6478355e180818")
    }
  18. bajtos commented on Feb 17, 2017

    @bajtos
    Member

    A possible workaround is described in #3121 (comment).

  19. rashmihunt commented on Jun 29, 2017

    @rashmihunt
    Contributor

    @valllabh Are you good with the workaround suggested by @bajtos ?#3121 (comment) If yes, we like to close this item.

  20. jmereaux commented on Sep 23, 2017

    @jmereaux

    Is there a working solution for this issue now?
    I have defined a "roles" relation on my custom user model (as described by @khashayar), but when querying a user's roles, the returned array is still empty.

  21. jmereaux commented on Oct 2, 2017

    @jmereaux

    Seems like adding the following does the trick:

    • "keyThrough": "roleId" on the roles relation in the custom user model
    • "keyThrough": "principalId"on the users relation in the custom role model
  22. dmastag commented on Apr 9, 2018

    @dmastag

    This is what I eventually put on my custom User Model

    "roles": {
          "type": "hasMany",
          "model": "Role",
          "foreignKey": "principalId",
          "keyThrough": "roleId",
          "through": "RoleMapping"
        }
    
  23. stale commented on Mar 11, 2020

    @stale

    This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

  24. stale commented on Mar 26, 2020

    @stale

    This issue has been closed due to continued inactivity. Thank you for your understanding. If you believe this to be in error, please contact one of the code owners, listed in the CODEOWNERS file at the top-level of this repository.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions