Add password protection to shorten and stats

This commit is contained in:
Christopher Cookman 2024-08-05 14:18:07 -06:00
parent f8a1d9c6ef
commit cad2514628
Signed by: ChrisChrome
GPG key ID: A023A26E42C33A42

View file

@ -42,6 +42,10 @@ app.get('/:shortUrl', (req, res) => { // Shortened URL
});
app.get('/stats/:shortUrl', (req, res) => { // Stats
if (req.query.passcode !== passcode) {
return res.status(403).json({ error: 'Invalid passcode' });
}
const shortUrl = req.params.shortUrl;
db.get('SELECT * FROM urls WHERE shortUrl = ?', [shortUrl], (err, row) => {
if (err) {
@ -68,6 +72,9 @@ app.post('/shorten', (req, res) => { // Shorten URL
if (!req.body.url) {
return res.status(400).json({ error: 'Please provide a URL' });
}
if (req.body.passcode !== passcode) {
return res.status(403).json({ error: 'Invalid passcode' });
}
// Generate a 8 character long string, only if { shortUrl } doesnt exist in body
const shortUrl = req.body.shortUrl || Math.random().toString(36).substr(2, 8);
// Check if shortUrl is already in use
@ -91,6 +98,7 @@ app.post('/shorten', (req, res) => { // Shorten URL
});
port = process.env.SERVER_PORT || 3000;
passcode = process.env.PASSCODE || 'ChangeMe';
app.listen(port, () => {
console.log(`Server is running on port ${port}`);