Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
var clientID = "<YOUR-CLIENT-ID>";
var raw_key = "<YOUR-KEY>";
var tenant_domain = "<YOUR-TENANT-DOMAIN>";
exports.get = function (request, response) {
if (request.user.level == 'anonymous') {
response.send(statusCodes.UNAUTHORIZED, null);
return;
}
var errorHandler = function (err) {
console.error(err);
response.send(statusCodes.INTERNAL_SERVER_ERROR, err);
};
request.user.getIdentities({
success: function (identities) {
var objectId = identities.aad.oid;
getAADToken(function (err, access_token) {
if (err) errorHandler(err);
else getUser(access_token, objectId, function (err, user_info) {
if (err) errorHandler(err);
else response.send(statusCodes.OK, user_info);
});
});
},
error: errorHandler
});
};
function getAADToken(callback) {
var req = require("request");
var key = encodeURIComponent(raw_key);
var options = {
url: "https://login.windows.net/" + tenant_domain + "/oauth2/token?api-version=1.0",
method: 'POST',
form: {
grant_type: "client_credentials",
resource: "https://graph.windows.net",
client_id: clientID,
client_secret: raw_key
}
};
req(options, function (err, resp, body) {
if (err || resp.statusCode !== 200) callback(err, null);
else callback(null, JSON.parse(body).access_token);
});
}
function getUser(access_token, objectId, callback) {
var req = require("request");
var options = {
url: "https://graph.windows.net/" + tenant_domain + "/users/" + objectId + "?api-version=1.0",
method: 'GET',
headers: {
"Authorization": "Bearer " + access_token
}
};
req(options, function (err, resp, body) {
if (err || resp.statusCode !== 200) callback(err, null);
else callback(null, JSON.parse(body));
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment