This repository has been archived by the owner on Jan 8, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
377 lines (343 loc) · 10 KB
/
app.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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
require("babel-register")({
presets: ["es2015"]
});
const createError = require("http-errors");
const express = require("express");
const path = require("path");
const cookieParser = require("cookie-parser");
const logger = require("morgan");
const compression = require("compression");
const jsonWebToken = require("jsonwebtoken");
const { prisma } = require("./prisma-client");
const history = require("connect-history-api-fallback");
const fs = require("fs");
const { ApolloServer, gql } = require("apollo-server-express");
const { readFileSync } = require("fs");
const { resolvers } = require("./resolvers");
const { JWTSecretKey } = require("./config");
const bcrypt = require("bcrypt");
const http = require("http");
const app = express();
const httpServer = http.createServer(app);
const io = require("socket.io").listen(httpServer, {
serveClient: false
});
//options
const { Step } = require("prosemirror-transform");
const schema = require("./prosemirror-schema.js");
const maxStoredSteps = 100;
const defaultData = {
version: 0,
doc: {
type: "doc",
content: [
{
type: "paragraph",
content: [{ type: "text", text: "" }]
}
]
}
};
io.on("connection", function(socket) {
let previousId;
let docPath;
let lockedPath;
let stepsPath;
const safeJoin = async currentId => {
socket.leave(previousId);
try {
const jwtToken = socket.request.headers.cookie
.match(/jwt=.*?; /m)[0]
.slice(4, -2);
const userId = jsonWebToken.verify(jwtToken, JWTSecretKey).id || false;
const members = await prisma
.note({ id: currentId })
.group()
.members();
for (const member of members) {
if (member.id === userId) {
socket.join(currentId);
previousId = currentId;
docPath = `./notes/${currentId}/db.json`;
lockedPath = `./notes/${currentId}/db_locked.json`;
stepsPath = `./notes/${currentId}/db_steps.json`;
}
}
} catch (error) {
console.error({ error: true, data: error });
}
};
function storeDoc(data) {
fs.writeFileSync(docPath, JSON.stringify(data, null, 2));
}
function storeSteps({ steps, version }) {
const oldData = JSON.parse(fs.readFileSync(stepsPath, "utf8"));
const limitedOldData = oldData.slice(
Math.max(oldData.length - maxStoredSteps)
);
const newData = [
...limitedOldData,
...steps.map((step, index) => {
return {
step: JSON.parse(JSON.stringify(step)),
version: version + index + 1,
clientID: step.clientID
};
})
];
fs.writeFileSync(stepsPath, JSON.stringify(newData));
}
function storeLocked(locked) {
fs.writeFileSync(lockedPath, locked.toString());
}
function getDoc() {
try {
return JSON.parse(fs.readFileSync(docPath, "utf8"));
} catch (e) {
return defaultData;
}
}
function getLocked(lockedPath) {
return JSON.parse(fs.readFileSync(lockedPath, "utf8"));
}
function getSteps(version) {
try {
const steps = JSON.parse(fs.readFileSync(stepsPath, "utf8"));
return steps.filter(step => step.version > version);
} catch (e) {
return [];
}
}
socket.on("getDoc", docId => {
safeJoin(docId).then(() => {
io.emit("init", getDoc());
});
});
socket.on("update", function({ version, clientID, steps }) {
const locked = getLocked(lockedPath);
// we need to check if there is another update processed
// so we store a "locked" state
if (locked) {
// we will do nothing and wait for another client update
return;
}
storeLocked(true);
const storedData = getDoc();
// version mismatch: the stored version is newer
// so we send all steps of this version back to the user
if (storedData.version !== version) {
socket.emit("update", {
version,
steps: getSteps(version)
});
storeLocked(false);
return;
}
let doc;
try {
doc = schema.nodeFromJSON(storedData.doc);
let newSteps = steps.map(step => {
const newStep = Step.fromJSON(schema, step);
newStep.clientID = clientID;
// apply step to document
let result = newStep.apply(doc);
if (result.doc === null) throw "Doc is null";
doc = result.doc;
return newStep;
});
// calculating a new version number is easy
const newVersion = version + newSteps.length;
// store data
storeSteps({ version, steps: newSteps });
storeDoc({ version: newVersion, doc });
// send update to everyone (me and others)
io.sockets.emit("update", {
version: newVersion,
steps: getSteps(version)
});
} catch (error) {
console.error(error);
} finally {
storeLocked(false);
}
});
socket.on("disconnect", function() {
io.emit("user disconnected");
});
});
app.use(compression());
app.use(express.static(path.join(__dirname, "images")));
// For development usage only
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "http://localhost:8080");
res.header("Access-Control-Allow-Credentials", "true");
res.header("Access-Control-Allow-Methods", "GET,HEAD,PUT,PATCH,POST,DELETE");
res.header("Access-Control-Expose-Headers", "Content-Length");
res.header(
"Access-Control-Allow-Headers",
"Accept, Authorization, Content-Type, X-Requested-With, Range"
);
if (req.method === "OPTIONS") {
return res.sendStatus(200);
} else {
return next();
}
});
// view engine setup
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "pug");
app.use(logger("dev"));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.get("/", (req, res) => {
res.sendFile(path.join(__dirname, "front", "dist", "index.html"));
});
app.get("/about", (req, res) => {
res.sendFile(path.join(__dirname, "front", "public", "about.html"));
});
app.post("/register", (req, res) => {
const MILLISECONDS_IN_HOUR = 3600000;
bcrypt.genSalt(10, function(err, salt) {
bcrypt.hash(req.body.password, salt, async function(err, hash) {
try {
const user = await prisma.createUser({
name: req.body.name,
email: req.body.email,
password: hash,
image: "/img/avatar.svg",
role: "USER"
});
const token = jsonWebToken.sign(user, JWTSecretKey);
res.cookie("jwt", token, {
maxAge: MILLISECONDS_IN_HOUR,
httpOnly: true
});
res.send({
email: user.email,
id: user.id,
image: user.image,
name: user.name,
role: user.role
});
} catch (error) {
res.send({ error: true, data: error });
}
});
});
});
app.post("/login", async (req, res) => {
const MILLISECONDS_IN_HOUR = 3600000;
try {
const user = await prisma.user({
email: req.body.email
});
bcrypt.compare(req.body.password, user.password, function(err, result) {
if (result) {
const tokenData = {
email: user.email,
name: user.name,
role: user.role,
id: user.id
};
const token = jsonWebToken.sign(tokenData, JWTSecretKey);
res.cookie("jwt", token, {
maxAge: MILLISECONDS_IN_HOUR,
httpOnly: true
});
res.send({
email: user.email,
id: user.id,
image: user.image,
name: user.name,
role: user.role
});
} else {
res.send({ error: true, data: "Invalid email or password" });
}
});
} catch (error) {
res.send({ error: true, data: error });
}
});
app.post("/logout", (req, res) => {
res.cookie("jwt", "", { maxAge: new Date(0) });
res.send({ error: false, data: "Logged out" });
});
app.get("/join/:groupId", async (req, res) => {
const cookie = req.cookies.jwt;
try {
if (cookie) {
const user = jsonWebToken.verify(cookie, JWTSecretKey);
const group = await prisma.group({ id: req.params.groupId });
if (user.id && Number(group.joinable) > Date.now()) {
const newGroup = { ...group, members: { connect: { id: user.id } } };
delete newGroup.id;
prisma.updateGroup({
data: newGroup,
where: { id: req.params.groupId }
});
res.send("Udało się dołączyć do grupy " + group.name);
}
}
res.send(
"Nie udało się dołączyć (niezalogowany lub dołączanie nowych członków jest wyłączone)"
);
} catch (e) {
res.send(String(e));
}
});
const apolloServer = new ApolloServer({
typeDefs: gql`
${readFileSync(__dirname.concat("/schema/schema.graphql"), "utf8")}
`,
resolvers,
context: ({ req, res }) => {
const MILLISECONDS_IN_HOUR = 3600000;
const cookie = req.cookies.jwt;
if (cookie === undefined) {
res.status(403).send({ error: true, data: "You must be logged in" });
} else {
res.cookie("jwt", cookie, {
maxAge: MILLISECONDS_IN_HOUR,
httpOnly: true
});
}
try {
return jsonWebToken.verify(cookie, JWTSecretKey);
} catch (error) {
res.status(403).send({ error: true, data: error });
return {};
}
}
});
apolloServer.applyMiddleware({
app,
cors: { credentials: true, origin: "http://localhost:8080" }
});
app.use(express.static(path.join(__dirname, "front", "dist")));
app.use(
history({
disableDotRule: true,
verbose: true
})
);
app.use(express.static(path.join(__dirname, "front", "dist")));
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get("env") === "development" ? err : {};
// render the error page
res.status(err.status || 500);
res.render("error");
});
httpServer.listen({ port: 4000 }, () =>
console.log(
`🚀 Server ready at http://localhost:4000${apolloServer.graphqlPath}`
)
);