-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
288 lines (242 loc) · 8.77 KB
/
Copy pathserver.js
File metadata and controls
288 lines (242 loc) · 8.77 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
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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
const express = require('express');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const { Pool } = require('pg');
const cors = require('cors');
require('dotenv').config();
const app = express();
const port = process.env.PORT || 3001;
const secret = process.env.JWT_SECRET;
const url = process.env.API_URL || `http://localhost:${port}`;
const schema = 'minimalink'; // Schema name stored in a configuration variable
app.use(express.json());
app.use(cors()); // Enable CORS for all routes
const pool = new Pool({
user: process.env.DB_USER,
host: process.env.DB_HOST,
database: process.env.DB_NAME,
password: process.env.DB_PASSWORD,
port: process.env.DB_PORT,
ssl: false
});
// Base62 characters
const base62chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
// Convert a number to base62
function toBase62(num) {
if (num === 0) return base62chars[0];
let base62 = '';
while (num > 0) {
base62 = base62chars[num % 62] + base62;
num = Math.floor(num / 62);
}
return base62;
}
// Generate a unique ID
function generateUniqueId() {
const currentTime = Date.now();
const randomNum = Math.floor(Math.random() * 10000);
return currentTime * 10000 + randomNum;
}
// Helper function to format dates
function formatDate(dateString) {
const months = [
"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
];
const date = new Date(dateString);
const day = date.getDate().toString().padStart(2, '0');
const month = months[date.getMonth()];
const hours = date.getHours().toString().padStart(2, '0');
const minutes = date.getMinutes().toString().padStart(2, '0');
return `${day} ${month}, ${hours}:${minutes}`;
}
// User registration
app.post('/api/register', async (req, res) => {
const { email, password } = req.body;
// Check for empty email or password
if (!email || !password) {
return res.status(400).send('Email and password are required');
}
try {
const hashedPassword = await bcrypt.hash(password, 10);
const result = await pool.query(`INSERT INTO ${schema}.users (email, password) VALUES ($1, $2) RETURNING id`, [email, hashedPassword]);
const userId = result.rows[0].id;
const token = jwt.sign({ userId, email }, secret, { expiresIn: '1h' });
res.json({ token, username: `${email}` });
} catch (err) {
console.error('Registration error', err);
res.status(500).send('Registration error');
}
});
// User login
app.post('/api/login', async (req, res) => {
const { email, password } = req.body;
// Check for empty email or password
if (!email || !password) {
return res.status(400).send('Email and password are required');
}
try {
const result = await pool.query(`SELECT id, password FROM ${schema}.users WHERE email = $1`, [email]);
if (result.rows.length === 0) {
return res.status(401).send('Invalid credentials');
}
const { id, password: hashedPassword } = result.rows[0];
const isMatch = await bcrypt.compare(password, hashedPassword);
if (!isMatch) {
return res.status(401).send('Invalid credentials');
}
const token = jwt.sign({ userId: id, email }, secret, { expiresIn: '1h' });
res.json({ token, username: `${email}` });
} catch (err) {
console.error('Login error', err);
res.status(500).send('Login error');
}
});
// Middleware to verify JWT
const authenticateJWT = (req, res, next) => {
const token = req.headers.authorization && req.headers.authorization.split(' ')[1];
if (!token) {
return res.status(401).send('Access token missing');
}
jwt.verify(token, secret, (err, user) => {
if (err) {
return res.status(403).send('Invalid token');
}
req.user = user;
next();
});
};
// Endpoint to shorten URL (with user authentication)
app.post('/api/v1/data/shorten', authenticateJWT, async (req, res) => {
const { longUrl } = req.body;
const userId = req.user.userId;
if (!longUrl) {
return res.status(400).send('longUrl is required');
}
let client;
try {
client = await pool.connect();
// Check if the user has exceeded the limit
const linkCountResult = await client.query(`SELECT COUNT(*) FROM ${schema}.urls WHERE user_id = $1`, [userId]);
const linkCount = parseInt(linkCountResult.rows[0].count, 10);
if (linkCount >= 3 && !req.user) {
return res.status(403).send('Guest users are limited to 3 links');
}
// Check if the long URL already exists
const result = await client.query(`SELECT short_url FROM ${schema}.urls WHERE long_url = $1 AND user_id = $2`, [longUrl, userId]);
if (result.rows.length > 0) {
const { short_url } = result.rows[0];
return res.json({ shortUrl: `${url}/${short_url}`, type: 'existing' });
}
// Generate new unique ID and short URL
const uniqueId = generateUniqueId();
const shortUrl = toBase62(uniqueId);
// Insert into the database with the current timestamp
await client.query(`INSERT INTO ${schema}.urls (id, short_url, long_url, created_at, clicks, user_id) VALUES ($1, $2, $3, CURRENT_TIMESTAMP, 0, $4)`, [uniqueId, shortUrl, longUrl, userId]);
res.json({ shortUrl: `${url}/${shortUrl}`, type: 'new' });
} catch (err) {
console.error('Database query error', err);
res.status(500).send('Database error');
} finally {
if (client) {
client.release();
}
}
});
// Endpoint to redirect to the original URL
app.get('/:shortUrl', async (req, res) => {
const { shortUrl } = req.params;
console.log(`Received request to redirect short URL: ${shortUrl}`);
let client;
try {
client = await pool.connect();
// Fetch the long URL and click count from the database
const result = await client.query(`SELECT long_url, clicks FROM ${schema}.urls WHERE short_url = $1`, [shortUrl]);
console.log(`Database query result: ${JSON.stringify(result.rows)}`);
if (result.rows.length > 0) {
let { long_url, clicks } = result.rows[0];
console.log(`Redirecting to long URL: ${long_url}`);
// Increment the click count
await client.query(`UPDATE ${schema}.urls SET clicks = $1 WHERE short_url = $2`, [clicks + 1, shortUrl]);
// Prepend protocol if missing
if (!long_url.startsWith('http://') && !long_url.startsWith('https://')) {
long_url = 'http://' + long_url;
}
// Ensure the URL is valid before redirecting
try {
new URL(long_url); // Validate URL format
return res.redirect(302, long_url);
} catch (e) {
console.error('Invalid URL format', e);
return res.status(400).send('Invalid URL format');
}
}
console.log('Short URL not found');
res.status(404).send('Short URL not found');
} catch (err) {
console.error('Database query error', err);
res.status(500).send('Database error');
} finally {
if (client) {
client.release();
}
}
});
// Endpoint to fetch the last 5 shortened URLs (guest users and authenticated users)
app.get('/api/v1/data/last5', authenticateJWT, async (req, res) => {
const userId = req.user.userId;
let client;
try {
client = await pool.connect();
// Fetch the last 5 shortened URLs for the authenticated user
const result = await client.query(`
SELECT short_url, long_url, created_at, clicks
FROM ${schema}.urls
WHERE user_id = $1
ORDER BY created_at DESC
LIMIT 5
`, [userId]);
// Format the result
const links = result.rows.map(row => ({
shortLink: `${url}/${row.short_url}`,
originalLink: row.long_url,
dateCreated: formatDate(row.created_at),
shortLinkId: row.short_url,
clicks: row.clicks
}));
res.json(links);
} catch (err) {
console.error('Database query error', err);
res.status(500).send('Database error');
} finally {
if (client) {
client.release();
}
}
});
// Endpoint to delete an entry based on short link (authenticated users only)
app.delete('/api/v1/data/delete/:shortUrl', authenticateJWT, async (req, res) => {
const { shortUrl } = req.params;
const userId = req.user.userId;
let client;
try {
client = await pool.connect();
// Delete the entry from the database
const result = await client.query(`DELETE FROM ${schema}.urls WHERE short_url = $1 AND user_id = $2 RETURNING *`, [shortUrl, userId]);
if (result.rowCount > 0) {
res.status(200).send(`Entry with short URL ${shortUrl} deleted successfully.`);
} else {
res.status(404).send('Short URL not found or you do not have permission to delete this link');
}
} catch (err) {
console.error('Database query error', err);
res.status(500).send('Database error');
} finally {
if (client) {
client.release();
}
}
});
app.listen(port, () => {
console.log(`minimaLINK listening at ${url}`);
});