Hi all,
We are building a serverless service to perform user management by using node-auth0 sdk but it cannot work as well as the direct api call.
//aws lambda
exports.handler = async (event) => {
const auth0Management = await createAuth0Management();
let response;
const requestBody = JSON.parse(event.body.toString());
const createUserResponse = await createAuth0User(auth0Management, requestBody);
response = buildResponse(200, createUserResponse);
return response;
};
async function createAuth0Management(){
return new ManagementClient({
domain: process.env.DOMAIN,
clientId: process.env.CLIENTID,
clientSecret: process.env.CLIENTSECRET,
scope: process.env.SCOPE
});
}
function buildResponse(statusCode, body){
return {
statusCode: statusCode,
headers:{
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json'
},
body: JSON.stringify(body)
}
}
async function createAuth0User(auth0Management, userInfo){
const body = {
email: userInfo[0],
username: userInfo[1],
password: userInfo[2],
connection: 'xxx'
};
//sdk cannot create user
await auth0Client.createUser(body)
.then(function (response){
console.log(`create user success: ${response}`); // <- can not see in cloudwatch
})
.catch(function (err) {
console.log(`create user error: ${err}`); // <- can not see in cloudwatch
});
}
However, we can create the user by calling the api directly
async function createAuth0User(auth0Management, userInfo){
const body = {
email: userInfo[0],
username: userInfo[1],
password: userInfo[2],
connection: 'xxx'
};
//api can create user
await doPostRequest(body).then(()=> {
console.log('created'); // <- it works
})
}
const doPostRequest = (body) => {
return new Promise((resolve, reject) => {
const options = {
host: 'xxx',
path: '/api/v2/users',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization':"Bearer xxx"
}
};
//create the request object with the callback with the result
const req = https.request(options, (res) => {
resolve(JSON.stringify(res.statusCode));
});
// handle the possible errors
req.on('error', (e) => {
reject(e.message);
});
//do the request
req.write(JSON.stringify(body));
//finish the request
req.end();
});
};
Could anyone some help on this, please? Thanks.