/
module.js
55 lines (45 loc) · 1.42 KB
/
module.js
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
import { is, every } from "rcompat/invariant";
import make_session from "./make_session.js";
const cookie = (name, value, { path, secure, httpOnly, sameSite }) =>
`${name}=${value};${httpOnly};Path=${path};${secure};SameSite=${sameSite}`;
// gets a cookie id and returns it if exists, otherwise generates a new one
const in_memory_session_manager = () => {
const store = new Map();
return id => make_session(store, id);
};
export default ({
name = "session_id",
sameSite = "Strict",
httpOnly = true,
path = "/",
manager = in_memory_session_manager(),
implicit = false,
} = {}) => {
every(name, sameSite, path).string();
is(httpOnly).boolean();
is(manager).function();
const options = {
sameSite,
path,
httpOnly: httpOnly ? ";HttpOnly" : "",
};
return {
name: "primate:session",
init(app, next) {
options.secure = app.secure ? ";Secure" : "";
return next(app);
},
async handle(request, next) {
const id = request.cookies.get(name);
const session = manager(id);
every(session.create, session.destroy).function();
const response = await next({ ...request, session });
implicit && session.create();
// only send the cookie if different than the received one
if (session.id !== id && session.id !== undefined) {
response.headers.set("Set-Cookie", cookie(name, session.id, options));
}
return response;
},
};
};