-
Notifications
You must be signed in to change notification settings - Fork 4
/
API.js
262 lines (189 loc) · 7.69 KB
/
API.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
const config = require('./Configuration.json');
const flakeId = require('flakeid');
const { deduplicate, filter, getClientsById, remove } = require('./Utils.js');
const { addMemberToServer, authenticate, createUser, createServer, deleteServer, generateInvite, getMember, getInvite,
getOwnedServers, getServer, isInServer, ownsServer, removeMemberFromServer, serverExists, storeMessage } = require('./DatabaseHandler.js');
const { dispatchMessage, dispatchMember, dispatchMemberLeave, dispatchServerJoin, dispatchServerLeave } = require('./Dispatcher.js');
const express = require('express');
const bodyParser = require('body-parser');
const api = express.Router();
const idGenerator = new flakeId({
timeOffset: (2018 - 1970) * 31536000 * 1000
});
api.use(bodyParser.json());
api.use(bodyParser.urlencoded({ extended: true }));
api.use(allowCORS);
//api.use(notFound);
api.get('/', (req, res) => {
res.send('Welcome to the Union API!');
// TODO: Serve docs or something
});
api.get('/info', (req, res) => {
res.json({
apiVersion: 1,
websocket: config.ws.port,
voice: config.voicews.port,
appSettings: config.rules
});
});
api.patch('/self', (req, res) => {
res.send('Not done.');
// TODO
});
api.post('/create', async (req, res) => {
const { username, password } = req.body;
if (!username || 0 === username.trim().length) {
return res.status(400).json({ 'error': 'Username cannot be empty.' });
}
if (username.trim().length > config.rules.usernameCharacterLimit) {
return res.status(400).json({ 'error': `Username cannot exceed ${config.rules.usernameCharacterLimit} characters.` });
}
if ([':', '#'].some(char => username.includes(char))) {
return res.status(400).json({ 'error': 'Your username contains prohibited characters.' });
}
if (!password || 5 > password.length) {
return res.status(400).json({ 'error': 'Password cannot be empty and must be 5 characters long or more.' });
}
createUser(username.trim(), password)
.then(id => res.status(200).send(id))
.catch(err => res.status(400).json({ 'error': err.message }));
});
api.post('/server', authorize, async (req, res) => { // this feels so inconsistent lul
const { name, iconUrl } = req.body;
if (!name || 0 === name.trim().length) {
return res.status(400).json({ 'error': 'Server name cannot be empty.' });
}
if (await getOwnedServers(req.user.id) >= config.rules.maxServersPerUser) {
return res.status(400).json({ 'error': `You cannot create more than ${config.rules.maxServersPerUser} servers` });
}
const server = await createServer(name, iconUrl, req.user.id);
res.status(200).send();
const clients = getClientsById(global.server.clients, req.user.id);
if (0 < clients.length) {
clients.forEach(ws => ws.user.servers = deduplicate(ws.user.servers, server.id));
dispatchServerJoin(clients, server);
}
});
api.delete('/server/:serverId', validateServer, authorize, async (req, res) => {
const { serverId } = req;
if (!await ownsServer(req.user.id, serverId)) {
return res.status(403).json({ 'error': 'You can only delete servers that you own.' });
}
await deleteServer(serverId);
res.status(200).send();
const clients = filter(global.server.clients, ws => ws.isAuthenticated && ws.user.servers.includes(serverId));
if (0 < clients.length) {
clients.forEach(ws => remove(ws.user.servers, serverId));
dispatchServerLeave(clients, serverId);
}
});
api.post('/server/:serverId/invite', validateServer, authorize, async (req, res) => {
const { serverId } = req;
if (!await ownsServer(req.user.id, serverId)) {
return res.status(403).json({ 'error': 'Only the server owner can generate invites.' });
}
const inviteCode = await generateInvite(serverId, req.user.id);
res.status(200).send({ code: inviteCode });
});
api.post('/server/:serverId/messages', validateServer, authorize, async (req, res) => {
const { serverId } = req;
const { content } = req.body;
if (!req.user.servers.includes(serverId)) {
return res.status(400).json({ 'error': 'You cannot send messages to this server' });
}
if (!content || 0 === content.trim().length) {
return res.status(400).json({ 'error': 'Content must be a string and not empty' });
}
if (content.length > config.rules.messageCharacterLimit) {
return res.status(400).json({ 'error': `Content cannot exceed ${config.rules.messageCharacterLimit} characters` });
}
const id = idGenerator.gen();
storeMessage(id, req.user.id);
const message = {
id,
server: serverId,
content: content.trim(),
author: req.user.id,
createdAt: Date.now()
};
const recipients = filter(global.server.clients, ws => ws.isAuthenticated && ws.user.servers.includes(serverId));
dispatchMessage(recipients, message);
res.status(200).send();
});
api.post('/invites/:inviteId', authorize, async (req, res) => {
const invite = await getInvite(req.params.inviteId);
if (!invite) {
return res.status(404).json({ 'error': 'Unknown invite' });
}
if (!await serverExists(invite.serverId)) {
return res.status(404).json({ 'error': 'Unknown server; invite expired' });
}
const { serverId } = invite;
if (await isInServer(req.user.id, serverId)) {
return res.status(200).send();
}
await addMemberToServer(req.user.id, serverId);
const clients = await getClientsById(global.server.clients, req.user.id);
const server = await getServer(serverId);
if (0 < clients.length) {
clients.forEach(ws => ws.user.servers = deduplicate(ws.user.servers, serverId));
dispatchServerJoin(clients, server);
}
const members = filter(global.server.clients, ws => ws.isAuthenticated && ws.user.servers.includes(serverId) && ws.user.id !== req.user.id);
const member = await getMember(req.user.id);
if (0 < members.length) {
dispatchMember(members, serverId, member);
}
res.status(200).send();
});
api.delete('/self/server/:serverId', validateServer, authorize, async (req, res) => {
const { serverId } = req;
if (!await isInServer(req.user.id, serverId)) {
return res.status(400).json({ 'error': 'You are not in that server' });
}
await removeMemberFromServer(req.user.id, serverId);
const self = await getClientsById(global.server.clients, req.user.id);
const members = filter(global.server.clients, ws => ws.isAuthenticated && ws.user.servers.includes(serverId));
if (0 < members.length) {
dispatchMemberLeave(members, req.user.id, serverId);
}
if (0 < self.length) {
self.forEach(ws => remove(ws.user.servers, serverId));
}
res.status(200).send();
});
api.get('/users/me', authorize, (req, res) => {
delete req.user.password; // :eyes:
res.json(req.user);
});
/**
* Validates the 'authorization' header and populates req.user
*/
async function authorize (req, res, next) {
const user = await authenticate(req.headers.authorization);
if (!user) {
return res.status(401).json({ 'error': 'Unauthorized: You must be logged in to access this route.' });
}
req.user = user;
next();
}
/**
* Ensures a server matching 'serverId' exists
*/
async function validateServer (req, res, next) {
const { serverId } = req.params;
if (!await serverExists(serverId)) {
return res.status(400).json({ 'error': 'Unknown server' });
}
req.serverId = serverId;
next();
}
/**
* Middleware to allow CORS
*/
function allowCORS (req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', '*');
next();
}
module.exports = api;