Lägg till autentisering och loggning, refaktorisera uppgifter till router

This commit is contained in:
2025-01-24 21:26:06 +01:00
parent 70365715fe
commit e091da93e9
7 changed files with 213 additions and 94 deletions

View File

@@ -1,106 +1,15 @@
require('dotenv').config();
const express = require('express');
const bodyParser = require('body-parser');
const fs = require('fs');
const path = require('path');
const basicAuth = require('basic-auth');
const debug = require('debug')('app');
const tasksRouter = require('./routes/tasks');
const app = express();
const port = 3044;
app.use(bodyParser.json());
app.use(express.static('public'));
// Ensure the /data directory exists
const dataDir = '/data';
if (!fs.existsSync(dataDir)) {
fs.mkdirSync(dataDir, { recursive: true });
}
// Ensure the tags.json file exists
const tagsFilePath = path.join(dataDir, 'tags.json');
if (!fs.existsSync(tagsFilePath)) {
fs.writeFileSync(tagsFilePath, JSON.stringify([]));
}
// Authentication middleware
const auth = (req, res, next) => {
const user = basicAuth(req);
const username = 'fredrik'; // Replace with your desired username
const password = 'apa'; // Replace with your desired password
if (user && user.name === username && user.pass === password) {
return next();
} else {
res.set('WWW-Authenticate', 'Basic realm="401"');
return res.status(401).send('Authentication required.');
}
};
// Protect the /add-task endpoint with authentication
app.post('/add-task', auth, (req, res) => {
const { subject, description, scheduled } = req.body;
const currentDateTime = new Date().toISOString().replace(/T/, ' ').replace(/\..+/, '');
let orgFormattedData = `
* TODO ${subject}
SCHEDULED: <${scheduled}>
:LOGBOOK:
- State "TODO" from "TODO" [${currentDateTime}]
:END:
`;
if (description) {
orgFormattedData = `
* TODO ${subject}
${description}
SCHEDULED: <${scheduled}>
:LOGBOOK:
- State "TODO" from "TODO" [${currentDateTime}]
:END:
`;
}
const filePath = path.join(dataDir, 'tasks.org');
fs.appendFile(filePath, orgFormattedData, (err) => {
if (err) {
debug('Error writing to file:', err);
return res.status(500).send('Error writing to file.');
}
res.send({ message: 'Task added successfully!' });
});
});
// Endpoint to save tags
app.post('/save-tags', auth, (req, res) => {
const { tags } = req.body;
const filePath = path.join(dataDir, 'tags.json');
fs.writeFile(filePath, JSON.stringify(tags), (err) => {
if (err) {
debug('Error saving tags:', err);
return res.status(500).send('Error saving tags.');
}
res.send({ message: 'Tags saved successfully!' });
});
});
// Endpoint to retrieve tags
app.get('/get-tags', auth, (req, res) => {
const filePath = path.join(dataDir, 'tags.json');
fs.readFile(filePath, (err, data) => {
if (err) {
debug('Error retrieving tags:', err);
return res.status(500).send('Error retrieving tags.');
}
try {
const tags = JSON.parse(data);
res.send(tags);
} catch (e) {
debug('Error parsing tags JSON:', e);
res.send([]);
}
});
});
app.use('/', tasksRouter);
app.listen(port, () => {
debug(`Server running at http://localhost:${port}`);