UNPKG

@kinde-oss/kinde-nodejs-sdk

Version:

Kinde Nodejs SDK allows integrate with Express server using middleware, helpers function

687 lines (676 loc) 59.3 kB
"use strict"; function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var _FlagDataTypeMap = _interopRequireDefault(require("./sdk/constant/FlagDataTypeMap")); var _RefreshToken = _interopRequireDefault(require("./sdk/oauth2/RefreshToken")); var _index = require("./index"); var _AuthorizationCode = _interopRequireDefault(require("./sdk/oauth2/AuthorizationCode")); var _ClientCredentials = _interopRequireDefault(require("./sdk/oauth2/ClientCredentials")); var _PKCE = _interopRequireDefault(require("./sdk/oauth2/PKCE")); var _Utils = require("./sdk/utils/Utils"); var _CookieOptions = _interopRequireDefault(require("./sdk/constant/CookieOptions")); var _SDKVersion = require("./sdk/utils/SDKVersion"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return exports; }; var exports = {}, Op = Object.prototype, hasOwn = Op.hasOwnProperty, defineProperty = Object.defineProperty || function (obj, key, desc) { obj[key] = desc.value; }, $Symbol = "function" == typeof Symbol ? Symbol : {}, iteratorSymbol = $Symbol.iterator || "@@iterator", asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator", toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; function define(obj, key, value) { return Object.defineProperty(obj, key, { value: value, enumerable: !0, configurable: !0, writable: !0 }), obj[key]; } try { define({}, ""); } catch (err) { define = function define(obj, key, value) { return obj[key] = value; }; } function wrap(innerFn, outerFn, self, tryLocsList) { var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator, generator = Object.create(protoGenerator.prototype), context = new Context(tryLocsList || []); return defineProperty(generator, "_invoke", { value: makeInvokeMethod(innerFn, self, context) }), generator; } function tryCatch(fn, obj, arg) { try { return { type: "normal", arg: fn.call(obj, arg) }; } catch (err) { return { type: "throw", arg: err }; } } exports.wrap = wrap; var ContinueSentinel = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var IteratorPrototype = {}; define(IteratorPrototype, iteratorSymbol, function () { return this; }); var getProto = Object.getPrototypeOf, NativeIteratorPrototype = getProto && getProto(getProto(values([]))); NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype); var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); function defineIteratorMethods(prototype) { ["next", "throw", "return"].forEach(function (method) { define(prototype, method, function (arg) { return this._invoke(method, arg); }); }); } function AsyncIterator(generator, PromiseImpl) { function invoke(method, arg, resolve, reject) { var record = tryCatch(generator[method], generator, arg); if ("throw" !== record.type) { var result = record.arg, value = result.value; return value && "object" == _typeof(value) && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) { invoke("next", value, resolve, reject); }, function (err) { invoke("throw", err, resolve, reject); }) : PromiseImpl.resolve(value).then(function (unwrapped) { result.value = unwrapped, resolve(result); }, function (error) { return invoke("throw", error, resolve, reject); }); } reject(record.arg); } var previousPromise; defineProperty(this, "_invoke", { value: function value(method, arg) { function callInvokeWithMethodAndArg() { return new PromiseImpl(function (resolve, reject) { invoke(method, arg, resolve, reject); }); } return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(innerFn, self, context) { var state = "suspendedStart"; return function (method, arg) { if ("executing" === state) throw new Error("Generator is already running"); if ("completed" === state) { if ("throw" === method) throw arg; return doneResult(); } for (context.method = method, context.arg = arg;;) { var delegate = context.delegate; if (delegate) { var delegateResult = maybeInvokeDelegate(delegate, context); if (delegateResult) { if (delegateResult === ContinueSentinel) continue; return delegateResult; } } if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) { if ("suspendedStart" === state) throw state = "completed", context.arg; context.dispatchException(context.arg); } else "return" === context.method && context.abrupt("return", context.arg); state = "executing"; var record = tryCatch(innerFn, self, context); if ("normal" === record.type) { if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue; return { value: record.arg, done: context.done }; } "throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg); } }; } function maybeInvokeDelegate(delegate, context) { var methodName = context.method, method = delegate.iterator[methodName]; if (undefined === method) return context.delegate = null, "throw" === methodName && delegate.iterator["return"] && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method) || "return" !== methodName && (context.method = "throw", context.arg = new TypeError("The iterator does not provide a '" + methodName + "' method")), ContinueSentinel; var record = tryCatch(method, delegate.iterator, context.arg); if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel; var info = record.arg; return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel); } function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; 1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry); } function resetTryEntry(entry) { var record = entry.completion || {}; record.type = "normal", delete record.arg, entry.completion = record; } function Context(tryLocsList) { this.tryEntries = [{ tryLoc: "root" }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0); } function values(iterable) { if (iterable) { var iteratorMethod = iterable[iteratorSymbol]; if (iteratorMethod) return iteratorMethod.call(iterable); if ("function" == typeof iterable.next) return iterable; if (!isNaN(iterable.length)) { var i = -1, next = function next() { for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next; return next.value = undefined, next.done = !0, next; }; return next.next = next; } } return { next: doneResult }; } function doneResult() { return { value: undefined, done: !0 }; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, defineProperty(Gp, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), defineProperty(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) { var ctor = "function" == typeof genFun && genFun.constructor; return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name)); }, exports.mark = function (genFun) { return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun; }, exports.awrap = function (arg) { return { __await: arg }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () { return this; }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) { void 0 === PromiseImpl && (PromiseImpl = Promise); var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl); return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) { return result.done ? result.value : iter.next(); }); }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () { return this; }), define(Gp, "toString", function () { return "[object Generator]"; }), exports.keys = function (val) { var object = Object(val), keys = []; for (var key in object) keys.push(key); return keys.reverse(), function next() { for (; keys.length;) { var key = keys.pop(); if (key in object) return next.value = key, next.done = !1, next; } return next.done = !0, next; }; }, exports.values = values, Context.prototype = { constructor: Context, reset: function reset(skipTempReset) { if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) "t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined); }, stop: function stop() { this.done = !0; var rootRecord = this.tryEntries[0].completion; if ("throw" === rootRecord.type) throw rootRecord.arg; return this.rval; }, dispatchException: function dispatchException(exception) { if (this.done) throw exception; var context = this; function handle(loc, caught) { return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught; } for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i], record = entry.completion; if ("root" === entry.tryLoc) return handle("end"); if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn.call(entry, "catchLoc"), hasFinally = hasOwn.call(entry, "finallyLoc"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } else if (hasCatch) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); } else { if (!hasFinally) throw new Error("try statement without catch or finally"); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } } } }, abrupt: function abrupt(type, arg) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) { var finallyEntry = entry; break; } } finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null); var record = finallyEntry ? finallyEntry.completion : {}; return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record); }, complete: function complete(record, afterLoc) { if ("throw" === record.type) throw record.arg; return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel; }, finish: function finish(finallyLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel; } }, "catch": function _catch(tryLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc === tryLoc) { var record = entry.completion; if ("throw" === record.type) { var thrown = record.arg; resetTryEntry(entry); } return thrown; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(iterable, resultName, nextLoc) { return this.delegate = { iterator: values(iterable), resultName: resultName, nextLoc: nextLoc }, "next" === this.method && (this.arg = undefined), ContinueSentinel; } }, exports; } function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); } function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } /** * KindeClient class for OAuth 2.0 authentication. * @class KindeClient * @param {Object} options - Options object * @property {String} options.domain - Base URL of the Kinde authorization server * @property {String} options.clientId - Client ID of the application * @property {String} options.clientSecret - Client secret of the application * @property {String} options.redirectUri - Redirection URI registered in the authorization server * @property {String} options.logoutRedirectUri - URI to redirect the user after logout * @property {String} options.postLoginRedirectUri - URI to redirect the user after login * @property {String} options.grantType - Grant type for the authentication process (client_credentials, authorization_code or pkce) * @property {String} options.audience - API Identifier for the target API (Optional) * @property {String} options.scope - List of scopes requested by the application (default: 'openid profile email offline') * @property {String} options.kindeSdkLanguage - Kinde SDK language name (default: 'Javascript') * @property {String} options.kindeSdkLanguageVersion - Kinde SDK language version */ var KindeClient = /*#__PURE__*/function (_ApiClient) { _inherits(KindeClient, _ApiClient); var _super = _createSuper(KindeClient); function KindeClient(options) { var _this; _classCallCheck(this, KindeClient); var domain = options.domain, clientId = options.clientId, clientSecret = options.clientSecret, redirectUri = options.redirectUri, logoutRedirectUri = options.logoutRedirectUri, _options$postLoginRed = options.postLoginRedirectUri, postLoginRedirectUri = _options$postLoginRed === void 0 ? '' : _options$postLoginRed, grantType = options.grantType, _options$audience = options.audience, audience = _options$audience === void 0 ? '' : _options$audience, _options$scope = options.scope, scope = _options$scope === void 0 ? 'openid profile email offline' : _options$scope, _options$kindeSdkLang = options.kindeSdkLanguage, kindeSdkLanguage = _options$kindeSdkLang === void 0 ? 'Node.js' : _options$kindeSdkLang, _options$kindeSdkLang2 = options.kindeSdkLanguageVersion, kindeSdkLanguageVersion = _options$kindeSdkLang2 === void 0 ? _SDKVersion.SDK_VERSION : _options$kindeSdkLang2; if (!domain || typeof domain !== 'string') { throw new Error('Please provide domain'); } _this = _super.call(this, domain); _this.domain = domain; if (!redirectUri || typeof redirectUri !== 'string') { throw new Error('Please provide redirectUri'); } _this.redirectUri = redirectUri; if (!clientSecret) { throw new Error('Please provide clientSecret'); } _this.clientSecret = clientSecret; if (!clientId) { throw new Error('Please provide clientId'); } _this.clientId = clientId; if (!grantType) { throw new Error('Please provide grantType'); } if (![_index.GrantType.CLIENT_CREDENTIALS, _index.GrantType.AUTHORIZATION_CODE, _index.GrantType.PKCE].includes(grantType)) { throw new Error('Please provide correct grantType'); } _this.grantType = grantType; if (!logoutRedirectUri || typeof logoutRedirectUri !== 'string') { throw new Error('Please provide logoutRedirectUri'); } _this.logoutRedirectUri = logoutRedirectUri; if (postLoginRedirectUri && typeof postLoginRedirectUri !== 'string') { throw new Error('Provided postLoginRedirectUri must be a string'); } _this.postLoginRedirectUri = postLoginRedirectUri; _this.audience = audience; _this.scope = scope; _this.kindeSdkLanguage = kindeSdkLanguage; _this.kindeSdkLanguageVersion = kindeSdkLanguageVersion; // other endpoint _this.tokenEndpoint = "".concat(domain, "/oauth2/token"); _this.logoutEndpoint = "".concat(domain, "/logout"); _this.authorizationEndpoint = "".concat(domain, "/oauth2/auth"); return _this; } /** * Login middleware function to handle OAuth 2.0 authentication. * @returns {Function} Middleware function for handling the authorization response * @property {Object} request - The HTTP request object * @property {String} request.query.state - Optional parameter used to pass a value to the authorization server * @property {String} request.query.org_code - Organization code * @property {String} request.query.lang - language to display for login page * @property {String} request.query.login_hint - email or phone-number to pre-fill login page * @property {String} request.query.connection_id - connection id string corresponding to social sign in * @property {String} request.query.post_login_redirect_url - URL to redirect the user after login */ _createClass(KindeClient, [{ key: "login", value: function login() { var _this2 = this; return /*#__PURE__*/function () { var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(req, res, next) { var sessionId, _req$query, _req$query$state, state, org_code, _req$query$lang, lang, _req$query$login_hint, login_hint, _req$query$connection, connection_id, _req$query$post_login, post_login_redirect_url, auth, authorizationURL, res_get_token, msg, codeVerifier, codeChallenge; return _regeneratorRuntime().wrap(function _callee$(_context) { while (1) switch (_context.prev = _context.next) { case 0: sessionId = (0, _Utils.getSessionId)(req); _req$query = req.query, _req$query$state = _req$query.state, state = _req$query$state === void 0 ? (0, _Utils.randomString)() : _req$query$state, org_code = _req$query.org_code, _req$query$lang = _req$query.lang, lang = _req$query$lang === void 0 ? '' : _req$query$lang, _req$query$login_hint = _req$query.login_hint, login_hint = _req$query$login_hint === void 0 ? '' : _req$query$login_hint, _req$query$connection = _req$query.connection_id, connection_id = _req$query$connection === void 0 ? '' : _req$query$connection, _req$query$post_login = _req$query.post_login_redirect_url, post_login_redirect_url = _req$query$post_login === void 0 ? '' : _req$query$post_login; if (!(_index.SessionStore.getDataByKey(sessionId, 'kindeAccessToken') && !_this2.isTokenExpired(sessionId))) { _context.next = 4; break; } return _context.abrupt("return", next()); case 4: _context.prev = 4; _context.t0 = _this2.grantType; _context.next = _context.t0 === _index.GrantType.CLIENT_CREDENTIALS ? 8 : _context.t0 === _index.GrantType.AUTHORIZATION_CODE ? 17 : _context.t0 === _index.GrantType.PKCE ? 23 : 32; break; case 8: auth = new _ClientCredentials["default"](); _context.next = 11; return auth.getToken(_this2); case 11: res_get_token = _context.sent; if (!(res_get_token !== null && res_get_token !== void 0 && res_get_token.error)) { _context.next = 15; break; } msg = (res_get_token === null || res_get_token === void 0 ? void 0 : res_get_token.error_description) || (res_get_token === null || res_get_token === void 0 ? void 0 : res_get_token.error); return _context.abrupt("return", next(new Error(msg))); case 15: _this2.saveToken(sessionId, res_get_token); return _context.abrupt("return", next()); case 17: auth = new _AuthorizationCode["default"](); authorizationURL = auth.generateAuthorizationURL(_this2, { state: state, org_code: org_code, lang: lang, login_hint: login_hint, connection_id: connection_id, start_page: 'login' }); if (post_login_redirect_url) { _index.SessionStore.setDataByKey(sessionId, 'kindePostLoginRedirectUrl', post_login_redirect_url); } _index.SessionStore.setDataByKey(sessionId, 'kindeOauthState', state); res.cookie('kindeSessionId', sessionId, _CookieOptions["default"]); return _context.abrupt("return", res.redirect(authorizationURL)); case 23: auth = new _PKCE["default"](); codeVerifier = (0, _Utils.randomString)(); codeChallenge = (0, _Utils.pkceChallengeFromVerifier)(codeVerifier); authorizationURL = auth.generateAuthorizationURL(_this2, { state: state, org_code: org_code, lang: lang, login_hint: login_hint, connection_id: connection_id, start_page: 'login' }, codeChallenge); if (post_login_redirect_url) { _index.SessionStore.setDataByKey(sessionId, 'kindePostLoginRedirectUrl', post_login_redirect_url); } _index.SessionStore.setDataByKey(sessionId, 'kindeOauthState', state); _index.SessionStore.setDataByKey(sessionId, 'kindeOauthCodeVerifier', codeVerifier); res.cookie('kindeSessionId', sessionId, _CookieOptions["default"]); return _context.abrupt("return", res.redirect(authorizationURL)); case 32: _context.next = 37; break; case 34: _context.prev = 34; _context.t1 = _context["catch"](4); return _context.abrupt("return", next(new Error(_context.t1))); case 37: case "end": return _context.stop(); } }, _callee, null, [[4, 34]]); })); return function (_x, _x2, _x3) { return _ref.apply(this, arguments); }; }(); } /** * Register middleware function to handle OAuth 2.0 authentication. * @returns {Function} Middleware function for handling the authorization response * @property {Object} request - The HTTP request object * @property {String} request.query.state - Optional parameter used to pass a value to the authorization server * @property {String} request.query.org_code - Organization code * @property {String} request.query.lang - language to display for register page * @property {String} request.query.login_hint - email or phone-number to pre-fill register page * @property {String} request.query.connection_id - connection id string corresponding to social sign in * @property {String} request.query.post_login_redirect_url - URL to redirect the user after login */ }, { key: "register", value: function register() { var _this3 = this; return function (req, res, next) { var sessionId = (0, _Utils.getSessionId)(req); var _req$query2 = req.query, _req$query2$state = _req$query2.state, state = _req$query2$state === void 0 ? (0, _Utils.randomString)() : _req$query2$state, org_code = _req$query2.org_code, _req$query2$lang = _req$query2.lang, lang = _req$query2$lang === void 0 ? '' : _req$query2$lang, _req$query2$login_hin = _req$query2.login_hint, login_hint = _req$query2$login_hin === void 0 ? '' : _req$query2$login_hin, _req$query2$connectio = _req$query2.connection_id, connection_id = _req$query2$connectio === void 0 ? '' : _req$query2$connectio, _req$query2$post_logi = _req$query2.post_login_redirect_url, post_login_redirect_url = _req$query2$post_logi === void 0 ? '' : _req$query2$post_logi; if (_index.SessionStore.getDataByKey(sessionId, 'kindeAccessToken') && !_this3.isTokenExpired(sessionId)) { return next(); } try { var auth, authorizationURL; switch (_this3.grantType) { case _index.GrantType.AUTHORIZATION_CODE: auth = new _AuthorizationCode["default"](); authorizationURL = auth.generateAuthorizationURL(_this3, { state: state, org_code: org_code, lang: lang, login_hint: login_hint, connection_id: connection_id, start_page: 'registration' }); if (post_login_redirect_url) { _index.SessionStore.setDataByKey(sessionId, 'kindePostLoginRedirectUrl', post_login_redirect_url); } _index.SessionStore.setDataByKey(sessionId, 'kindeOauthState', state); res.cookie('kindeSessionId', sessionId, _CookieOptions["default"]); return res.redirect(authorizationURL); case _index.GrantType.PKCE: auth = new _PKCE["default"](); var codeVerifier = (0, _Utils.randomString)(); var codeChallenge = (0, _Utils.pkceChallengeFromVerifier)(codeVerifier); authorizationURL = auth.generateAuthorizationURL(_this3, { state: state, org_code: org_code, lang: lang, login_hint: login_hint, connection_id: connection_id, start_page: 'registration' }, codeChallenge); if (post_login_redirect_url) { _index.SessionStore.setDataByKey(sessionId, 'kindePostLoginRedirectUrl', post_login_redirect_url); } _index.SessionStore.setDataByKey(sessionId, 'kindeOauthState', state); _index.SessionStore.setDataByKey(sessionId, 'kindeOauthCodeVerifier', codeVerifier); res.cookie('kindeSessionId', sessionId, _CookieOptions["default"]); return res.redirect(authorizationURL); } } catch (err) { return next(new Error(err)); } }; } /** * Callback middleware function for Kinde OAuth 2.0 flow * This function is responsible for handling the response from the authorization server * and obtaining the access token. * @returns {Function} Middleware function for handling the authorization response */ }, { key: "callback", value: function callback() { var _this4 = this; return /*#__PURE__*/function () { var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(req, res, next) { var sessionId, _req$query3, code, state, error, error_description, auth, res_get_token, msg, _res_get_token, _res_get_token2, _res_get_token3, _msg, postLoginRedirectUrlFromStore, postLoginRedirectUrl, _res_get_token4, codeVerifier, _res_get_token5, _res_get_token6, _msg2, _postLoginRedirectUrlFromStore, _postLoginRedirectUrl; return _regeneratorRuntime().wrap(function _callee2$(_context2) { while (1) switch (_context2.prev = _context2.next) { case 0: sessionId = (0, _Utils.getSessionId)(req); _context2.prev = 1; if (!(_index.SessionStore.getDataByKey(sessionId, 'kindeAccessToken') && !_this4.isTokenExpired(sessionId))) { _context2.next = 4; break; } return _context2.abrupt("return", next()); case 4: _req$query3 = req.query, code = _req$query3.code, state = _req$query3.state, error = _req$query3.error, error_description = _req$query3.error_description; if (!error) { _context2.next = 8; break; } msg = error_description || error; return _context2.abrupt("return", next(new Error(msg))); case 8: if (!(!_index.SessionStore.getDataByKey(sessionId, 'kindeOauthState') || state !== _index.SessionStore.getDataByKey(sessionId, 'kindeOauthState'))) { _context2.next = 10; break; } return _context2.abrupt("return", next(new Error('Authentication failed because it tries to validate state'))); case 10: if (code) { _context2.next = 12; break; } return _context2.abrupt("return", next(new Error('Not found code param'))); case 12: _context2.t0 = _this4.grantType; _context2.next = _context2.t0 === _index.GrantType.AUTHORIZATION_CODE ? 15 : _context2.t0 === _index.GrantType.PKCE ? 29 : 46; break; case 15: auth = new _AuthorizationCode["default"](); _context2.next = 18; return auth.getToken(_this4, code); case 18: res_get_token = _context2.sent; if (!((_res_get_token = res_get_token) !== null && _res_get_token !== void 0 && _res_get_token.error)) { _context2.next = 22; break; } _msg = ((_res_get_token2 = res_get_token) === null || _res_get_token2 === void 0 ? void 0 : _res_get_token2.error_description) || ((_res_get_token3 = res_get_token) === null || _res_get_token3 === void 0 ? void 0 : _res_get_token3.error); return _context2.abrupt("return", next(new Error(_msg))); case 22: postLoginRedirectUrlFromStore = _index.SessionStore.getDataByKey(sessionId, 'kindePostLoginRedirectUrl'); if (postLoginRedirectUrlFromStore) { _index.SessionStore.removeDataByKey(sessionId, 'kindePostLoginRedirectUrl'); } _this4.saveToken(sessionId, res_get_token); postLoginRedirectUrl = postLoginRedirectUrlFromStore ? postLoginRedirectUrlFromStore : _this4.postLoginRedirectUri; if (!postLoginRedirectUrl) { _context2.next = 28; break; } return _context2.abrupt("return", res.redirect(postLoginRedirectUrl)); case 28: return _context2.abrupt("return", next()); case 29: codeVerifier = _index.SessionStore.getDataByKey(sessionId, 'kindeOauthCodeVerifier'); if (codeVerifier) { _context2.next = 32; break; } return _context2.abrupt("return", next(new Error('Not found code_verifier'))); case 32: auth = new _PKCE["default"](); _context2.next = 35; return auth.getToken(_this4, code, codeVerifier); case 35: res_get_token = _context2.sent; if (!((_res_get_token4 = res_get_token) !== null && _res_get_token4 !== void 0 && _res_get_token4.error)) { _context2.next = 39; break; } _msg2 = ((_res_get_token5 = res_get_token) === null || _res_get_token5 === void 0 ? void 0 : _res_get_token5.error_description) || ((_res_get_token6 = res_get_token) === null || _res_get_token6 === void 0 ? void 0 : _res_get_token6.error); return _context2.abrupt("return", next(new Error(_msg2))); case 39: _postLoginRedirectUrlFromStore = _index.SessionStore.getDataByKey(sessionId, 'kindePostLoginRedirectUrl'); if (_postLoginRedirectUrlFromStore) { _index.SessionStore.removeDataByKey(sessionId, 'kindePostLoginRedirectUrl'); } _this4.saveToken(sessionId, res_get_token); _postLoginRedirectUrl = _postLoginRedirectUrlFromStore ? _postLoginRedirectUrlFromStore : _this4.postLoginRedirectUri; if (!_postLoginRedirectUrl) { _context2.next = 45; break; } return _context2.abrupt("return", res.redirect(_postLoginRedirectUrl)); case 45: return _context2.abrupt("return", next()); case 46: _context2.next = 52; break; case 48: _context2.prev = 48; _context2.t1 = _context2["catch"](1); _this4.clearSession(sessionId, res); return _context2.abrupt("return", next(new Error(_context2.t1))); case 52: case "end": return _context2.stop(); } }, _callee2, null, [[1, 48]]); })); return function (_x4, _x5, _x6) { return _ref2.apply(this, arguments); }; }(); } /** * CreateOrg middleware functions allows an organization to be created. * @returns {Function} Middleware function for handling the authorization response * @property {Object} request - The HTTP request object * @property {String} request.query.state - Optional parameter used to pass a value to the authorization server * @property {Boolean} request.query.is_create_org - Flag indicating if the user is creating a new organization * @property {String} request.query.org_name - Organization name */ }, { key: "createOrg", value: function createOrg() { var _this5 = this; return function (req, res, next) { var sessionId = (0, _Utils.getSessionId)(req); if (_index.SessionStore.getDataByKey(sessionId, 'kindeAccessToken') && !_this5.isTokenExpired(sessionId)) { return next(); } var _req$query4 = req.query, _req$query4$state = _req$query4.state, state = _req$query4$state === void 0 ? (0, _Utils.randomString)() : _req$query4$state, _req$query4$is_create = _req$query4.is_create_org, is_create_org = _req$query4$is_create === void 0 ? true : _req$query4$is_create, _req$query4$org_name = _req$query4.org_name, org_name = _req$query4$org_name === void 0 ? '' : _req$query4$org_name; try { var auth, authorizationURL; switch (_this5.grantType) { case _index.GrantType.AUTHORIZATION_CODE: auth = new _AuthorizationCode["default"](); authorizationURL = auth.generateAuthorizationURL(_this5, { state: state, is_create_org: is_create_org, org_name: org_name, start_page: 'registration' }); _index.SessionStore.setDataByKey(sessionId, 'kindeOauthState', state); res.cookie('kindeSessionId', sessionId, _CookieOptions["default"]); return res.redirect(authorizationURL); case _index.GrantType.PKCE: auth = new _PKCE["default"](); var codeVerifier = (0, _Utils.randomString)(); var codeChallenge = (0, _Utils.pkceChallengeFromVerifier)(codeVerifier); authorizationURL = auth.generateAuthorizationURL(_this5, { state: state, is_create_org: is_create_org, org_name: org_name, start_page: 'registration' }, codeChallenge); _index.SessionStore.setDataByKey(sessionId, 'kindeOauthState', state); _index.SessionStore.setDataByKey(sessionId, 'kindeOauthCodeVerifier', codeVerifier); res.cookie('kindeSessionId', sessionId, _CookieOptions["default"]); return res.redirect(authorizationURL); } } catch (err) { return next(new Error(err)); } }; } /** * It destroy the token from the req.session and redirects the user to the logout redirect uri * @returns {Response} - The HTTP response with redirect logout URL */ }, { key: "logout", value: function logout() { var _this6 = this; return function (req, res) { var sessionId = (0, _Utils.getSessionId)(req); _this6.clearSession(sessionId, res); return res.redirect("".concat(_this6.logoutEndpoint, "?redirect=").concat(encodeURIComponent(_this6.logoutRedirectUri))); }; } /** * saveToken - saves the tokens and user information to the store and req.session. * @param {String} sessionId - sessionId * @param {Object} token - Token object containing access_token, id_token, expires_in, etc ... */ }, { key: "saveToken", value: function saveToken(sessionId, token) { this.authentications.kindeBearerAuth.accessToken = token.access_token; _index.SessionStore.setData(sessionId, { kindeAccessToken: token.access_token, kindeIdToken: token.id_token, kindeRefreshToken: token.refresh_token, kindeLoginTimeStamp: Date.now(), kindeExpiresIn: token.expires_in }); if (token.id_token) { var payloadIdToken = (0, _Utils.parseJWT)(token.id_token); if (payloadIdToken) { var user = { id: payloadIdToken.sub, given_name: payloadIdToken.given_name, family_name: payloadIdToken.family_name, email: payloadIdToken.email, picture: payloadIdToken.picture }; _index.SessionStore.setDataByKey(sessionId, 'kindeUser', user); } } if (token.access_token) { var payloadAccessToken = (0, _Utils.parseJWT)(token.access_token); if (payloadAccessToken) { var feature_flags = payloadAccessToken.feature_flags; _index.SessionStore.setDataByKey(sessionId, 'kindeFeatureFlags', feature_flags); } } } /** * Retrieves the refresh token for the specified session ID and updates the authentication token. * @param {String} sessionId - The sessionId. * @throws {Error} If the refresh token is invalid or expired. * @throws {Error} If the refresh token is missing. */ }, { key: "getRefreshToken", value: function () { var _getRefreshToken = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(sessionId) { var auth, kindeRefreshToken, res_get_token; return _regeneratorRuntime().wrap(function _callee3$(_context3) { while (1) switch (_context3.prev = _context3.next) { case 0: auth = new _RefreshToken["default"](); kindeRefreshToken = _index.SessionStore.getDataByKey(sessionId, 'kindeRefreshToken'); if (!kindeRefreshToken) { _context3.next = 14; break; } _context3.next = 5; return auth.getToken(this, kindeRefreshToken); case 5: res_get_token = _context3.sent; if (!(res_get_token !== null && res_get_token !== void 0 && res_get_token.error)) { _context3.next = 10; break; } _index.SessionStore.removeData(sessionId); delete this.authentications.kindeBearerAuth.accessToken; throw new Error('Refresh token is invalid or expired'); case 10: this.saveToken(sessionId, res_get_token); return _context3.abrupt("return", res_get_token); case 14: throw new Error('Cannot get token - user is not authenticated'); case 15: case "end": return _context3.stop(); } }, _callee3, this); })); function getRefreshToken(_x7) { return _getRefreshToken.apply(this, arguments); } return getRefreshToken; }() /** * Function return an access token from memory * @param {Object} request - The HTTP request object * @returns {String} - Returns the access token */ }, { key: "getToken", value: function () { var _getToken = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4(request) { var sessionId, auth, res_get_token, _res_get_token7, _res_get_token8, _res_get_token9, msg; return _regeneratorRuntime().wrap(function _callee4$(_context4) { while (1) switch (_context4.prev = _context4.next) { case 0: sessionId = (0, _Utils.getSessionId)(request); _context4.prev = 1; if (!(_index.SessionStore.getDataByKey(sessionId, 'kindeAccessToken') && !this.isTokenExpired(sessionId))) { _context4.next = 4; break; } return _context4.abrupt("return", _index.SessionStore.getDataByKey(sessionId, 'kindeAccessToken')); case 4: if (!(this.grantType === _index.GrantType.CLIENT_CREDENTIALS)) { _context4.next = 16; break; } auth = new _ClientCredentials["default"](); _context4.next = 8; return auth.getToken(this); case 8: res_get_token = _context4.sent; if (!((_res_get_token7 = res_get_token) !== null && _res_get_token7 !== void 0 && _res_get_token7.error)) { _context4.next = 14; break; } _index.SessionStore.removeData(sessionId); delete this.authentications.kindeBearerAuth.accessToken; msg = ((_res_get_token8 = res_get_token) === null || _res_get_token8 === void 0 ? void 0 : _res_get_token8.error_description) || ((_res_get_token9 = res_get_token) === null || _res_get_token9 === void 0 ? void 0 : _res_get_token9.error); throw new Error(msg); case 14: this.saveToken(sessionId, res_get_token); return _context4.abrupt("return", res_get_token.access_token); case 16: if (!(this.grantType === _index.GrantType.AUTHORIZATION_CODE || this.grantType === _index.GrantType.PKCE)) { _context4.next = 21; break; } _context4.next = 19; return this.getRefreshToken(sessionId); case 19: res_get_token = _context4.sent; return _context4.abrupt("return", res_get_token.access_token); case 21: _context4.next = 28; break; case 23: _context4.prev = 23; _context4.t0 = _context4["catch"](1); _index.SessionStore.removeData(sessionId); delete this.authentications.kindeBearerAuth.accessToken; throw new Error(_context4.t0); case 28: case "end": return _context4.stop(); } }, _callee4, this, [[1, 23]]); })); function getToken(_x8) { return _getToken.apply(this, arguments); } return getToken; }() /** * Checks if the access token has expired * @param {Object} sessionId - sessionId * @return {Boolean} True if the access token is not expired, false otherwise */ }, { key: "isTokenExpired", value: function isTokenExpired(sessionId) { var currentTime = Date.now(); var kindeLoginTimeStamp = _index.SessionStore.getDataByKey(sessionId, 'kindeLoginTimeStamp'); var kindeExpiresIn = _index.SessionStore.getDataByKey(sessionId, 'kindeExpiresIn'); if (!kindeLoginTimeStamp || !kindeExpiresIn || currentTime > kindeLoginTimeStamp + kindeExpiresIn * 1000) { delete this.authentications.kindeBearerAuth.accessToken; return true; } return false; } /** * Check if the user is authenticated. * @param {Object} request - The HTTP request object * @returns {Boolean} true if the user is authenticated, otherwise false. */ }, { key: "isAuthenticated", value: function () { var _isAuthenticated = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5(request) { var sessionId; return _regeneratorRuntime().wrap(function _callee5$(_context5) { while (1) switch (_context5.prev = _context5.next) { case 0: sessionId = (0, _Utils.getSessionId)(request); if (!_index.SessionStore.getDataByKey(sessionId, 'kindeAccessToken')) { _context5.next = 6; break; } if (!this.isTokenExpired(sessionId)) {