sozsoft-platform/ui/src/utils/jwt.ts
2026-08-16 18:30:07 +03:00

27 lines
982 B
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* jwt-decode yerine kullanılan minimal çözücü.
*
* Sadece payload okunuyor; imza doğrulaması zaten sunucunun işi. Token
* base64url kodlu olduğu için `-`/`_` çevrilir ve padding tamamlanır;
* ayrıca Türkçe karakter içeren claim'lerin bozulmaması için atob çıktısı
* UTF-8 olarak yeniden çözülür.
*/
export const jwtDecode = <T = Record<string, unknown>>(token: string): T => {
const payload = token?.split('.')[1]
if (!payload) {
throw new Error('Invalid token specified: missing payload')
}
const base64 = payload.replace(/-/g, '+').replace(/_/g, '/')
const padded = base64.padEnd(base64.length + ((4 - (base64.length % 4)) % 4), '=')
try {
const binary = atob(padded)
const bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0))
return JSON.parse(new TextDecoder().decode(bytes)) as T
} catch {
throw new Error('Invalid token specified: payload could not be decoded')
}
}
export default jwtDecode