11 Commits

17 changed files with 360 additions and 112 deletions

View File

@@ -9,10 +9,20 @@ services:
volumes:
- /srv/swarm/org-todo-pwa/data:/data
user: "1000:1000"
environment:
- DEBUG=app
- AUTH_USERNAME=fredrik
- AUTH_PASSWORD=apa
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:3044"]
interval: 5m
timeout: 10s
retries: 3
deploy:
labels:
- "traefik.enable=true"
- "traefik.http.routers.plan.tls=true"
- "traefik.http.routers.plan.tls.certresolver=myhttpchallenge"
- "traefik.http.routers.plan.rule=Host(`todo.casablanca.wahlberg.se`)"
- "traefik.http.routers.plan.entrypoints=websecure"
- "traefik.http.routers.plan.entrypoints=websecure"

BIN
favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 66 KiB

98
logger.js Normal file
View File

@@ -0,0 +1,98 @@
const { createLogger, format, transports } = require('winston');
const logger = createLogger({
level: 'info',
format: format.combine(
format.timestamp(),
format.json()
),
transports: [
new transports.Console(),
new transports.File({ filename: 'app.log' })
]
});
module.exports = logger;
// filepath: /home/fredrik/dev/org-todo-pwa/routes/tasks.js
const express = require('express');
const fs = require('fs');
const path = require('path');
const logger = require('../logger');
const auth = require('../middleware/auth');
const router = express.Router();
const dataDir = '/data';
// Ensure the /data directory exists
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([]));
}
// Protect the /add-task endpoint with authentication
router.post('/add-task', auth, async (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');
try {
await fs.promises.appendFile(filePath, orgFormattedData);
res.send({ message: 'Task added successfully!' });
} catch (err) {
logger.error('Error writing to file:', err);
res.status(500).send('Error writing to file.');
}
});
// Endpoint to save tags
router.post('/save-tags', auth, async (req, res) => {
const { tags } = req.body;
const filePath = path.join(dataDir, 'tags.json');
try {
await fs.promises.writeFile(filePath, JSON.stringify(tags));
res.send({ message: 'Tags saved successfully!' });
} catch (err) {
logger.error('Error saving tags:', err);
res.status(500).send('Error saving tags.');
}
});
// Endpoint to retrieve tags
router.get('/get-tags', auth, async (req, res) => {
const filePath = path.join(dataDir, 'tags.json');
try {
const data = await fs.promises.readFile(filePath);
const tags = JSON.parse(data);
res.send(tags);
} catch (err) {
logger.error('Error retrieving tags:', err);
res.status(500).send('Error retrieving tags.');
}
});
module.exports = router;

11
middleware/auth.js Normal file
View File

@@ -0,0 +1,11 @@
const basicAuth = require('basic-auth');
const auth = (req, res, next) => {
if (req.session && req.session.user) {
return next();
} else {
res.status(401).send('Authentication required.');
}
};
module.exports = auth;

84
package-lock.json generated
View File

@@ -12,7 +12,9 @@
"basic-auth": "^2.0.1",
"body-parser": "^1.20.3",
"debug": "^4.4.0",
"dotenv": "^16.4.7",
"express": "^4.21.2",
"express-session": "^1.18.1",
"fs": "^0.0.1-security"
}
},
@@ -185,6 +187,17 @@
"npm": "1.2.8000 || >= 1.4.16"
}
},
"node_modules/dotenv": {
"version": "16.4.7",
"resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.4.7.tgz",
"integrity": "sha512-47qPchRCykZC03FhkYAhrvwU4xDBFIj1QPqaarj6mdM/hgUzfPHcpkHJOn3mJAufFeeAxAzeGsr5X0M4k6fLZQ==",
"engines": {
"node": ">=12"
},
"funding": {
"url": "https://dotenvx.com"
}
},
"node_modules/dunder-proto": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",
@@ -296,6 +309,50 @@
"url": "https://opencollective.com/express"
}
},
"node_modules/express-session": {
"version": "1.18.1",
"resolved": "https://registry.npmjs.org/express-session/-/express-session-1.18.1.tgz",
"integrity": "sha512-a5mtTqEaZvBCL9A9aqkrtfz+3SMDhOVUnjafjo+s7A9Txkq+SVX2DLvSp1Zrv4uCXa3lMSK3viWnh9Gg07PBUA==",
"dependencies": {
"cookie": "0.7.2",
"cookie-signature": "1.0.7",
"debug": "2.6.9",
"depd": "~2.0.0",
"on-headers": "~1.0.2",
"parseurl": "~1.3.3",
"safe-buffer": "5.2.1",
"uid-safe": "~2.1.5"
},
"engines": {
"node": ">= 0.8.0"
}
},
"node_modules/express-session/node_modules/cookie": {
"version": "0.7.2",
"resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz",
"integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/express-session/node_modules/cookie-signature": {
"version": "1.0.7",
"resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.7.tgz",
"integrity": "sha512-NXdYc3dLr47pBkpUCHtKSwIOQXLVn8dZEuywboCOJY/osA0wFSLlSawr3KN8qXJEyX66FcONTH8EIlVuK0yyFA=="
},
"node_modules/express-session/node_modules/debug": {
"version": "2.6.9",
"resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz",
"integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==",
"dependencies": {
"ms": "2.0.0"
}
},
"node_modules/express-session/node_modules/ms": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
"integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A=="
},
"node_modules/express/node_modules/debug": {
"version": "2.6.9",
"resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz",
@@ -572,6 +629,14 @@
"node": ">= 0.8"
}
},
"node_modules/on-headers": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/on-headers/-/on-headers-1.0.2.tgz",
"integrity": "sha512-pZAE+FJLoyITytdqK0U5s+FIpjN0JP3OzFi/u8Rx+EV5/W+JTWGXG8xFzevE7AjBfDqHv/8vL8qQsIhHnqRkrA==",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/parseurl": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz",
@@ -611,6 +676,14 @@
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/random-bytes": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/random-bytes/-/random-bytes-1.0.0.tgz",
"integrity": "sha512-iv7LhNVO047HzYR3InF6pUcUsPQiHTM1Qal51DcGSuZFBil1aBBWG5eHPNek7bvILMaYJ/8RU1e8w1AMdHmLQQ==",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/range-parser": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz",
@@ -816,6 +889,17 @@
"node": ">= 0.6"
}
},
"node_modules/uid-safe": {
"version": "2.1.5",
"resolved": "https://registry.npmjs.org/uid-safe/-/uid-safe-2.1.5.tgz",
"integrity": "sha512-KPHm4VL5dDXKz01UuEd88Df+KzynaohSL9fBh096KWAxSKZQDI2uBrVqtvRM4rwrIrRRKsdLNML/lnaaVSRioA==",
"dependencies": {
"random-bytes": "~1.0.0"
},
"engines": {
"node": ">= 0.8"
}
},
"node_modules/unpipe": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz",

View File

@@ -13,7 +13,9 @@
"basic-auth": "^2.0.1",
"body-parser": "^1.20.3",
"debug": "^4.4.0",
"dotenv": "^16.4.7",
"express": "^4.21.2",
"express-session": "^1.18.1",
"fs": "^0.0.1-security"
}
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.7 KiB

After

Width:  |  Height:  |  Size: 3.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 12 KiB

After

Width:  |  Height:  |  Size: 12 KiB

View File

@@ -17,11 +17,15 @@ document.addEventListener('DOMContentLoaded', function() {
const loginMessage = document.getElementById('loginMessage');
// Check if user is already logged in
if (sessionStorage.getItem('loggedIn') === 'true') {
loginContainer.style.display = 'none';
appContainer.style.display = 'block';
loadTags();
}
fetch('/check-session')
.then(response => response.json())
.then(data => {
if (data.loggedIn) {
loginContainer.style.display = 'none';
appContainer.style.display = 'block';
loadTags();
}
});
loginForm.addEventListener('submit', function(e) {
e.preventDefault();
@@ -29,15 +33,27 @@ document.addEventListener('DOMContentLoaded', function() {
const username = document.getElementById('username').value;
const password = document.getElementById('password').value;
// Simple authentication check (replace with your own logic)
if (username === 'fredrik' && password === 'apa') {
sessionStorage.setItem('loggedIn', 'true');
loginContainer.style.display = 'none';
appContainer.style.display = 'block';
loadTags();
} else {
loginMessage.textContent = 'Invalid username or password';
}
// Send credentials to the server for validation
fetch('/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Basic ' + btoa(username + ':' + password)
}
})
.then(response => {
if (response.ok) {
sessionStorage.setItem('loggedIn', 'true');
loginContainer.style.display = 'none';
appContainer.style.display = 'block';
loadTags();
} else {
loginMessage.textContent = 'Invalid username or password';
}
})
.catch(error => {
loginMessage.textContent = 'Error logging in';
});
});
document.getElementById('taskForm').addEventListener('submit', function(e) {
@@ -52,7 +68,7 @@ document.addEventListener('DOMContentLoaded', function() {
// Structure data for Org mode
const taskData = {
subject: `${subject} :${tags}:`,
subject: tags ? `${subject} :${tags}:` : subject,
description,
scheduled
};

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.2 KiB

After

Width:  |  Height:  |  Size: 3.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 249 B

After

Width:  |  Height:  |  Size: 216 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 467 B

After

Width:  |  Height:  |  Size: 396 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

After

Width:  |  Height:  |  Size: 15 KiB

View File

@@ -14,14 +14,14 @@
</head>
<body>
<div id="loginContainer" class="container">
<h1 class="center-align">Login</h1>
<h1 class="center-align">Logga in</h1>
<form id="loginForm">
<div class="input-field">
<label for="username">Username:</label>
<label for="username">Användarnamn:</label>
<input type="text" id="username" required>
</div>
<div class="input-field">
<label for="password">Password:</label>
<label for="password">Lösenord:</label>
<input type="password" id="password" required>
</div>
<button class="btn waves-effect waves-light" type="submit">Login</button>
@@ -48,7 +48,7 @@
</div>
<div class="input-field">
<label for="tags">Tags (separated by commas):</label>
<label for="tags">Taggar (separera med komma):</label>
<input type="text" id="tags" class="autocomplete">
</div>

27
routes/auth.js Normal file
View File

@@ -0,0 +1,27 @@
const express = require('express');
const basicAuth = require('basic-auth');
const router = express.Router();
router.post('/login', (req, res) => {
const user = basicAuth(req);
const username = process.env.AUTH_USERNAME;
const password = process.env.AUTH_PASSWORD;
if (user && user.name === username && user.pass === password) {
req.session.user = user.name;
res.status(200).send('Login successful');
} else {
res.status(401).send('Authentication required');
}
});
router.post('/logout', (req, res) => {
req.session.destroy((err) => {
if (err) {
return res.status(500).send('Error logging out');
}
res.status(200).send('Logout successful');
});
});
module.exports = router;

79
routes/tasks.js Normal file
View File

@@ -0,0 +1,79 @@
const express = require('express');
const fs = require('fs');
const path = require('path');
const debug = require('debug')('app');
const auth = require('../middleware/auth');
const router = express.Router();
const dataDir = '/data';
// Ensure the /data directory exists
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([]));
}
// Protect the /add-task endpoint with authentication
router.post('/add-task', auth, async (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');
try {
await fs.promises.appendFile(filePath, orgFormattedData);
res.send({ message: 'Task added successfully!' });
} catch (err) {
debug('Error writing to file:', err);
res.status(500).send('Error writing to file.');
}
});
// Endpoint to save tags
router.post('/save-tags', auth, async (req, res) => {
const { tags } = req.body;
const filePath = path.join(dataDir, 'tags.json');
try {
await fs.promises.writeFile(filePath, JSON.stringify(tags));
res.send({ message: 'Tags saved successfully!' });
} catch (err) {
debug('Error saving tags:', err);
res.status(500).send('Error saving tags.');
}
});
// Endpoint to retrieve tags
router.get('/get-tags', auth, async (req, res) => {
const filePath = path.join(dataDir, 'tags.json');
try {
const data = await fs.promises.readFile(filePath);
const tags = JSON.parse(data);
res.send(tags);
} catch (err) {
debug('Error retrieving tags:', err);
res.status(500).send('Error retrieving tags.');
}
});
module.exports = router;

105
server.js
View File

@@ -1,9 +1,10 @@
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 session = require('express-session');
const debug = require('debug')('app');
const tasksRouter = require('./routes/tasks');
const authRouter = require('./routes/auth');
const app = express();
const port = 3044;
@@ -11,96 +12,16 @@ 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 });
}
// Configure session middleware
app.use(session({
secret: process.env.SESSION_SECRET || 'default_secret', // Use a strong secret in production
resave: false,
saveUninitialized: true,
cookie: { secure: false } // Set to true if using HTTPS
}));
// 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.use('/', authRouter);
app.listen(port, () => {
debug(`Server running at http://localhost:${port}`);