UNPKG

@cobuildlab/auth0-utils

Version:

This is package to deal with common scenarios working with auth0 platform

370 lines (369 loc) 17.2 kB
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; Object.defineProperty(exports, "__esModule", { value: true }); exports.fetchUserToken = exports.hanldeFetch = exports.updateAuth0User = exports.sendAuth0EmailVerification = exports.fetchAccessTokenOnAuth0 = exports.fetchUserByEmailOnAuth0 = exports.createAuth0User = void 0; var node_fetch_1 = require("node-fetch"); var nanoid_1 = require("nanoid"); /** * This action create a auth0 users. * * @param {string} email - Email to create the user. * @param {string} access_token - Need the access token of auth0, you need this obligatory. * @param {string} auth0UsersUrl - This is a url of auth0 project, you can get this in the doc of auth0. Example: https://your-app.us.auth0.com/api/v2/users. * @returns {Promise<any>} - Success data if created the user. * @private */ var createAuth0User = function (email, access_token, auth0UsersUrl) { return __awaiter(void 0, void 0, void 0, function () { var password, userResponse, error_1; return __generator(this, function (_a) { switch (_a.label) { case 0: password = (0, nanoid_1.nanoid)(10); console.log(password); if (!access_token) { throw new Error('No valid access token'); } _a.label = 1; case 1: _a.trys.push([1, 3, , 4]); return [4 /*yield*/, (0, node_fetch_1.default)("".concat(auth0UsersUrl), { method: 'POST', headers: { 'content-type': 'application/json', Authorization: 'Bearer ' + access_token, }, body: JSON.stringify({ email: email, password: "*".concat(password, "*"), connection: 'Username-Password-Authentication', }), })]; case 2: userResponse = _a.sent(); return [3 /*break*/, 4]; case 3: error_1 = _a.sent(); console.log('ERROR CREATING AUTH0 USER \n', error_1); if (typeof error_1 === 'string') { throw new Error(error_1); } throw error_1; case 4: return [4 /*yield*/, userResponse.json()]; case 5: userResponse = _a.sent(); if (!userResponse) { console.log('CreateUserError', userResponse); console.log('ERROR CREATING AUTH0 USER \n'); throw new Error('ERROR CREATING AUTH0 USER'); } console.log('User auth0 Created Success', userResponse); return [2 /*return*/, userResponse]; } }); }); }; exports.createAuth0User = createAuth0User; /** * @description Fetch user by email on auth0. * * @param {string} email - Email of the user to look all data of user in auth0. * @param {string} access_token - Api access token. * @param {string} token_type - The type of api token. * @param {string} url - Url to fetch the users by email on auth0. Example: https://your-app.us.auth0.com/api/v2/users-by-email?email=. * * @returns {Promise<string | undefined>} The id of the user to be blocked. * @private */ var fetchUserByEmailOnAuth0 = function (email, access_token, token_type, url) { return __awaiter(void 0, void 0, void 0, function () { var userResponse, user, error_2; return __generator(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 3, , 4]); return [4 /*yield*/, (0, node_fetch_1.default)(url + email, { method: 'GET', headers: { Authorization: "".concat(token_type, " ").concat(access_token), }, })]; case 1: userResponse = _a.sent(); return [4 /*yield*/, userResponse.json()]; case 2: user = (_a.sent())[0]; return [2 /*return*/, user.user_id]; case 3: error_2 = _a.sent(); console.log('ERROR FECHING USER \n', error_2); throw error_2; case 4: return [2 /*return*/]; } }); }); }; exports.fetchUserByEmailOnAuth0 = fetchUserByEmailOnAuth0; /** * @description Function to fetch auth0 access token. * @param {string} fetchTokenUrl - Url to fetch auth0 token. Example: https://your-app.us.auth0.com/oauth/token. * @param {string} auth0Audience - Auth0 audience of your project. Example: https://your-app.us.auth0.com/api/v2/. * @param {string} auth0MachineClientId - Need a M2M client id. Example: IAx2aVXfXUNW1qjk4sQYtMMRoWFSM6wx. * @param {string} auth0MachineSecret - Need a M2M client secret. Example: PZJJKWuBQcUc610fyGaLP4mVV6S9kHYyHSreup8A4Ltum7yAWgPTKzX4YxkydShb. * @returns {Promise<AccessTokenAuth0>} The access token and token type for conections with the API. * @private */ var fetchAccessTokenOnAuth0 = function (fetchTokenUrl, auth0Audience, auth0MachineClientId, auth0MachineSecret) { return __awaiter(void 0, void 0, void 0, function () { var response, authResponse, error_3; return __generator(this, function (_a) { switch (_a.label) { case 0: if (fetchTokenUrl === undefined) throw new Error('fetchTokenUrl is undefined'); _a.label = 1; case 1: _a.trys.push([1, 4, , 5]); return [4 /*yield*/, (0, node_fetch_1.default)(fetchTokenUrl, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ audience: auth0Audience, grant_type: 'client_credentials', client_id: auth0MachineClientId, client_secret: auth0MachineSecret, }), })]; case 2: response = _a.sent(); return [4 /*yield*/, response.json()]; case 3: authResponse = (_a.sent()); if (!authResponse.access_token) { console.log('accessTokenError', authResponse); throw new Error('There was a problem with the access token'); } return [2 /*return*/, authResponse]; case 4: error_3 = _a.sent(); console.log('authActionError', error_3); throw error_3; case 5: return [2 /*return*/]; } }); }); }; exports.fetchAccessTokenOnAuth0 = fetchAccessTokenOnAuth0; /** * @description Request email verification from Auth0. * * @param {string} auth_domain - Auth0's auth domain. * @param {string} access_token - Auth0's management api access token (see {@linkcode fetchAccessTokenOnAuth0}). * @param {string} user_id - Authenticated user ID. * @param {string} client_id - Auth0's machine client ID. * @param {string} provider - User's authentication provider. * * @returns {Promise<void>} - Gracefully exit if job was successfully created. * * @private */ var sendAuth0EmailVerification = function (auth_domain, access_token, user_id, client_id, provider) { return __awaiter(void 0, void 0, void 0, function () { var response; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, (0, node_fetch_1.default)("https://".concat(auth_domain, "/api/v2/jobs/verification-email"), { method: 'POST', headers: { 'content-type': 'application/json', Authorization: "Bearer ".concat(access_token), }, body: JSON.stringify({ user_id: "".concat(provider, "|").concat(user_id), client_id: client_id, identity: { user_id: user_id, provider: provider, }, }), })]; case 1: response = _a.sent(); if (response.status !== 201) { throw new Error("Request failed with status code ".concat(response.status)); } return [2 /*return*/]; } }); }); }; exports.sendAuth0EmailVerification = sendAuth0EmailVerification; /** * This action updates an auth0 user. * * @param {string} user_id - ID of the user to be updated. * @param {string} access_token - Auth0 access token. Required. * @param {string} auth_domain - This is the url of the auth0 project, you can get this in the doc of auth0. Example: https://your-app.us.auth0.com/api/v2/users. * @param {Object} data - Data to be updated. * @returns {Promise<any>} - Success data if user is updated. * @private */ var updateAuth0User = function (user_id, access_token, auth_domain, data) { return __awaiter(void 0, void 0, void 0, function () { var userResponse, error_4; return __generator(this, function (_a) { switch (_a.label) { case 0: if (!access_token) { throw new Error('No valid access token'); } if (!auth_domain) { throw new Error('No valid auth0 auth domain'); } _a.label = 1; case 1: _a.trys.push([1, 3, , 4]); return [4 /*yield*/, (0, node_fetch_1.default)("https://".concat(auth_domain, "/api/v2/users/").concat(user_id), { method: 'PATCH', headers: { 'content-type': 'application/json', Authorization: 'Bearer ' + access_token, }, body: JSON.stringify(data), })]; case 2: userResponse = _a.sent(); return [3 /*break*/, 4]; case 3: error_4 = _a.sent(); console.log('ERROR UPDATING AUTH0 USER \n', error_4); throw error_4; case 4: return [4 /*yield*/, userResponse.json()]; case 5: userResponse = _a.sent(); if (!userResponse) { console.log('UpdateUserError', userResponse); console.log('ERROR UPDATING AUTH0 USER \n'); throw new Error('ERROR UPDATING AUTH0 USER'); } console.log('User auth0 Update Success', userResponse); return [2 /*return*/, userResponse]; } }); }); }; exports.updateAuth0User = updateAuth0User; /** * @param promise - Input promise. * @returns Promise Result. */ function hanldeFetch(promise) { return __awaiter(this, void 0, void 0, function () { var result, data; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, promise]; case 1: result = _a.sent(); return [4 /*yield*/, result.json()]; case 2: data = _a.sent(); if (data.error || data.statusCode >= 400) { throw data; } return [2 /*return*/, data]; } }); }); } exports.hanldeFetch = hanldeFetch; /** * This action updates an auth0 user. * * @param {string} fetchTokenUrl - Token url. * @param {string} username - Username or email. * @param {string} password - Current user password. * @param {Object} auth0Audience - Audience. * @param {string} auth0MachineClientId - Cliend id required. * @param {string} auth0MachineSecret - Secret Cliend id required. * @param {Object} scope - Data to be updated. * @returns {Promise<any>} - Success data if user is updated. * @private */ var fetchUserToken = function (fetchTokenUrl, username, password, auth0Audience, auth0MachineClientId, auth0MachineSecret, scope) { if (scope === void 0) { scope = 'profile email'; } return __awaiter(void 0, void 0, void 0, function () { var response, error_5, authResponse; return __generator(this, function (_a) { switch (_a.label) { case 0: if (fetchTokenUrl === undefined) throw new Error('fetchTokenUrl is undefined'); _a.label = 1; case 1: _a.trys.push([1, 3, , 4]); return [4 /*yield*/, (0, node_fetch_1.default)(fetchTokenUrl, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ audience: auth0Audience, grant_type: 'password', password: password, username: username, client_id: auth0MachineClientId, client_secret: auth0MachineSecret, scope: scope, }), })]; case 2: response = _a.sent(); return [3 /*break*/, 4]; case 3: error_5 = _a.sent(); console.log('authActionError', error_5); throw error_5; case 4: if (response.status === 403) { throw { message: 'Invalid password or email', status: 403 }; } else if (!response.ok) { throw new Error('Failed to get token'); } return [4 /*yield*/, response.json()]; case 5: authResponse = (_a.sent()); if (!authResponse.access_token) { console.log('accessTokenError', authResponse); throw new Error('There was a problem with the access token'); } return [2 /*return*/, authResponse]; } }); }); }; exports.fetchUserToken = fetchUserToken;