UNPKG

next-bungie-auth

Version:

Next Bungie Auth is an open source Next.js library that provides a configurable solution for authenticating your users with Bungie.net

63 lines (62 loc) 2.27 kB
/* eslint-disable @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-argument */ import { BungieAuthorizationError } from "./error"; const responseJsonKeys = [ "access_token", "token_type", "expires_in", "refresh_token", "refresh_expires_in", "membership_id", ]; const errorResponseJsonKeys = ["error", "error_description"]; /** @internal */ export const getTokens = async ({ grantType, value, }, config) => { const data = await config .tokenHttp({ clientId: config.clientId, clientSecret: config.clientSecret, grantType, grantKey: grantType === "authorization_code" ? "code" : "refresh_token", value, }) .then(async (res) => { if (res.ok) { const tokenResponse = await res.json(); if (!responseJsonKeys.every((key) => key in tokenResponse)) { throw new TypeError("Response body is missing required keys"); } return tokenResponse; } // Handle invalid token response if (res.headers.get("content-type")?.includes("application/json")) { const errorResponse = await res.json(); if (!errorResponseJsonKeys.every((key) => key in errorResponse)) { throw new TypeError(`Unexpected error response: ${JSON.stringify(errorResponse)}`); } throw new BungieAuthorizationError(errorResponse.error, errorResponse.error_description); } else { throw new TypeError(`Invalid response [${res.status}]: ${await res.text()}`); } }); return data; }; /** @internal */ export const encodeToken = (data, config) => { return btoa(data .split("") .map((c, i) => String.fromCharCode(c.charCodeAt(0) + config.clientSecret.charCodeAt(i % config.clientSecret.length))) .join("")); }; /** @internal */ export const decodeToken = (encodedStr, config) => { if (!encodedStr) { return null; } return atob(encodedStr) .split("") .map((c, i) => String.fromCharCode(c.charCodeAt(0) - config.clientSecret.charCodeAt(i % config.clientSecret.length))) .join(""); };