it-tools/src/tools/jwt-parser/jwt-parser.service.ts

47 lines
1.5 KiB
TypeScript
Raw Normal View History

2023-01-13 13:59:27 +01:00
import jwtDecode, { type JwtHeader, type JwtPayload } from 'jwt-decode';
import _ from 'lodash';
import { match } from 'ts-pattern';
import { ALGORITHM_DESCRIPTIONS, CLAIM_DESCRIPTIONS } from './jwt-parser.constants';
2023-01-13 13:59:27 +01:00
export { decodeJwt };
function decodeJwt({ jwt }: { jwt: string }) {
const rawHeader = jwtDecode<JwtHeader>(jwt, { header: true });
const rawPayload = jwtDecode<JwtPayload>(jwt);
const header = _.map(rawHeader, (value, claim) => parseClaims({ claim, value }));
const payload = _.map(rawPayload, (value, claim) => parseClaims({ claim, value }));
2023-01-13 13:59:27 +01:00
return {
header,
payload,
};
}
2023-01-13 13:59:27 +01:00
function parseClaims({ claim, value }: { claim: string; value: unknown }) {
const claimDescription = CLAIM_DESCRIPTIONS[claim];
const formattedValue = _.isPlainObject(value) ? JSON.stringify(value, null, 3) : _.toString(value);
2023-01-13 13:59:27 +01:00
const friendlyValue = getFriendlyValue({ claim, value });
return {
value: formattedValue,
friendlyValue,
claim,
claimDescription,
};
}
2023-01-13 13:59:27 +01:00
function getFriendlyValue({ claim, value }: { claim: string; value: unknown }) {
return match(claim)
.with('exp', 'nbf', 'iat', () => dateFormatter(value))
.with('alg', () => (_.isString(value) ? ALGORITHM_DESCRIPTIONS[value] : undefined))
.otherwise(() => undefined);
}
2023-01-13 13:59:27 +01:00
const dateFormatter = (value: unknown) => {
if (_.isNil(value)) return undefined;
2023-01-13 13:59:27 +01:00
const date = new Date(Number(value) * 1000);
return `${date.toLocaleDateString()} ${date.toLocaleTimeString()}`;
};