-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
executable file
·124 lines (109 loc) · 3.06 KB
/
index.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
const express = require('express');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const Chat = require('./chatdb');
const Users = require('./usersdb');
let repost=null; /*Переменная для текста repost*/
const app = express();
app.use(bodyParser());
app.use(cookieParser());
app.use(express.static('client'));
const chat = new Chat('db.db');
const users = new Users();
let onlineUsers = [];
app.get('/', (req, res) => {
const user = users.getCurrent(req, (user) => {
const page = user.length ? 'chat' : 'login';
res.sendFile('client/' + page + '.html', {root: __dirname});
});
});
app.post('/users', (req, res) => {
const name = req.body.user;
const password = req.body.password;
if (name === '') {
res.sendStatus(401);
return;
}
users.get(name, (user) => {
if (user.length) {
if (password !== user[0].password) {
res.sendStatus(403);
} else {
onlineUsers.push(name);
res.cookie('sid', user[0].sid);
res.redirect('/');
}
} else {
onlineUsers.push(name);
users.add(name, password).then((user) => {
res.cookie('sid', user.sid);
res.redirect('/');
}).catch(() => {
res.sendStatus(500);
});
}
});
});
app.get('/messages', (req, res) => {
users.getCurrent(req, (user) => {
if (!user.length) {
res.sendStatus(403);
} else {
chat.getAll(user[0].name, (messages) => {
res.json(messages);
});
}
});
});
app.post('/messages', (req, res) => {
const user = users.getCurrent(req, (user) => {
if (!user.length) {
res.sendStatus(403);
} else {
chat.add(user[0].name, req.body.text, repost);
chat.getAll(user[0].name, (data) => {
res.json(data);
});
}
});
});
app.get('/messages/:id', (req, res) => {
users.getCurrent(req, (user) => {
if (!user.length) {
res.sendStatus(403);
} else {
const messageId = req.params.id;
// select message from DB
chat.get(messageId, message => res.json(message));
}
});
});
app.post('/change', (req, res) => {
users.getCurrent(req, (user) => {
if (!user.length) {
res.sendStatus(403);
} else {
chat.put(req.body.messageId, req.body.text, (callback) => {
});
chat.getAll(user[0].name, (data) => {
res.json(data);
});
}
});
});
app.get('/logout', (req, res) => {
res.cookie('sid', null);
res.redirect('/');
});
app.post('/logout', (req, res) => {
onlineUsers.pop();
res.json(onlineUsers);
console.log(onlineUsers);
});
app.post('/repost', (req, res) => {
repost = req.body;
});
app.post('/onlineUsers', (req, res) => {
res.json(onlineUsers);
});
app.listen(3000);