-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
75 lines (64 loc) · 2.07 KB
/
app.js
File metadata and controls
75 lines (64 loc) · 2.07 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
const express = require('express');
const mongoose = require('mongoose');
const { nanoid } = import('nanoid');
const path = require('path');
const app = express();
const PORT = process.env.PORT || 3000;
// Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/pastebin', {
useNewUrlParser: true,
useUnifiedTopology: true,
});
// Define Paste schema and model
const pasteSchema = new mongoose.Schema({
content: String,
pasteId: { type: String, unique: true },
ip: String, // New field to store user's IP
createdAt: { type: Date, default: Date.now },
});
const Paste = mongoose.model('Paste', pasteSchema);
// Middleware
app.use(express.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, 'public')));
app.set('view engine', 'ejs');
// Route Admin
app.get('/admin', async (req, res) => {
const pastes = await Paste.find({});
res.render('admin', { pastes });
});
// Route to create a new paste
app.post('/create', async (req, res) => {
const content = req.body.content;
const pasteId = nanoid(10);
const ip = req.headers['x-forwarded-for'] || req.socket.remoteAddress; // Get user's IP address
const newPaste = new Paste({ content, pasteId, ip });
await newPaste.save();
res.redirect(`/${pasteId}`);
});
// Route to display a paste by its ID (must be placed below /admin)
app.get('/:id', async (req, res) => {
const pasteId = req.params.id;
const paste = await Paste.findOne({ pasteId });
if (paste) {
res.render('paste', { content: paste.content });
} else {
res.status(404).send('Paste not found');
}
});
// Route to modify a paste
app.post('/admin/edit/:id', async (req, res) => {
const pasteId = req.params.id;
const newContent = req.body.content;
await Paste.updateOne({ pasteId }, { content: newContent });
res.redirect('/admin');
});
// Route to delete a paste
app.post('/admin/delete/:id', async (req, res) => {
const pasteId = req.params.id;
await Paste.deleteOne({ pasteId });
res.redirect('/admin');
});
// Start server
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});