UNPKG

@hellocoop/helper-server

Version:

Hellō helper functions for server

38 lines (37 loc) 1.43 kB
"use strict"; // fetches an ID token from Hellō given the code and code_verifier Object.defineProperty(exports, "__esModule", { value: true }); exports.fetchToken = fetchToken; const definitions_1 = require("@hellocoop/definitions"); const DEFAULT_ENDPOINT = '/oauth/token'; async function fetchToken({ code, code_verifier, client_id, redirect_uri, wallet }) { const params = { code, code_verifier, client_id, redirect_uri, grant_type: 'authorization_code' }; const body = new URLSearchParams(params).toString(); const tokenEndpoint = (wallet || definitions_1.PRODUCTION_WALLET) + DEFAULT_ENDPOINT; try { const r = await fetch(tokenEndpoint, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body }); const json = await r.json(); if (!r.ok) { const message = `Fetch ${tokenEndpoint} failed with ${r.status}. ` + (json.error ? json.error + '.' : ''); throw new Error(message); } if (json.error) // should not happen as errors have a non 200 response, but just in case throw new Error(json.error); if (!json.id_token) // should not happen, but just in case throw new Error('No id_token in response.'); return json.id_token; } catch (error) { throw new Error(error); } }