-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathindex.js
More file actions
44 lines (35 loc) · 1.08 KB
/
Copy pathindex.js
File metadata and controls
44 lines (35 loc) · 1.08 KB
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
import express from "express";
import sessions from "client-sessions";
import { fileURLToPath } from "url";
import { dirname, join } from "path";
const __dirname = dirname(fileURLToPath(import.meta.url));
const ONE_DAY_MS = 24 * 60 * 60 * 1000;
const FIVE_MINUTES_MS = 5 * 60 * 1000;
export const app = express();
app.use(sessions({
cookieName: "session",
secret: process.env.SESSION_SECRET,
duration: ONE_DAY_MS,
activeDuration: FIVE_MINUTES_MS,
cookie: { httpOnly: true, secure: true, sameSite: "lax" },
}));
app.get("/login", (req, res) => {
res.sendFile(join(__dirname, "login.html"));
});
app.post("/api/login", express.urlencoded({ extended: false }), (req, res) => {
req.session.user = { name: req.body.name };
res.json({ ok: true });
});
app.get("/logout", (req, res) => {
res.sendFile(join(__dirname, "logout.html"));
});
app.post("/api/logout", (req, res) => {
req.session.reset();
res.json({ ok: true });
});
export function requireLogin(req, res, next) {
if (!req.session?.user) {
return res.status(401).json({ error: "unauthorized" });
}
next();
}