-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
101 lines (86 loc) · 2.33 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
const path = require("path");
const crypto = require("crypto");
const express = require("express");
const bodyParser = require("body-parser");
const db = {
docs: [],
token2doc: {},
login2doc: {},
add(doc) {
this.docs.push(doc);
this.token2doc[doc.token] = doc;
this.login2doc[doc.login] = doc;
},
getByToken(token) {
return this.token2doc[token];
},
getByLogin(login) {
return this.login2doc[login];
}
};
const app = express();
const srcPath = path.resolve(__dirname, "app");
const vuePath = path.resolve(__dirname, "node_modules/vue/dist/vue.min.js");
const idbPath = path.resolve(__dirname, "node_modules/idb/build/idb.js");
app.use(bodyParser.json({ limit: "50mb", extended: true }));
app.use(express.static(srcPath));
app.get("/vue.min.js", function(req, res) {
res.sendFile(vuePath);
});
app.get("/idb.js", function(req, res) {
res.sendFile(idbPath);
});
app.get("/user/:token", function(req, res) {
const token = req.params.token;
const userData = db.getByToken(token);
if (userData) {
res.status(200).send(userData);
} else {
res.status(401).send({ error: "Unauthorized" });
}
});
app.post("/auth", function(req, res) {
const { newcomer, login, password, name, photo } = req.body;
const userData = db.getByLogin(login);
const token = crypto
.createHash("md5")
.update(login + password)
.digest("hex");
if (newcomer) {
if (userData) {
res.status(401).send({ error: "Try another login" });
} else {
db.add({
token,
login,
name,
photo,
hist: {},
timestamp: Date.now()
});
res.status(200).send({ token });
}
} else if (!userData) {
res.status(401).send({ error: "Incorrect login" });
} else if (userData.token !== token) {
res.status(401).send({ error: "Incorrect password" });
} else {
res.status(200).send({ token });
}
});
app.post("/prophecy", function(req, res) {
const { token, prophecy } = req.body;
const userData = db.getByToken(token);
if (userData) {
userData.hist[prophecy.index] = prophecy;
userData.timestamp = Date.now();
res.status(200).send({ status: "OK" });
} else {
res.status(401).send({ error: "Unauthorized" });
}
});
app.use((req, res, next) => {
res.status(404).send("Fin!");
});
app.listen(4000);
console.log(`http://localhost:4000`);