-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
executable file
·104 lines (92 loc) · 2.28 KB
/
server.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
const fs = require("fs")
const express = require("express")
const cookieParser = require("cookie-parser")
const bodyParser = require("body-parser")
const { getHomePage } = require("./handlers/index.js")
const {
logoutHandler,
loginHandler,
getLoginPage,
getAccountsPage,
getRegisterPage,
registerHandler } = require("./handlers/session.js")
const server = express()
server.set("views", __dirname + "/views")
server.set("view engine", "jsx")
server.use(bodyParser.json());
server.use(cookieParser())
server.use(bodyParser.urlencoded({ extended: true }));
server.use(express.static(__dirname + "/static"))
server.engine("jsx", require("express-react-views").createEngine({ beautify: true }))
var sessions = {}
const removeSession = (authToken) =>
sessions[authToken] = null
const createSession = (user) => {
const token = (self = (size) => {
if (!size) return ""
return Math.random().toString(16).substring(2) + self(size - 1)
})(4)
sessions[token] = user
console.log(sessions)
return token
}
const getSession = (req, res) => {
const { authToken } = req.cookies
if (!authToken) return null
return sessions[authToken]
}
const routes = [
{
path: "/",
handler: getHomePage
},
{
path: "/accounts",
handler: getAccountsPage
},
{
isGuest: true,
path: "/register",
handler: getRegisterPage
},
{
isGuest: true,
method: "post",
path: "/register",
handler(...args) {
registerHandler(createSession, ...args)
}
},
{
isGuest: true,
method: "post",
path: "/login",
handler(...args) {
loginHandler(createSession, ...args)
}
},
{
isGuest: true,
path: "/login",
handler: getLoginPage
},
{
isPrivate: true,
path: "/logout",
handler(...args) {
logoutHandler(removeSession, ...args)
}
}
]
for (let { method, path, isPrivate, handler, isGuest } of routes) {
if (!method) method = "get"
server[method](path, (req, res) => {
const session = getSession(req, res)
if (isPrivate && !session) return res.render("login", {loginFailed: "Veuillez vous connecter!"})
else
req.session = Object.assign({}, session)
if (isGuest && session) return getHomePage(req, res)
handler(req, res)
})
}
server.listen(90)