Skip to content

Commit b4e10d9

Browse files
committed
Add AccessTokenPayload validation to parseJwt function
1 parent 0b130b5 commit b4e10d9

File tree

1 file changed

+15
-2
lines changed

1 file changed

+15
-2
lines changed

frontend/src/contexts/UserContext.tsx

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,8 @@
1+
import {
2+
AccessToken,
3+
AccessTokenPayload,
4+
AccessTokenPayloadSchema,
5+
} from "@/types/Token";
16
import { UserProfile } from "@/types/User";
27
import React, {
38
createContext,
@@ -28,8 +33,16 @@ export function useUser() {
2833
return useContext(UserContext);
2934
}
3035

31-
function parseJwt(token: string) {
36+
function parseJwt(token: AccessToken): AccessTokenPayload {
3237
const base64Url = token.split(".")[1];
3338
const base64 = base64Url.replace(/-/g, "+").replace(/_/g, "/");
34-
return JSON.parse(atob(base64));
39+
const jsonPayload = decodeURIComponent(
40+
atob(base64)
41+
.split("")
42+
.map((c) => {
43+
return "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2);
44+
})
45+
.join("")
46+
);
47+
return AccessTokenPayloadSchema.parse(JSON.parse(jsonPayload));
3548
}

0 commit comments

Comments
 (0)