Skip to content

Instantly share code, notes, and snippets.

@pmoelgaard
Last active October 26, 2015 17:45
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pmoelgaard/af6aa61146766f0e8551 to your computer and use it in GitHub Desktop.
Save pmoelgaard/af6aa61146766f0e8551 to your computer and use it in GitHub Desktop.
Simple WhoAmI for Loopback
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);
}
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'}
}
);
};
{
"name": "WhoAmI",
"base": "Model",
"plural": "whoami",
"acls": [
{
"accessType": "*",
"principalType": "ROLE",
"principalId": "$everyone",
"permission": "DENY"
},
{
"accessType": "*",
"principalType": "ROLE",
"principalId": "$authenticated",
"permission": "ALLOW"
}
]
}
@pmoelgaard
Copy link
Author

Add the following to model-config.json

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

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