Skip to content
This repository was archived by the owner on Mar 10, 2024. It is now read-only.

Commit 2319f1a

Browse files
preapre for auth documents
1 parent 620a6c2 commit 2319f1a

File tree

4 files changed

+70
-18
lines changed

4 files changed

+70
-18
lines changed

src/db/MongoDB.js

Lines changed: 49 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
const { MongoClient, ObjectID } = require("mongodb");
2+
var crypto = require('crypto');
23
const configs = require('../config/config');
34
const utils = require('../utils');
45

@@ -24,14 +25,16 @@ class MongoDB {
2425
this.db = await this.client.connect();
2526
this.codeWe = await this.db.db('codewe');
2627
this.documentsCollection = await this.codeWe.collection('codewe');
28+
this.usersCollection = await this.codeWe.collection('users');
2729
} catch (err) {
2830
if (configs.DEBUG) {
2931
console.error('Error with db connection');
3032
}
33+
throw new Error(err);
3134
}
3235
}
3336

34-
async createDocument () {
37+
async createDocument (language) {
3538
let doc = {
3639
content: baseCode,
3740
creationDate: Date.now(),
@@ -41,7 +44,7 @@ class MongoDB {
4144
editors: [],
4245
documentLink: '',
4346
linkView: '',
44-
language: 'python',
47+
language: language,
4548
tab: 4
4649
};
4750
try {
@@ -68,9 +71,36 @@ class MongoDB {
6871
}
6972
}
7073

74+
async createUser(userId, secretToken) {
75+
try {
76+
await this.usersCollection.insertOne({
77+
userId: userId,
78+
secretToken: crypto.createHash('sha256').update(secretToken).digest('base64')
79+
});
80+
return 'Success';
81+
} catch (err) {
82+
if (configs.DEBUG) {
83+
console.error('Error when creating user');
84+
}
85+
}
86+
}
87+
88+
async checkUserSecretToken(userId, secretToken) {
89+
try {
90+
const user = await this.usersCollection.findOne({userId: userId});
91+
return (user.secretToken == crypto.createHash('sha256').update(secretToken).digest('base64'));
92+
} catch (err) {
93+
if (configs.DEBUG) {
94+
console.error('Error when checking user secret token');
95+
}
96+
return 'Error';
97+
}
98+
}
99+
71100
async setLine (documentLink, uuid, content) {
72101
try {
73102
await this.documentsCollection.updateOne({documentLink: documentLink, 'content.uuid': uuid}, {$set: {'content.$.content': content.slice(0, 5000)}});
103+
return 'Succes';
74104
} catch (err) {
75105
if (configs.DEBUG) {
76106
console.error('Error when changing line content');
@@ -97,6 +127,7 @@ class MongoDB {
97127
}
98128
});
99129
}
130+
return 'Succes';
100131
} catch (err) {
101132
if (configs.DEBUG) {
102133
console.error('Error when adding a new line to document');
@@ -108,6 +139,7 @@ class MongoDB {
108139
try {
109140
// Delete line at the right place
110141
await this.documentsCollection.updateOne({documentLink: documentLink}, {$pull: {content: {uuid: uuid}}});
142+
return 'Succes';
111143
} catch (err) {
112144
if (configs.DEBUG) {
113145
console.error('Error when deleting a line in document');
@@ -121,6 +153,7 @@ class MongoDB {
121153
const update = {};
122154
update[param] = newValue;
123155
await this.documentsCollection.updateOne({documentLink: documentLink}, {$set: update});
156+
return 'Succes';
124157
} catch (err) {
125158
if (configs.DEBUG) {
126159
console.error(err);
@@ -129,24 +162,25 @@ class MongoDB {
129162
}
130163

131164
async changeCustomName(documentLink, newName) {
132-
this.changeParam(documentLink, 'customDocumentName', newName);
165+
return this.changeParam(documentLink, 'customDocumentName', newName);
133166
}
134167

135168
async changeTabSize(documentLink, newTabSize) {
136169
if (Number.isInteger(newTabSize)) {
137-
this.changeParam(documentLink, 'tab', newTabSize);
170+
return this.changeParam(documentLink, 'tab', newTabSize);
138171
}
139172
}
140173

141174
async changeLanguage(documentLink, newLanguage) {
142175
if (["python"].includes(newLanguage)) {
143-
this.changeParam(documentLink, 'language', newLanguage);
176+
return this.changeParam(documentLink, 'language', newLanguage);
144177
}
145178
}
146179

147180
async addNewEditors(documentLink, newEditorsId) {
148181
try {
149182
await this.documentsCollection.updateOne({documentLink: documentLink}, {$addToSet: {editors: newEditorsId}});
183+
return 'Success';
150184
} catch (err) {
151185
if (configs.DEBUG) {
152186
console.error(error);
@@ -155,16 +189,17 @@ class MongoDB {
155189
}
156190

157191
async updateLastViewedDate(documentLink) {
158-
this.changeParam(documentLink, 'lastViewedDate', Date.now());
192+
return this.changeParam(documentLink, 'lastViewedDate', Date.now());
159193
}
160194

161195
async deleteOldDocuments(days) {
162196
const oldTimestamp = Date.now() - 1000 * 60 * 60 * 24 * days;
163-
this.documentsCollection.deleteMany({'lastViewedDate': {$lt : oldTimestamp} });
197+
return this.documentsCollection.deleteMany({'lastViewedDate': {$lt : oldTimestamp} });
164198
}
165199

166200
async applyRequests (documentLink, requests) {
167201
// TODO look to use bulk write
202+
let success = true;
168203
try {
169204
// Avoid too many requests
170205
requests = requests.slice(0, 50);
@@ -173,16 +208,20 @@ class MongoDB {
173208
let data = request.data;
174209
switch (requestType) {
175210
case 'set-line':
176-
await this.setLine(documentLink, data.id, data.content);
211+
let results = await this.setLine(documentLink, data.id, data.content);
212+
if (!results) success = false;
177213
break;
178214
case 'new-line':
179-
await this.newLine(documentLink, data.previous, data.id, data.content);
215+
let results = await this.newLine(documentLink, data.previous, data.id, data.content);
216+
if (!results) success = false;
180217
break;
181218
case 'delete-line':
182-
await this.deleteLine(documentLink, data.id);
219+
let results = await this.deleteLine(documentLink, data.id);
220+
if (!results) success = false;
183221
break;
184222
}
185223
}
224+
return success;
186225
} catch (err) {
187226
if (configs.DEBUG) {
188227
console.error('Error when applying requests');

src/routes/editor.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,10 +41,11 @@ const router = express.Router();
4141
router.get('/:docId', async (req, res, next) => {
4242
try {
4343
let document = (await db.getDocument(req.params.docId));
44-
if (document) {
44+
if (document) { // && (document.public || (document.editors.includes(req.body.userId) && db.checkUserSecretToken(req.body.userId, secretkey)))
4545
document.document_id = req.params.docId;
4646
res.render('editor.html', {document: document, production: config.PRODUCTION, client_versobe: config.CLIENT_VERBOSE});
4747
}
48+
// else if (!document.public)
4849
else {
4950
res.status(404).render('404.html', {production: config.PRODUCTION, client_versobe: config.CLIENT_VERBOSE})
5051
}

src/routes/index.js

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -52,8 +52,14 @@ router.get('/', (req, res) => {
5252
*/
5353
router.post('/create_document', async (req, res, next) => {
5454
try {
55-
let documentId = await db.createDocument();
56-
res.redirect(`/editor/${documentId}`);
55+
//const language = req.body.language
56+
let documentId = await db.createDocument('python');
57+
if (documentId) {
58+
res.redirect(`/editor/${documentId}`);
59+
}
60+
else {
61+
res.status(500);
62+
}
5763
} catch (err) {
5864
next(err);
5965
}

src/socket/socket.js

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -61,9 +61,12 @@ module.exports = function (wss) {
6161
switch (data.event) {
6262
case 'update':
6363
try {
64+
// let document = db.getDocument(data.room);
65+
// if (document.public || (document.editors.include(userId) and db.checkUsersSecretToken(userId, secretToken)))
6466
broadcastRoomExceptSender(data, 'uuid', data.uuid);
65-
db.updateLastViewedDate(data.room);
66-
db.applyRequests(data.room, data.data);
67+
const succesUpdatingDate = db.updateLastViewedDate(data.room);
68+
const succesUpdate = db.applyRequests(data.room, data.data);
69+
if (!succesUpdatingDate || !succesUpdate) socket.send(JSON.stringify({event: 'update', success: false}));
6770
} catch (err) {
6871
if (config.DEBUG) {
6972
console.error(err);
@@ -83,7 +86,8 @@ module.exports = function (wss) {
8386
case 'language':
8487
try {
8588
broadcastRoomExceptSender(data, 'language', data.language);
86-
db.changeLanguage(data.room, data.language);
89+
const success = db.changeLanguage(data.room, data.language);
90+
if (!success) socket.send(JSON.stringify({event: 'language', success: false}));
8791
} catch (err) {
8892
if (config.DEBUG) {
8993
console.error(err);
@@ -93,7 +97,8 @@ module.exports = function (wss) {
9397
case 'changeTabSize':
9498
try {
9599
broadcastRoomExceptSender(data, 'tabSize', data.tabSize);
96-
db.changeTabSize(data.room, data.tabSize);
100+
const success = db.changeTabSize(data.room, data.tabSize);
101+
if (!success) socket.send(JSON.stringify({event: 'changeTabSize', success: false}));
97102
} catch (err) {
98103
if (config.DEBUG) {
99104
console.error(err);
@@ -103,7 +108,8 @@ module.exports = function (wss) {
103108
case 'changeCustomName':
104109
try {
105110
broadcastRoomExceptSender(data, 'customName', data.customName);
106-
db.changeCustomName(data.customName);
111+
let success = db.changeCustomName(data.customName);
112+
if (!success) socket.send(JSON.stringify({event: 'changeCustomName', success: false}));
107113
} catch (err) {
108114
if (config.DEBUG) {
109115
console.error(err);

0 commit comments

Comments
 (0)