Uncategorized

Simple WhoAmI for Loopback

Retrieving the currently authenticated user in a Loopback Application can be done in many ways, and one of them is the one I want to share in this post.

I wanted to be able to utilise the Angular SDK as well as the Explorer, so adding a routing manually in a boot script was not really an option, however simple that might be, so I decided to opt for implementing it as a custom Model.

The first thing to do is to create a whoami.json and whoami.js file in the commons directory.

whoami.json

{
  "name": "WhoAmI",
  "base": "Model",
  "plural": "whoami",
  "acls": [
    {
      "accessType": "*",
      "principalType": "ROLE",
      "principalId": "$everyone",
      "permission": "DENY"
    },
    {
      "accessType": "*",
      "principalType": "ROLE",
      "principalId": "$authenticated",
      "permission": "ALLOW"
    }
  ]
}

whoami.js

module.exports = function (WhoAmI) {

    WhoAmI.whoAmI = function (req, next) {
        var AccessToken = WhoAmI.app.models.AccessToken;
        AccessToken.findForRequest(req, {}, function (aux, accesstoken) {
            var UserModel = WhoAmI.app.models.User;
            UserModel.findById(accesstoken.userId, function (error, user) {
                next(error, user);
            });
        });
    }

    WhoAmI.remoteMethod(
        'whoAmI',
        {
            accepts: {arg: 'req', type: 'object', http: {source: 'req'}},
            returns: {arg: 'user', type: 'object'},
            http: {path: '/', verb: 'get'}
        }
    );
};

Secondly, I make sure to add the model to the model-config.json

...
"WhoAmI": {
  "dataSource": null,
  "public": true
}
...

Now, when you restart the server, you will see the following endpoint having been added to your API

2015-03-01_23-05-18

And because of the ACL’s we set in the model, all requests without an access-token are handled by the security of Loopback… so there you go, a nice and easy WhoAmI !

Alternatively… a bootscript

If you for some reason should be inclined to prefer putting it in a boot script, all you have to do is to create a file in the boot directory of the server with the following content

module.exports = function (server) {

    var router = server.loopback.Router();

    router.get('/whoami', function (req, res) {

        var AccessToken = server.models.AccessToken;
        AccessToken.findForRequest(req, {}, function (aux, accesstoken) {
            if (accesstoken == undefined) {
                res.status(401);
                res.send({
                    'Error': 'Unauthorized',
                    'Message': 'You need to be authenticated to access this endpoint'
                });
            }
            else {
                var UserModel = server.models.User;
                UserModel.findById(accesstoken.userId, function (err, user) {
                    res.status(200);
                    res.send(user);
                });
            }
        });
    });

    server.use(router);
}

Gist: https://gist.github.com/pmoelgaard/af6aa61146766f0e8551

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s