UNPKG

passport-descope

Version:

Passport strategy for Descope authentication service

3 lines (2 loc) 1.72 kB
"use strict";function e(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var r=e(require("@descope/node-sdk"));module.exports=class{constructor(e){this._options=e,this.name="descope",this._descopeClient=r.default({projectId:e.projectId,managementKey:e.managementKey}),this._realm=e.realm||"Users",e.scope&&(this._scope=Array.isArray(e.scope)?e.scope:[e.scope])}async authenticate(e,t){const o=this,s=(e=>{var r;const t=null===(r=e.headers)||void 0===r?void 0:r.authorization;if(!t)return null;const o=t.split(" ");if(2==o.length){const e=o[0],r=o[1];if(/^Bearer$/i.test(e))return r}return null})(e)||(e=>{var t;const o={},s=null===(t=e.headers)||void 0===t?void 0:t.cookie;return s?(s.split(";").forEach((e=>{let[r,...t]=e.split("=");if(r=null==r?void 0:r.trim(),!r)return;const s=t.join("=").trim();s&&(o[r]=decodeURIComponent(s))})),o[r.default.SessionTokenCookieName]):null})(e);let n=null;try{n=await o._descopeClient.validateJwt(s)}catch(e){const r="No valid token provided",t=e instanceof Error?e.message:r;return o.fail(o._challenge(401,t))}o._options.verify(n,(async(e,r,t)=>{if(e)return o.error(e);if(!r)return"string"==typeof t&&(t={message:t}),t=t||{},o.fail(o._challenge(401,"invalid_token",t.message));if(t&&t.userDetails){const e=await o._descopeClient.management.user.loadByUserId(n.token.sub);if(console.log(e),!e.ok)return o.fail(o._challenge(401,e.error.errorDescription,e.error.errorMessage));r=e.data}return o.success(r,t)}),e)}_challenge(e,r,t){let o='Bearer realm="'+this._realm+'"';return this._scope&&(o+=', scope="'+this._scope.join(" ")+'"'),e&&(o+=', error="'+e+'"'),r&&(o+=', error_description="'+r+'"'),t&&(o+=', error_uri="'+t+'"'),o}}; //# sourceMappingURL=index.cjs.js.map