UNPKG

@permitio/permit-js

Version:

Permitio is a frontend package that makes it easy to use permit abilities

221 lines 11.4 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 __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.PermitElements = void 0; const ky_1 = __importDefault(require("ky")); const types_1 = require("./types"); const sendToken_1 = require("./sendToken"); const PERMIT_URL = new RegExp('^https:\/\/([a-z0-9]{32}\.|)embed\(\.api|)(\.stg|)\.permit\.io$'); const PERMIT_LOCAL_URL = new RegExp('http:\/\/localhost:.000'); const PERMIT_API_URL = "https://api.permit.io"; class PermitElements { constructor() { this.isDev = false; this.loginWithAjax = ({ loginUrl, loginMethod, tenant, token, headers, userJwt, userKeyClaim, }) => __awaiter(this, void 0, void 0, function* () { let postData = { tenant: tenant }; if (loginMethod === types_1.LoginMethod.bearer) { if (token === undefined) { throw new Error('When using bearer login, token must be defined'); } this.config = Object.assign(Object.assign({}, this.config), { headers: Object.assign(Object.assign({}, this.config.headers), { Authorization: `Bearer ${token}` }) }); } if (loginMethod === types_1.LoginMethod.supportsPrivateBrowser) { if (token) { this.config = Object.assign(Object.assign({}, this.config), { headers: Object.assign(Object.assign({}, this.config.headers), { Authorization: `Bearer ${token}` }) }); } if (headers) { this.config = Object.assign(Object.assign({}, this.config), { headers: Object.assign({}, headers) }); } this.config = Object.assign(Object.assign({}, this.config), { headers: Object.assign({}, this.config.headers) }); } if (loginMethod === types_1.LoginMethod.header) { if (headers === undefined) { throw new Error('When using header login, headers must be defined'); } this.config = Object.assign(Object.assign({}, this.config), { headers: Object.assign({}, headers) }); } if (loginMethod === types_1.LoginMethod.frontendOnly) { if (tenant === undefined) { throw new Error('When using frontendOnly login, tenant must be defined'); } postData = { tenant_id: tenant, user_jwt: userJwt }; if (userKeyClaim !== undefined) { postData = Object.assign(Object.assign({}, postData), { user_key_claim: userKeyClaim }); } } else { if (userKeyClaim !== undefined) { console.warn('userKeyClaim will be used only when using frontendOnly login method'); } } return ky_1.default.post(loginUrl, Object.assign({ json: postData }, this.config)) .json() .then((data) => { if (loginMethod === types_1.LoginMethod.frontendOnly) { return data.redirect_url; } else { return data.url; } }) .catch((error) => { this.isConnected = false; console.error(error); throw new Error('Error while trying to login, make sure that you\'ve created a login as route in your application and passed the right credentials'); }); }); this.login = ({ loginUrl, loginMethod = types_1.LoginMethod.cookie, tenant, token, headers, userJwt, envId, elementIframeUrl, userKeyClaim, permitApiUrl = PERMIT_API_URL, }) => __awaiter(this, void 0, void 0, function* () { if (this.isConnected) { console.info('Already connected, if you want to connect to another tenant, please logout first'); return Promise.resolve(true); } // check if the iframe is already created const checkIframe = document.getElementById('permit-iframe'); if (checkIframe) { return Promise.resolve(false); } let iframeUrl = loginUrl; if (loginMethod === types_1.LoginMethod.bearer || loginMethod === types_1.LoginMethod.header || loginMethod === types_1.LoginMethod.cookie) { if (loginUrl === undefined) { throw new Error('When using bearer, header or cookie login, loginUrl must be defined'); } } if (loginMethod === types_1.LoginMethod.frontendOnly) { if (userJwt === undefined) { throw new Error('When using frontendOnly login, userJwt must be defined'); } if (loginUrl !== undefined) { console.warn('When using frontendOnly login, loginUrl will be ignored'); } if (envId === undefined) { throw new Error('When using frontendOnly login, envId must be defined'); } loginUrl = `${permitApiUrl}/v2/auth/${envId}/elements_fe_login_as`; iframeUrl = yield this.loginWithAjax({ loginUrl, loginMethod, tenant, token, userJwt, userKeyClaim }); } if (loginMethod === types_1.LoginMethod.supportsPrivateBrowser) { if (!elementIframeUrl) { throw new Error('When using supportsPrivateBrowser login, elementIframeUrl must be defined'); } const tokenWithOutCookie = yield this.loginWithAjax({ loginUrl, loginMethod, tenant, token, headers, userKeyClaim }); (0, sendToken_1.sendTokenToIframe)(tokenWithOutCookie, elementIframeUrl); return Promise.resolve(true); } if (loginMethod === types_1.LoginMethod.header || loginMethod === types_1.LoginMethod.bearer) { iframeUrl = yield this.loginWithAjax({ loginUrl, loginMethod, tenant, token, headers, userKeyClaim }); } if (loginMethod === types_1.LoginMethod.cookie && tenant !== undefined) { if (loginUrl.includes('?')) { iframeUrl = `${loginUrl}&tenant=${tenant}`; } else { iframeUrl = `${loginUrl}?tenant=${tenant}`; } } else { iframeUrl = loginUrl; } const iframe = document.createElement('iframe'); iframe.style.display = 'hidden'; iframe.style.width = '1px'; iframe.style.height = '1px'; iframe.style.position = 'absolute'; iframe.style.top = '-10px'; iframe.style.left = '-10px'; iframe.src = iframeUrl; return new Promise((resolve, reject) => { window.addEventListener("message", (msg) => { var _a; const urlRegex = PERMIT_URL; if (msg.origin.match(urlRegex)) { if (msg.data.success === true) { this.isConnected = true; this.me = msg.data.me; resolve(true); } if (msg.data.success === false) { this.isConnected = false; const errorMsg = decodeURIComponent((_a = msg === null || msg === void 0 ? void 0 : msg.data) === null || _a === void 0 ? void 0 : _a.error); reject(errorMsg); } } }, false); document.body.appendChild(iframe); this.isConnected = true; setTimeout(() => { document.body.removeChild(iframe); }, 3000); }); }); this.approve = ({ inviteCode, email, token, envId, user_key_claim = "sub", attributes = {} }) => __awaiter(this, void 0, void 0, function* () { const cleanEnvId = envId.replace(/-/g, ''); const approveUrl = `https://${cleanEnvId}.embed.api.permit.io/v2/auth/${cleanEnvId}/user_invites/${inviteCode}/approve`; const params = { email: email, user_key_claim: user_key_claim, attributes: attributes, }; this.config = Object.assign(Object.assign({}, this.config), { headers: { Authorization: `Bearer ${token}` } }); return ky_1.default .post(approveUrl, Object.assign({ json: params }, this.config)).json() .then((data) => { return data; }) .catch((error) => { console.error(error); throw new Error('Error while trying to approve invite'); }); }); this.logout = (logoutCustomUrl) => __awaiter(this, void 0, void 0, function* () { var _a, _b; let logoutUrl = ''; if (logoutCustomUrl) { logoutUrl = logoutCustomUrl; } else { const cleanEnvId = (_b = (_a = this.me) === null || _a === void 0 ? void 0 : _a.actor) === null || _b === void 0 ? void 0 : _b.env_id.replace(/-/g, ''); logoutUrl = `https://${cleanEnvId}.embed.api.permit.io/v2/auth/logout`; } // add iframe to logout const iframe = document.createElement('iframe'); iframe.id = 'permit-iframe-logout'; iframe.style.width = '1px'; iframe.style.height = '1px'; iframe.style.position = 'absolute'; iframe.src = logoutUrl; iframe.style.top = '-10px'; iframe.style.left = '-10px'; document.body.appendChild(iframe); this.isConnected = false; return Promise.resolve(true); }); this.help = () => { const helpMessage = `Permit elements lets you display Permit elements in your application To use this feature you need to follow these instructions: https://permit.io/docs/elements`; console.info(helpMessage); return helpMessage; }; this.config = { credentials: 'include' }; this.isConnected = false; } } exports.PermitElements = PermitElements; //# sourceMappingURL=elements.js.map