-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.ts
69 lines (58 loc) · 1.62 KB
/
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import { SessionData, SessionOptions } from "./types.ts";
import { Session } from "./session.ts";
import {
deleteCookie,
getCookies,
MiddlewareHandlerContext,
nanoid,
setCookie,
} from "./deps.ts";
export const middleware = async (
request: Request,
context: MiddlewareHandlerContext,
options: SessionOptions,
) => {
const cookieName = options.cookie?.name ?? "fresh_session";
const sessionId = getCookies(request.headers)[cookieName] ?? await nanoid(32);
const url = new URL(request.url);
if (["_frsh", ".ico"].some((part) => url.pathname.includes(part))) {
return await context.next();
}
let data: Promise<SessionData | null> | SessionData | null = null;
if (sessionId) {
data = await options.store.byId(sessionId);
}
if (!data) {
data = {
_flash: {},
_expire: new Date(
Date.now() +
(options?.expiration
? options?.expiration * 1000
: 60 * 60 * 2 * 1000),
).getTime(),
_delete: false,
};
}
context.state.session = new Session(sessionId, data);
const response = await context.next();
await options.store.persist(sessionId, data);
await options.store.gc();
setCookie(response.headers, {
name: cookieName,
path: "/",
secure: true,
domain: url.hostname,
expires: Date.now() +
(options?.expiration ? options.expiration * 1000 : 60 * 60 * 2 * 1000), // Two hours...
sameSite: "Lax",
value: sessionId,
httpOnly: true,
...options.cookie,
});
if (data._delete) {
await options.store?.delete(sessionId);
deleteCookie(response.headers, cookieName);
}
return response;
};