This repository has been archived by the owner on Feb 14, 2022. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.mjs
153 lines (139 loc) · 3.8 KB
/
index.mjs
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
'use strict';
import './env.mjs';
import logger from './logger.mjs';
logger('INFO');
import { User } from './db.mjs';
import { readdir } from 'fs/promises';
import express, { json, urlencoded } from 'express';
import rL from 'express-rate-limit';
import ms from 'ms';
import compression, { filter as _filter } from 'compression';
import UAParser from 'ua-parser-js';
const instance = process.env.NODE_APP_INSTANCE || 0;
const port = parseInt(`800${instance}`);
const app = express();
import Token from './Token.mjs';
Array.prototype.equals = function(array) {
// if the other array is a falsy value, return
if (!array) return false;
// compare lengths - can save a lot of time
if (this.length != array.length) return false;
for (var i = 0, l = this.length; i < l; i++) {
// Check if we have nested arrays
if (this[i] instanceof Array && array[i] instanceof Array) {
// recurse into the nested arrays
if (!this[i].equals(array[i])) return false;
} else if (this[i] != array[i]) {
// Warning - two different object instances will never be equal: {x:20} != {x:20}
return false;
}
}
return true;
};
// Hide method from for-in loops
Object.defineProperty(Array.prototype, 'equals', { enumerable: false });
const shouldCompress = (req, res) => {
// don't compress responses asking explicitly not
if (req.headers['x-no-compression']) {
return false;
}
// use compression filter function
return _filter(req, res);
};
app.use(async (req, res, next) => {
req.ua = new UAParser(req.headers['user-agent']).getResult();
next();
});
app.use(json());
//enable compression
app.use(compression({ filter: shouldCompress }));
//enable automatic urlencoded parsing of request body
app.use(urlencoded({ extended: true }));
async function auth(req) {
if (!req.headers.authorization) throw null;
let tokenData = new Token(req.headers.authorization);
let usr = await User.findOne({
where: {
id: tokenData.id
}
});
if (!usr) throw null;
if (usr.bannedAt !== null) throw null;
if (
!usr.sessions ||
!usr.sessions.some(
session =>
tokenData.bytes.toJSON().data.equals(session.token.bytes.data) &&
tokenData.time === session.token.time &&
tokenData.id === session.token.id
)
)
throw null;
return usr;
}
//use auth function and append user to Request Object
app.use(async (req, res, next) => {
let user,
errored = false,
error;
try {
user = await auth(req);
} catch (err) {
if (err) {
errored = true;
error = err;
}
user = null;
}
req.user = user;
if (errored) {
res.status(500).json({ error: 'Internal Server Error' });
console.error(error);
} else {
next();
}
});
//Enable default ratelimits
app.use(
'/api/',
rL({
windowMs: ms('5mins'),
max: 100,
keyGenerator: (req, res) => {
return req.user ? req.user.id : req.headers['x-forwarded-for'] || req.ip;
}
})
);
app.all('/api/', (req, res) => {
res.status(200).json({
hello: 'world',
version: '2.0.0'
});
});
(async function() {
let endpoints = await readdir('./api/');
endpoints.forEach(async file => {
endpoints = (await import(`./api/${file}`)).default;
console.info(`Loading endpoints from ${file}`);
endpoints.forEach(endpoint => {
console.info(
`Loading endpoint ${endpoint.method.toUpperCase()} ${endpoint.path}`
);
app[endpoint.method](
endpoint.path,
...endpoint.preHandlers,
async (req, res) => {
try {
await endpoint.handler(req, res);
} catch (error) {
res.status(500).json({ error: 'Internal Server Error' });
console.error(error);
}
}
);
});
});
})();
app.listen(port, () => {
console.log(`Server listening on port ${port}`);
});