-
Notifications
You must be signed in to change notification settings - Fork 7
/
index.js
57 lines (46 loc) · 1.62 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
const http = require("http");
const PORT = process.env.PORT || 5000;
const url = require("url");
const queryValid = require("./utils/checkQueryValidity");
const rateLimitCache = require("./utils/rateLimit")
const password = require("./utils/generate-password.js");
const cacheObj = new rateLimitCache()
const server = http.createServer((req, res) => {
const queryObj = url.parse(req.url, true).query;
const ip = req.socket.remoteAddress;
const rateLimitExceeded = cacheObj.setCache(ip)
if(rateLimitExceeded === false) {
res.end("Too many requests, slow down. Max 20 allowed in 10 seconds")
}else {
const validQueries = {
num: "boolean",
caps: "boolean",
char: "boolean",
len: "number",
};
const validity = queryValid(queryObj, validQueries);
const headers = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET",
"Content-Type": "application/json",
};
if(queryObj && queryObj.len && queryObj.num < 8){
res.writeHead(400, headers);
res.end(JSON.stringify({ data: `len can't be less than 8` }));
}
if (validity.state === false) {
res.writeHead(400, headers);
res.end(JSON.stringify({ data: `${validity.key} is not a valid query` }));
} else {
const data = password(
queryObj.num,
queryObj.char,
queryObj.len,
queryObj.caps
);
res.writeHead(200, headers);
res.end(JSON.stringify({ data: data }));
}
}
});
server.listen(PORT, () => console.log("Server started on port " + PORT));