forked from Xu-pixel/cabbage_server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Middlewares.ts
40 lines (35 loc) · 1.24 KB
/
Middlewares.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
import { Status, Middleware } from "https://deno.land/x/oak@v11.1.0/mod.ts";
import { verify } from "https://deno.land/x/djwt@v2.8/mod.ts";
import { CabbageState } from "./State.ts";
import { key } from "./key.ts";
export const ErrorHandler: Middleware = async ({ response }, next) => {
try {
await next()
} catch (e) {
response.body = { message: e.message }
response.status = e.status || Status.BadRequest
}
}
export const Logger: Middleware = async (ctx, next) => {
await next();
const rt = ctx.response.headers.get("X-Response-Time");
console.log(`${ctx.request.method} ${ctx.request.url} - ${rt}`);
}
// Timing
export const Timer: Middleware = async (ctx, next) => {
const start = Date.now();
await next();
const ms = Date.now() - start;
ctx.response.headers.set("X-Response-Time", `${ms}ms`);
}
export const JWTKeeper: Middleware<CabbageState> = async ({ request, state, throw: _throw }, next) => {
const jwt = request.headers.get('Authorization')?.slice(7)
try {
const payload = await verify(jwt || '', key)
console.log(payload)
state.userName = payload.name as string
} catch {
_throw(Status.Forbidden, '没有登录状态')
}
await next()
}