|
| 1 | +const express = require('express'); |
| 2 | +const bodyParser = require('body-parser'); |
| 3 | +const cors = require('cors'); // Import CORS |
| 4 | + |
| 5 | +const app = express(); |
| 6 | +const port = process.env.PORT || 3000; // Port for Render to listen on |
| 7 | + |
| 8 | +// In-memory storage for wikis |
| 9 | +let wikis = [ |
| 10 | + { id: 1, title: 'Node.js', content: 'Node.js is a JavaScript runtime built on Chrome\'s V8 JavaScript engine.', owner: 'kRxZy_kRxZy' }, |
| 11 | + { id: 2, title: 'JavaScript', content: 'JavaScript is a programming language commonly used for web development.', owner: 'MyScratchedAccount' }, |
| 12 | +]; |
| 13 | + |
| 14 | +app.use(bodyParser.json()); |
| 15 | +app.use(cors()); // Enable CORS for all requests |
| 16 | + |
| 17 | +const authorizedUsers = ['kRxZy_kRxZy', 'MyScratchedAccount', 'mcgdj']; |
| 18 | + |
| 19 | +// Middleware to check if user is authorized to edit or delete |
| 20 | +const isAuthorized = (username, wikiOwner) => { |
| 21 | + return username === wikiOwner || authorizedUsers.includes(username); |
| 22 | +}; |
| 23 | + |
| 24 | +// Serve static files (public assets) |
| 25 | +app.use(express.static('public')); |
| 26 | + |
| 27 | +// Create a new wiki |
| 28 | +app.post('/api/wikis', (req, res) => { |
| 29 | + const { title, content, owner } = req.body; |
| 30 | + const newWiki = { id: wikis.length + 1, title, content, owner }; |
| 31 | + wikis.push(newWiki); |
| 32 | + res.status(201).json(newWiki); |
| 33 | +}); |
| 34 | + |
| 35 | +// Edit an existing wiki |
| 36 | +app.put('/api/wikis/:id', (req, res) => { |
| 37 | + const { id } = req.params; |
| 38 | + const { title, content, owner } = req.body; |
| 39 | + |
| 40 | + const wiki = wikis.find(wiki => wiki.id === parseInt(id)); |
| 41 | + if (wiki && isAuthorized(owner, wiki.owner)) { |
| 42 | + wiki.title = title; |
| 43 | + wiki.content = content; |
| 44 | + res.json(wiki); |
| 45 | + } else { |
| 46 | + res.status(403).send('Not authorized or wiki not found'); |
| 47 | + } |
| 48 | +}); |
| 49 | + |
| 50 | +// Delete a wiki |
| 51 | +app.delete('/api/wikis/:id', (req, res) => { |
| 52 | + const { id } = req.params; |
| 53 | + const { owner } = req.body; |
| 54 | + |
| 55 | + const wikiIndex = wikis.findIndex(wiki => wiki.id === parseInt(id)); |
| 56 | + if (wikiIndex !== -1 && isAuthorized(owner, wikis[wikiIndex].owner)) { |
| 57 | + wikis.splice(wikiIndex, 1); |
| 58 | + res.status(200).send('Wiki deleted'); |
| 59 | + } else { |
| 60 | + res.status(403).send('Not authorized or wiki not found'); |
| 61 | + } |
| 62 | +}); |
| 63 | + |
| 64 | +// Get all wikis |
| 65 | +app.get('/api/wikis', (req, res) => { |
| 66 | + res.json(wikis); |
| 67 | +}); |
| 68 | + |
| 69 | +// Start the server |
| 70 | +app.listen(port, () => { |
| 71 | + console.log(`Server is running on port ${port}`); |
| 72 | +}); |
0 commit comments