0
votes

I have list of more than 5k users in my another DB, and I want to migrate all the users in loopback DB, there are many duplicate users exists so that I am checking if user exists then I am updating a user otherwise I am creating new one. I have written a script for that. Its working fine but after updates first user, loopback starts throwing an error 401 Unauthorized if I execute GET user detail API. Even I have allowed Unauthenticated user to access update, create property with ACL, but its not working with this as well.

I have extended the User model.

Can anyone please throw some light? Help will be appeciated!

Thanks

1

1 Answers

1
votes

LoopBack's default ACLs are more specific than the ones you are defining, so that yours don't have effect at the end. The @authenticated and @unauthenticated ALLOW rules doesn't have precedence over DENY all rules. But custom roles do, and using a custom ADMINISTRATOR role is the right way in the framework.

  1. You need to create a Role for an specific user.
  2. Map that role to the user using the RoleMapping model.

Steps 1 and 2 can be done with this boot script (ex: App/server/boot/create-admin-user.js):

module.exports = function(app) {

  var User = app.models.ExtendedUser;
  var Role = app.models.Role;
  var RoleMapping = app.models.RoleMapping;

  User.findOrCreate({ where: { username: 'admin', email: '[email protected]' } },
  {
    username: 'admin', 
    email: '[email protected]', 
    password: 'admin123'
  }, 
  function(err, user) {
      if (err) return console.log(err);
      // Create the admin role
      Role.findOrCreate({where: { name: 'ADMINISTRATOR' }},
        { name: 'ADMINISTRATOR' }, 
        function(err, role) {
          if (err) return debug(err);
          console.log("Role Created: " + role.name);     
          // Assign admin role
          RoleMapping.findOrCreate({where: { roleId: role.id, principalId: user.id }},
            { roleId: role.id, principalId: user.id, principalType: RoleMapping.USER }, 
            function(err, roleMapping) {
              if (err) return console.log(err);
              console.log("ADMINISTRATOR Role assigned to " + user.username);
            });        
        });
    });
};
  1. Create an ACL entry in your ExtendedUser model to ALLOW the ROLE ADMINISTRATOR to WRITE:

```

{
  "name": "ExtendedUser",
  "base": "User",
  /* ... */
  "acls": [
    {
      "accessType": "READ",
      "principalType": "ROLE",
      "principalId": "$authenticated",
      "permission": "ALLOW"
    },
    {
      "accessType": "WRITE",
      "principalType": "ROLE",
      "principalId": "ADMINISTRATOR",
      "permission": "ALLOW"
    }
  ]
}