Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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"
}
]
}
Owner

pmoelgaard commented Mar 1, 2015

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