Skip to content

Instantly share code, notes, and snippets.

@Tanver-Hasan
Last active August 25, 2022 16:30
Show Gist options
  • Save Tanver-Hasan/9214cef82e85295f69a42ee8c2b1f019 to your computer and use it in GitHub Desktop.
Save Tanver-Hasan/9214cef82e85295f69a42ee8c2b1f019 to your computer and use it in GitHub Desktop.
Executing ROPG grant type in custom db to authenticate the user with another tenant

Custom DB script for connecting with root teant which stores the user information. The login script uses authentication api and exeucte ROPG. get_user script uses apiv2 to query and return the user information

function getByEmail(email, callback) {
const ManagementClient = require("[email protected]").ManagementClient;
const auth0 = new ManagementClient({
domain: "[tenant domin]",
clientId: "[Client ID]", // use configuration object
clientSecret: "[Client Secret]", // use configuration object
});
const params = {
search_engine: "v3",
q: `email:${email}`,
per_page: 10,
page: 0,
};
auth0
.getUsers(params)
.then((users) => {
if (Array.isArray(users) && users.length > 0) {
const publicProfile = users[0];
const profile = {
user_id: publicProfile.user_id.replace("auth0|", ""), // Optional: remove "auth0|" from public cloud id. This is done to avoid an id like "auth0|auth0|123"
email: publicProfile.email,
email_verified: publicProfile.email_verified,
username: publicProfile.username,
};
console.log(profile);
return callback(null, profile);
}
return callback(null);
})
.catch((err) => {
callback(err);
});
}
function login(email, password, callback) {
const request = require("request");
const jwt_decode = require("jwt-decode");
function decodeToken(token) {
const decodedToken = jwt_decode(token);
console.log(decodedToken);
const user = {
user_id: decodedToken.sub.replace("auth0|", ""), // remove "auth0|" from public cloud id. This is done to avoid an id like "auth0|auth0|123"
email: decodedToken.email,
email_verified: decodedToken.email_verified,
};
return user;
}
var options = {
method: "POST",
url: "https://[Auth0 Tenant Domain]/oauth/token",
headers: { "content-type": "application/x-www-form-urlencoded" },
form: {
grant_type: "password",
username: email,
password: password,
//audience: 'YOUR_API_IDENTIFIER',
scope: "openid profile email",
client_id: "[Client ID]",
client_secret: "[Client Secret]"
},
};
request(options, function (error, response, body) {
// if (error) throw new Error(error);
if (error){
return callback(new WrongUsernameOrPasswordError(email, "Incorrect username/email or password."));
}
var data = JSON.parse(body);
const profile = decodeToken(data.id_token);
callback(null, {
email: profile.email,
email_verified: profile.email_verified,
user_id: profile.user_id,
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment