@nopwdio/sdk-js
Version:
Nopwd JS SDK
58 lines • 2.67 kB
JavaScript
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());
});
};
import { endpoint } from "../internal/api/endpoint.js";
import { BadRequestError, ForbiddenError, NotFoundError, UnauthorizedError, } from "../internal/api/errors.js";
import { AbortError, InvalidTokenError, MissingTokenError, NetworkError, UnexpectedError, } from "./errors.js";
/**
* Checks if the token is valid and returns its payload.
* Important: make sure to verify the "aud" claim matches your own domain.
* @param token the access token to verify
* @param signal a way to abord the request (clientside) if needed
* @returns the jwt's payload (if valid)
* @throws {AbortError} when the authentication flow has been canceled (using signal)
* @throws {MissingTokenError} if the token is not defined
* @throws {NetworkError} when a connection error occured
* @throws {InvalidTokenError} when the access token is malformed or expired
* @throws {UnexpectedError} when an unexpected error occured
*/
export const verify = (token, signal) => __awaiter(void 0, void 0, void 0, function* () {
try {
if (!token) {
throw new MissingTokenError();
}
const jwt = (yield endpoint({
method: "GET",
ressource: `/tokens/${token}`,
signal,
}));
return jwt;
}
catch (e) {
if (e instanceof AbortError || e instanceof NetworkError || e instanceof MissingTokenError) {
throw e;
}
if (e instanceof BadRequestError ||
e instanceof NotFoundError ||
e instanceof UnauthorizedError ||
e instanceof ForbiddenError) {
throw new InvalidTokenError();
}
throw new UnexpectedError(e);
}
});
export const getPayload = function (token) {
const jwtParts = token.split(".");
if (jwtParts.length !== 3) {
throw new InvalidTokenError();
}
const payload64 = jwtParts[1].replace(/-/g, "+").replace(/_/g, "/");
return JSON.parse(atob(payload64));
};
//# sourceMappingURL=token.js.map