-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
65 lines (56 loc) · 1.5 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import { jws } from 'jsrsasign';
export async function verify(userToken: string, aud: string) {
let jwt: IJWT = decodeJWT(userToken)
var jwKey = await fetchPublicKey(jwt.header.kid);
const isValid = jws.JWS.verifyJWT(userToken, jwKey, {
alg: ['RS256'], iss: `https://securetoken.google.com/${aud}`, aud
});
return { isValid, decoded: jwt };
}
function decodeJWT(jwtString: string): IJWT {
// @ts-ignore
const jwt: IJWT = jwtString.match(
/(?<header>[^.]+)\.(?<payload>[^.]+)\.(?<signature>[^.]+)/
).groups;
// @ts-ignore
jwt.header = JSON.parse(atob(jwt.header));
// @ts-ignore
jwt.payload = JSON.parse(atob(jwt.payload));
return jwt;
}
async function fetchPublicKey(kid: string): Promise<any> {
var key: any = await (await fetch('https://www.googleapis.com/robot/v1/metadata/x509/[email protected]')).json();
key = key[kid];
return key;
}
interface IJWT {
header: IJWT_Header,
payload: IJWT_Payload
signature: string;
}
interface IJWT_Header {
alg: string;
kid: string;
typ: string;
}
interface IJWT_Payload {
name: string;
giftcard: boolean;
timecard: boolean;
role: string;
setup: true;
iss: string;
aud: string;
auth_time: number;
user_id: string;
sub: string;
iat: number;
exp: number;
email: string;
email_verified: boolean;
firebase: {
indentities: [object];
sign_in_provider: 'password';
tenant: string;
}
}