-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
87 lines (76 loc) · 1.92 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
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
const express = require('express')
const session = require('express-session');
const app = express()
const db = require('mongoose')
const UrlDetail = require('./models/url')
require('dotenv').config();
const {
nanoid
} = require('nanoid');
const bodyParser = require('body-parser');
const PORT = process.env.PORT || 3000
app.use(express.urlencoded({
extended: false
}))
app.set('view engine', 'ejs')
const captcha = require('svg-captcha-express').create({
cookie: 'captcha',
size: 5,
noise: 3,
width: 200,
height: 50,
background: '#fafafa',
charPreset: 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789',
});
app.use(
session({
secret: process.env.SECRET,
resave: false,
saveUninitialized: true
})
);
app.use(bodyParser.urlencoded({
extended: false
}));
db.connect(process.env.MONGODB_URI, {
useNewUrlParser: true,
useUnifiedTopology: true
})
app.get('/captcha.jpg', captcha.image());
app.get('/', async (req, res) => {
const allUrls = await UrlDetail.find({
owner: req.headers['x-forwarded-for'] || req.socket.remoteAddress
})
res.render('index', {
captcha: '/captcha.jpg',
urlsData: allUrls,
siteUrl: req.protocol + '://' + req.get('host') + req.originalUrl
})
})
app.post('/short_url', async (req, res) => {
if (!captcha.check(req, req.body.captcha))
return res.send('Invalid captcha')
const originalUrl = req.body.originalUrl
const record = new UrlDetail({
fullUrl: originalUrl,
owner: req.headers['x-forwarded-for'] || req.socket.remoteAddress,
shortUrl: nanoid(6)
})
await record.save()
res.redirect('/')
})
app.get('/:shortID', async (req, res) => {
const shortID = req.params.shortID
const urlDetails = await UrlDetail.findOne({
shortUrl: shortID
})
if (!urlDetails) return res.status(404).send('No short url found')
urlDetails.hits += 1
await urlDetails.save()
res.redirect(urlDetails.fullUrl)
})
db.connection.on('open', async () => {
app.listen(PORT, () => {
console.log('Listening on PORT: ' + PORT)
})
})