-
Notifications
You must be signed in to change notification settings - Fork 2
/
server.js
85 lines (83 loc) · 2.53 KB
/
server.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
// Calling all the required modules
require("dotenv").config();
const log = require("./handlers/logHandler");
const fs = require("fs");
const routes = fs
.readdirSync(__dirname + "/routes")
.filter((file) => file.endsWith(".js"));
const mongoose = require("mongoose");
const express = require("express");
const app = express();
const users = require("./models/users");
const others = require("./models/others");
var bodyParser = require("body-parser");
app.use(bodyParser.json());
app.use(
bodyParser.urlencoded({
extended: true,
})
);
mongoose.connect(process.env.mongo, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
var db = mongoose.connection;
db.on("error", console.log.bind(console, "Could not connect to the database!"));
db.once("open", function (callback) {
log.info("Connected to MongoDB!", true);
});
app.get("/", (request, response) => {
response.json({ message: "Welcome to the eCrimePortal API." });
setInterval(async function () {
const us = await users.find();
us.forEach(async (user) => {
const u = await users.findOne({ key: `${user.key}` });
u.calls = 0;
await u.save();
log.info("Refreshed the call limit for all users.");
});
}, 3600000);
});
app.use(async function (req, res, next) {
if (!req.headers.authorization) {
return res.status(400).json({ message: "Bad request" });
}
const auth = await users.findOne({ key: req.headers.authorization });
if (!auth) {
return res.status(403).json({ message: "Invalid key" });
}
if (auth.permission === "8") {
return next();
}
if (parseInt(auth.calls) >= parseInt(auth.limit)) {
return res.status(429).json({ message: "Exceeded your rate limit" });
}
var curcalls = parseInt(auth.calls);
console.log(curcalls);
auth.calls = curcalls + 1;
await auth.save();
next();
});
app.use(async function (req, res, next) {
const ipauth = await others.findOne({ ip: req.connection.remoteAddress });
if (!ipauth) {
return res.status(403).json({ message: "The API is IP whitelisted" });
}
next();
});
for (const route of routes) {
var x = route.slice(0, -3);
var name = require(__dirname + "/routes/" + route);
log.info(`Loaded route ${x}`);
app.use("/" + x, name);
}
app.use(function (req, res) {
res.status(404).send({ message: "Resource not found!" });
});
app.use(function (err, req, res, next) {
res.status(500).send({ message: "Server Error!" });
});
// listen for requests
const listener = app.listen(process.env.port, () => {
log.info("API is online on port " + listener.address().port, true);
});