|
1 | | -import type { User } from '@/types/user' |
| 1 | +import type {User} from '@/types/user' |
2 | 2 |
|
3 | 3 | export const useJwt = () => { |
4 | | - const parseJwt = (token: string): User | undefined => { |
5 | | - const base64Payload = token.split('.')[1] |
| 4 | + const parseJwt = (token: string): User | undefined => { |
| 5 | + const base64Payload = token.split('.')[1] |
6 | 6 |
|
7 | | - if (base64Payload === undefined) { |
8 | | - return undefined |
9 | | - } |
| 7 | + if (base64Payload === undefined) { |
| 8 | + return undefined |
| 9 | + } |
10 | 10 |
|
11 | | - const base64 = base64Payload.replace(/-/g, '+').replace(/_/g, '/') |
| 11 | + const base64 = base64Payload.replace(/-/g, '+').replace(/_/g, '/') |
12 | 12 |
|
13 | | - const jsonPayload = decodeURIComponent( |
14 | | - window |
15 | | - .atob(base64) |
16 | | - .split('') |
17 | | - .map(function (c) { |
18 | | - return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2) |
19 | | - }) |
20 | | - .join('') |
21 | | - ) |
| 13 | + let jsonPayload: string |
22 | 14 |
|
23 | | - const jsonUser = JSON.parse(jsonPayload) |
| 15 | + if (typeof window !== 'undefined') { |
| 16 | + // Running in browser |
| 17 | + jsonPayload = decodeURIComponent( |
| 18 | + window |
| 19 | + .atob(base64) |
| 20 | + .split('') |
| 21 | + .map((c) => '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2)) |
| 22 | + .join('') |
| 23 | + ) |
| 24 | + } else { |
| 25 | + // Running in Node (SSR) |
| 26 | + const buffer = Buffer.from(base64, 'base64') |
| 27 | + jsonPayload = buffer.toString('utf-8') |
| 28 | + } |
24 | 29 |
|
25 | | - return { |
26 | | - id: jsonUser['slack_id'], |
27 | | - name: jsonUser['name'], |
28 | | - avatar: jsonUser['avatar'], |
29 | | - email: jsonUser['email'], |
| 30 | + const jsonUser = JSON.parse(jsonPayload) |
| 31 | + |
| 32 | + return { |
| 33 | + id: jsonUser['slack_id'], |
| 34 | + name: jsonUser['name'], |
| 35 | + avatar: jsonUser['avatar'], |
| 36 | + email: jsonUser['email'], |
| 37 | + } |
30 | 38 | } |
31 | | - } |
32 | 39 |
|
33 | | - return { |
34 | | - parseJwt, |
35 | | - } |
| 40 | + return { |
| 41 | + parseJwt, |
| 42 | + } |
36 | 43 | } |
0 commit comments