Skip to content

Instantly share code, notes, and snippets.

@SumanaMalkapuram
Last active January 29, 2020 23:33
Show Gist options
  • Save SumanaMalkapuram/79f73ac3089a6326392adffecfed2e41 to your computer and use it in GitHub Desktop.
Save SumanaMalkapuram/79f73ac3089a6326392adffecfed2e41 to your computer and use it in GitHub Desktop.
global object
function(user, context, callback) {
// Modules
const request = require('request');
// Options
const requestTokenOptions = {
method: 'POST',
uri: 'https://' + auth0.domain + '/oauth/token',
headers: {
'content-type': 'application/json'
},
json: {
grant_type: 'client_credentials',
client_id: configuration.clientId,
client_secret: configuration.clientSecret,
audience: '<<Your backend API>>'
}
};
var updateProfile = {
uri: configuration.userEndpoint,
method: 'POST',
headers: {
'content-type': 'application/json'
},
json: { /// Sample data to POST to your API
'auth0_id': user.user_id,
'email': user.email,
'email_verified': user.email_verified,
'account_created_at': user.created_at,
'last_login_at': user.updated_at,
'last_login_ip': context.request.ip
}
};
function callbackWithData(error, response, data) {
if (error !== null) {
callback(new Error('HTTP request error.'));
} else if (response.statusCode === 403) {
callback(new UnauthorizedError(`Access denied - [403 - ${data.code} - ${data.msg}]`));
} else if (response.statusCode === 200) {
const namespace = 'https://sample.com/';
context.idToken[namespace + 'user_id'] = data.user_id;
context.idToken[namespace + 'email'] = user.email;
callback(null, user, context);
} else {
callback(new Error(`Generic Error - [${response.statusCode} - ${data.code} - ${data.msg}]`));
}
}
function postProfile(data) {
// Set access token in header
updateProfile.headers.authorization = `Bearer ${data.access_token}`;
// Request for user profile and callback
request(updateProfile, callbackWithData);
}
if (global.tokenData) {
if (global.tokenData.expire_time > new Date().getTime()) {
postProfile(global.tokenData);
return;
}
}
// Request access token
request(requestTokenOptions, function prepareToken(error, response, data) {
if (error) {
callback(new Error('HTTP request error.'));
return;
} else {
data.expire_time = new Date().getTime() + (data.expires_in * 1000);
global.tokenData = data;
postProfile(data);
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment