loopback icon indicating copy to clipboard operation
loopback copied to clipboard

How can I get account's role in "beforeRemote"?

Open Spark-star opened this issue 12 years ago • 5 comments

I created a model Account which extend from "User", I also covered the relations with "AccessToken" like this

"accessTokens": {
      "type": "hasMany",
      "model": "AccessToken",
      "foreignKey": "accountId"
    }

My question is how can I get the account's role in "beforeRemote"?

the code like this :

Account.beforeRemote('method', function(ctx, next) { 

if( role = 'admin' ) { can update  something }
else{ only can update one property , for example: name}
next(); 
  });

How can I get the "role" ? Thanks

Spark-star avatar Oct 23 '14 07:10 Spark-star

@Spark-star you should do that using the loopback authorisation

pungoyal avatar Nov 10 '14 09:11 pungoyal

// common/models/account.js
var RoleMapping = app.loopback.RoleMapping;
Account.beforeRemote('method', function(ctx, account, next) {
    RoleMapping.findOne({
        where: { principalId: account.Id },
        include: 'role'
    }, function(err, roleMapping) {
        if (err || !roleMapping) { return next(err); }
        role = roleMapping.role().name
        if (role === 'admin') {
            \\ Do awesome
        else {
            \\ Weak sauce!
         }
        next();
    });
})

BerkeleyTrue avatar Dec 17 '14 00:12 BerkeleyTrue

Thank you so much! It's great.

bigktmbig avatar Nov 25 '15 01:11 bigktmbig

This document should help as well: https://docs.strongloop.com/display/LB/Remote+hooks

Closing this issue for now. If you still have an issue with the same subject, please feel free to leave the comment and I will re-open the issue. Thanks.

loay avatar Apr 07 '16 01:04 loay

Now you can use this: ctx.args.options.authorizedRoles

Remember to apply "strictObjectIDCoercion" option with true value to the following models in model-config.json:

  • Role

  • ACL

  • RoleMapping

LinhTran1 avatar Sep 11 '17 15:09 LinhTran1