function parseJwt()

in apps/newsletters-api/src/app/get-user-profile.ts [8:30]


function parseJwt(
	token: string,
	bodyOrHeader: 'body' | 'headers' = 'body',
): UserProfile | undefined {
	try {
		const base64Url = token.split('.')[
			bodyOrHeader === 'headers' ? 0 : 1
			] as string;
		const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
		const jsonPayload = decodeURIComponent(
			atob(base64)
				.split('')
				.map(function (c) {
					return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
				})
				.join(''),
		);
		return JSON.parse(jsonPayload) as UserProfile;
	} catch (err: unknown) {
		console.warn('failed to parseJwt', err);
		return undefined;
	}
}