-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy pathjwt-auth.middleware.ts
47 lines (40 loc) · 1.12 KB
/
jwt-auth.middleware.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
import { Context, AuthUser } from "./../types.ts";
import { validateJwt } from "https://deno.land/x/[email protected]/validate.ts";
/**
* Decode token and returns payload
* if given token is not expired
* and valid with respect to given `secret`
*/
const getJwtPayload = async (token: string, secret: string): Promise<any | null> => {
try {
const jwtObject = await validateJwt(token, secret);
if (jwtObject && jwtObject.payload) {
return jwtObject.payload;
}
} catch (err) {}
return null;
};
/***
* JWTAuth middleware
* Decode authorization bearer token
* and attach as an user in application context
*/
const JWTAuthMiddleware = (JWTSecret: string) => {
return async (
ctx: Context,
next: () => Promise<void>,
) => {
try {
const authHeader = ctx.request.headers.get("Authorization");
if (authHeader) {
const token = authHeader.replace(/^bearer/i, "").trim();
const user = await getJwtPayload(token, JWTSecret);
if (user) {
ctx.user = user as AuthUser;
}
}
} catch (err) { }
await next();
};
}
export { JWTAuthMiddleware };