-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
179 lines (147 loc) · 4.47 KB
/
server.js
File metadata and controls
179 lines (147 loc) · 4.47 KB
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
const express = require("express");
const rateLimit = require("express-rate-limit");
require("dotenv").config();
const { MongoClient } = require("mongodb");
const app = express();
const PORT = process.env.PORT || 3000;
// Middleware
app.use(express.static("public"));
app.use(express.json());
// MongoDB setup
const client = new MongoClient(process.env.CONNECTIONSTRING);
let db;
async function connectDB() {
await client.connect();
db = client.db("urlDataDb");
console.log("MongoDB connection success");
}
// Start server ONLY after DB connects
async function startServer() {
try {
await connectDB();
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
} catch (err) {
console.error("MongoDB connection failed:", err);
process.exit(1);
}
}
// Rate limiter (to prevent spam)
const createLimiter = rateLimit({
windowMs: 60 * 60 * 1000, // 1h
max: 10,
standardHeaders: true,
legacyHeaders: false,
handler: (req, res) => {
res.status(429).json({ message: "You've reached the limit. Please try again later." });
}
});
startServer();
// Routes
// Create new short URL
app.post("/new", createLimiter, async (req, res) => {
if (!db) {
return res.status(500).json({ error: "Database unavailable" });
}
let { url } = req.body;
url = url?.trim();
console.log(`URL entered: ${url}`);
if (!url) {
return res.status(400).json({ error: "URL is required" });
}
if (!isValidUrl(url)) {
return res.status(400).json({ error: "Invalid URL format" });
}
const collection = db.collection("urlData");
let randomIdValid = false;
let randomId;
while (!randomIdValid) {
randomId = Math.random().toString(36).slice(2, 8);
const response = await collection.findOne({ _id: randomId });
if (!response) randomIdValid = true;
}
await collection.insertOne({
_id: randomId,
url: url,
time: getFormattedDate(),
clicks: 0,
ip: req.ip
});
return res.status(201).json({ id: randomId });
});
app.post("/check", async (req, res) => {
if (!db) {
return res.status(500).json({ error: "Database unavailable" });
}
let { url } = req.body;
url = url?.trim();
console.log(`URL entered: ${url}`);
if (!url) {
return res.status(400).json({ error: "Short code is required" });
}
if (url.length !== 6) {
return res.status(400).json({ error: "Short code must be 6 characters" });
}
const collection = db.collection("urlData");
const doc = await collection.findOne({ _id: url });
if (doc) {
return res.status(200).json({
shortened: doc._id,
original: doc.url
});
}
return res.status(404).json({ error: "URL not found" });
});
// Redirect
app.get("/dir/:id", async (req, res) => {
if (!db) {
return res.status(500).send("Database unavailable");
}
const collection = db.collection("urlData");
const id = req.params.id;
const urlDoc = await collection.findOne({ _id: id });
if (!urlDoc) {
return res.status(404).send("ERROR 404: Link not found.");
}
await collection.updateOne(
{ _id: id },
{ $inc: { clicks: 1 } }
);
res.redirect(urlDoc.url);
});
// Functions
// Check if URL is valid or not
function isValidUrl(url) {
try {
const u = new URL(url);
if (!["http:", "https:"].includes(u.protocol)) return false;
const host = u.hostname;
// must contain a dot, e.g., google.com
if (!host.includes(".")) return false;
// optional: prevent localhost / private IPs
if (
host === "localhost" ||
host === "127.0.0.1" ||
host.startsWith("192.168.") ||
host.startsWith("10.") ||
host.startsWith("172.")
) return false;
// optional: simple TLD check
const tld = host.split(".").pop();
if (tld.length < 2 || tld.length > 6) return false;
return true;
} catch {
return false;
}
}
// Get formatted date
function getFormattedDate() {
const now = new Date();
const day = String(now.getUTCDate()).padStart(2, "0");
const month = String(now.getUTCMonth() + 1).padStart(2, "0");
const year = now.getUTCFullYear();
const hour = now.getHours();
const minute = now.getMinutes();
return `${day}/${month}/${year} ${hour}:${minute}`;
}