forked from GrasshopperBears/sparcs-simple-http-server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
handlers.js
82 lines (75 loc) · 1.74 KB
/
handlers.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
const fs = require("fs");
const set500Error = (res) => {
res.statusCode = 500;
res.body = "Internal Server Error";
return;
};
const handleMainPage = (req, res) => {
const cookie = req.headers.cookie;
if (cookie.includes("authenticated=true")) {
fs.readFile("./public/index.html", (err, data) => {
if (err) {
set500Error(res);
return;
}
res.writeHead(200, { "Content-Type": "text/html" });
res.end(data);
});
return;
} else {
res.writeHead(303, { location: "/login" });
res.end();
}
};
const handleLoginPage = (req, res) => {
if (req.method === "GET") {
// GET request.
fs.readFile("./public/login.html", (err, data) => {
if (err) {
set500Error(res);
return;
}
res.writeHead(200, { "Content-Type": "text/html" });
res.end(data);
});
} else {
// POST request.
res.setHeader("Set-Cookie", ["authenticated=true"]);
res.writeHead(308, { location: "/" });
res.end();
}
};
const handleLogoutPage = (_, res) => {
res.setHeader("Set-Cookie", ["authenticated="]);
res.writeHead(308, { location: "/" });
res.end();
};
const handleTeapotPage = (_, res) => {
fs.readFile("./public/teapot.html", (err, data) => {
if (err) {
set500Error(res);
return;
}
res.writeHead(200, { "Content-Type": "text/html" });
res.end(data);
});
return;
};
const handle404Page = (_, res) => {
fs.readFile("./public/not-found.html", (err, data) => {
if (err) {
set500Error(res);
return;
}
res.writeHead(200, { "Content-Type": "text/html" });
res.end(data);
});
return;
};
module.exports = {
handleMainPage,
handleLoginPage,
handleLogoutPage,
handleTeapotPage,
handle404Page,
};