28 Commits

Author SHA1 Message Date
e74871bf94 Add SQLite session store and configure session middleware 2025-01-29 22:13:07 +01:00
a9dfb8d54d Enhance service worker with update handling and improve task scheduling format 2025-01-29 21:57:04 +01:00
502938b8cf Add timepicker initialization and combine scheduled date with time input 2025-01-29 21:43:06 +01:00
5413323a3c Refactor task formatting and extend session cookie expiration to one month 2025-01-29 21:31:11 +01:00
dfa616fc52 Update form placeholders and button text for improved clarity and localization 2025-01-26 19:16:09 +01:00
38fbf13fd7 Hide navigation and sidenav elements by default in the CSS 2025-01-25 20:49:50 +01:00
b39f0e7339 Set default date for datepicker to tomorrow and update navigation visibility 2025-01-25 12:05:33 +01:00
1122de442b Refactor navigation and form elements for improved usability and localization 2025-01-25 11:21:26 +01:00
09772d859d Fixar inloggningen. Menyn fortfarande ett problem 2025-01-25 10:13:59 +01:00
05d6cba8ef Fix #20 2025-01-25 09:04:25 +01:00
6864cfa14e Tar bort rest av basic auth 2025-01-25 08:38:54 +01:00
6159fc4ee8 .vscode 2025-01-25 08:23:05 +01:00
6520dcb78c Lägger till .vscode för att dölja ikoner etc. 2025-01-25 08:22:55 +01:00
c993848278 Merge pull request 'Längre intervall på healthcheck' (#17) from reset into main
Reviewed-on: #17
2025-01-24 23:17:55 +01:00
87feaa9880 Längre intervall på healthcheck 2025-01-24 23:17:02 +01:00
23a39247a1 Implement session-based authentication and add logout functionality
Fix #15
2025-01-24 22:02:54 +01:00
da2f568acf Implement server-side authentication and update login UI texts 2025-01-24 21:54:05 +01:00
1edcefbd64 Ta bort kolon vid tomma taggar.
Fixar #12
2025-01-24 21:40:16 +01:00
276587f1dc Merge pull request 'cleanup' (#11) from cleanup into main
Reviewed-on: #11
2025-01-24 21:34:53 +01:00
adbe5fcfb4 Lägg till hälsokontroll för tjänsten i docker-compose, fixes #8 2025-01-24 21:33:09 +01:00
a58da5398c Lägg till hälsokontroll för tjänsten i docker-compose 2025-01-24 21:30:19 +01:00
51656c0ee4 Merge pull request 'Lägg till autentisering och loggning, refaktorisera uppgifter till router' (#9) from cleanup into main
Reviewed-on: #9
2025-01-24 21:26:50 +01:00
e091da93e9 Lägg till autentisering och loggning, refaktorisera uppgifter till router 2025-01-24 21:26:06 +01:00
70365715fe Uppdaterar iconerna 2025-01-24 21:08:18 +01:00
6c72c02896 Tagghantering, fix #3 2025-01-24 20:54:12 +01:00
eb5adae406 Vi har morgondagen som förvalt datum istället för idag 2025-01-24 18:30:01 +01:00
892c20dfae Ny inloggning, formulär innnan. Fixes #7 2025-01-24 18:26:53 +01:00
d75a0882dd Fixes #5 2025-01-24 18:22:05 +01:00
20 changed files with 2424 additions and 146 deletions

9
.vscode/settings.json vendored Normal file
View File

@@ -0,0 +1,9 @@
{
"files.exclude": {
"**/*.png": true,
"**/*.jpg": true,
"**/*.gif": true,
"**/*.svg": true,
"**/*.ico": true
}
}

View File

@@ -16,5 +16,8 @@ COPY . .
# Expose the port the app runs on
EXPOSE 3044
# Set the DEBUG environment variable
ENV DEBUG=app
# Command to run the application
CMD ["node", "server.js"]

View File

@@ -9,6 +9,17 @@ services:
volumes:
- /srv/swarm/org-todo-pwa/data:/data
user: "1000:1000"
environment:
- DEBUG=app
- AUTH_USERNAME=fredrik
- AUTH_PASSWORD=apa
- SESSION_SECRET=superheimlich # Add your session secret key
- NODE_ENV=production # Ensure the environment is set to production
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:3044"]
interval: 5m
timeout: 10s
retries: 3
deploy:
labels:
- "traefik.enable=true"
@@ -16,3 +27,4 @@ services:
- "traefik.http.routers.plan.tls.certresolver=myhttpchallenge"
- "traefik.http.routers.plan.rule=Host(`todo.casablanca.wahlberg.se`)"
- "traefik.http.routers.plan.entrypoints=websecure"

16
logger.js Normal file
View File

@@ -0,0 +1,16 @@
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;

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;

1864
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -12,7 +12,13 @@
"dependencies": {
"basic-auth": "^2.0.1",
"body-parser": "^1.20.3",
"connect-sqlite3": "^0.9.15",
"cookie-parser": "^1.4.7",
"debug": "^4.4.0",
"dotenv": "^16.4.7",
"express": "^4.21.2",
"fs": "^0.0.1-security"
"express-session": "^1.18.1",
"fs": "^0.0.1-security",
"winston": "^3.17.0"
}
}

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

@@ -3,6 +3,24 @@ if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/service-worker.js')
.then(registration => {
console.log('ServiceWorker registration successful with scope: ', registration.scope);
registration.onupdatefound = () => {
const installingWorker = registration.installing;
installingWorker.onstatechange = () => {
if (installingWorker.state === 'installed') {
if (navigator.serviceWorker.controller) {
// New update available
console.log('New content is available; please refresh.');
if (confirm('New version available. Do you want to update?')) {
window.location.reload();
}
} else {
// Content is cached for offline use
console.log('Content is cached for offline use.');
}
}
};
};
})
.catch(error => {
console.log('ServiceWorker registration failed: ', error);
@@ -10,34 +28,210 @@ if ('serviceWorker' in navigator) {
});
}
document.getElementById('taskForm').addEventListener('submit', function(e) {
document.addEventListener('DOMContentLoaded', function() {
const loginForm = document.getElementById('loginForm');
const loginContainer = document.getElementById('loginContainer');
const appContainer = document.getElementById('appContainer');
const loginMessage = document.getElementById('loginMessage');
const logoutButton = document.getElementById('logoutButton');
const taskForm = document.getElementById('taskForm');
const sidenav = document.querySelector('.sidenav');
if (!loginForm || !loginContainer || !appContainer || !loginMessage || !logoutButton || !taskForm || !sidenav) {
console.error('One or more elements are missing in the DOM');
return;
}
// Initialize Materialize components
M.Sidenav.init(sidenav);
// Calculate tomorrow's date
const today = new Date();
const tomorrow = new Date(today);
tomorrow.setDate(today.getDate() + 1);
// Initialize datepicker with tomorrow as the default date
M.Datepicker.init(document.querySelectorAll('.datepicker'), {
format: 'yyyy-mm-dd',
defaultDate: tomorrow,
setDefaultDate: true,
firstDay: 1
});
// Initialize timepicker
M.Timepicker.init(document.querySelectorAll('.timepicker'), {
twelveHour: false // Use 24-hour format
});
// Check if user is already logged in
fetch('/check-session')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
if (data.loggedIn) {
loginContainer.style.display = 'none';
appContainer.style.display = 'block';
loadTags();
} else {
loginContainer.style.display = 'block';
appContainer.style.display = 'none';
}
})
.catch(error => {
console.error('Error checking session:', error);
loginMessage.textContent = 'Error checking session. Please try again later.';
});
loginForm.addEventListener('submit', function(e) {
e.preventDefault();
const username = document.getElementById('username').value;
const password = document.getElementById('password').value;
// 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';
});
});
logoutButton.addEventListener('click', function() {
fetch('/logout', {
method: 'POST'
})
.then(response => {
if (response.ok) {
sessionStorage.removeItem('loggedIn');
loginContainer.style.display = 'block';
appContainer.style.display = 'none';
}
})
.catch(error => {
console.error('Error logging out:', error);
});
});
taskForm.addEventListener('submit', async function(e) {
e.preventDefault();
// Get form values
const subject = document.getElementById('subject').value;
const description = document.getElementById('description').value;
const scheduled = document.getElementById('scheduled').value;
const time = document.getElementById('time').value;
const tagsInput = document.getElementById('tags').value;
const tags = tagsInput.split(',').map(tag => tag.trim()).filter(tag => tag).join(':');
// Combine scheduled date and time if time is provided
const scheduledDateTime = time ? `${scheduled}T${time}:00` : scheduled;
// Structure data for Org mode
const taskData = {
subject,
subject: tags ? `${subject} :${tags}:` : subject,
description,
scheduled
scheduled: scheduledDateTime
};
// Send data to backend using fetch
fetch('/add-task', {
// Save tags to server
const savedTags = JSON.parse(localStorage.getItem('tags')) || [];
const newTags = tagsInput.split(',').map(tag => tag.trim()).filter(tag => tag && !savedTags.includes(tag));
const allTags = [...savedTags, ...newTags];
localStorage.setItem('tags', JSON.stringify(allTags));
fetch('/save-tags', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ tags: allTags })
}).then(() => {
loadTags(); // Force refresh tags after saving
});
// Save task to server or IndexedDB if offline
if (navigator.onLine) {
try {
const response = await fetch('/add-task', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(taskData)
})
.then(response => response.json())
.then(data => {
});
const data = await response.json();
document.getElementById('responseMessage').textContent = data.message;
taskForm.reset(); // Reset the form after saving the task
} catch (error) {
if (error.status === 401) {
sessionStorage.removeItem('loggedIn');
loginContainer.style.display = 'block';
appContainer.style.display = 'none';
} else {
document.getElementById('responseMessage').textContent = "Error saving task!";
}
}
} else {
try {
// Save task to IndexedDB
const db = await idb.openDB('org-todo-pwa', 1, {
upgrade(db) {
db.createObjectStore('tasks', { keyPath: 'id', autoIncrement: true });
}
});
await db.add('tasks', taskData);
document.getElementById('responseMessage').textContent = "Task saved offline!";
taskForm.reset(); // Reset the form after saving the task
} catch (error) {
document.getElementById('responseMessage').textContent = "Error saving task offline!";
console.error('Error saving task offline:', error);
}
}
});
// Load tags from server and initialize autocomplete
function loadTags() {
fetch('/get-tags')
.then(response => response.json())
.then(tags => {
localStorage.setItem('tags', JSON.stringify(tags));
const autocompleteData = {};
tags.forEach(tag => {
autocompleteData[tag] = null; // Materialize autocomplete requires a key-value pair
});
const tagsInput = document.getElementById('tags');
M.Autocomplete.init(tagsInput, {
data: autocompleteData,
onAutocomplete: function(selectedTag) {
const currentTags = tagsInput.value.split(',').map(tag => tag.trim()).filter(tag => tag);
if (!currentTags.includes(selectedTag)) {
currentTags.push(selectedTag);
tagsInput.value = currentTags.join(', ');
}
}
});
})
.catch(error => {
document.getElementById('responseMessage').textContent = "Error saving task!";
console.error('Error loading tags:', error);
});
}
});

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

@@ -13,41 +13,62 @@
<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
</head>
<body>
<div class="container">
<div id="loginContainer" class="container">
<h1 class="center-align">Logga in</h1>
<form id="loginForm">
<div class="input-field">
<input type="text" id="username" placeholder="Användarnamn" required>
<label for="username">Användarnamn</label>
</div>
<div class="input-field">
<input type="password" id="password" placeholder="Lösenord" required>
<label for="password">Lösenord</label>
</div>
<button class="btn waves-effect waves-light" type="submit">Login</button>
</form>
<p id="loginMessage" class="center-align"></p>
</div>
<div id="appContainer" class="container" style="display:none;">
<h1 class="center-align">TODO</h1>
<nav>
<div class="nav-wrapper">
<a href="#" class="brand-logo">Menu</a>
<a href="#" data-target="mobile-demo" class="sidenav-trigger"><i class="material-icons">menu</i></a>
</div>
</nav>
<ul class="sidenav" id="mobile-demo">
<li><a id="logoutButton">Logout</a></li>
</ul>
<form id="taskForm">
<div class="input-field">
<label for="subject">Uppgift:</label>
<input type="text" id="subject" required>
<input type="text" id="subject" placeholder="Vad ska göras?" required autocomplete="off">
<label for="subject">Uppgift</label>
</div>
<div class="input-field">
<label for="description">Beskrivning:</label>
<textarea id="description" class="materialize-textarea"></textarea>
<textarea id="description" class="materialize-textarea" placeholder="Beskrivning"></textarea>
<label for="description">Mer detaljer</label>
</div>
<div class="input-field">
<label for="scheduled">Datum:</label>
<input type="date" id="scheduled" lang="sv-SE" required>
<input type="text" id="scheduled" class="datepicker" required>
<label for="scheduled">Planerat datum</label>
</div>
<button class="btn waves-effect waves-light" type="submit">Spara</button>
<div class="input-field">
<input type="text" id="time" class="timepicker">
<label for="time">Tid (valfritt)</label>
</div>
<div class="input-field">
<input type="text" id="tags" placeholder="Taggar">
<label for="tags">Taggar</label>
</div>
<button class="btn waves-effect waves-light" type="submit">Spara uppgift</button>
<p id="responseMessage"></p>
</form>
<p id="responseMessage" class="center-align"></p>
</div>
<script src="app.js"></script>
<script>
// Set today's date as the default for the date input
const today = new Date().toISOString().split('T')[0];
document.getElementById('scheduled').value = today;
// Initialize flatpickr with Swedish locale and Monday as the first day of the week
flatpickr("#scheduled", {
//locale: "sv-SE", // Set Swedish locale
weekNumbers: true, // Show week numbers
firstDayOfWeek: 1 // Start weeks on Monday
});
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<script src="app.js"></script>
</body>
</html>

View File

@@ -1,23 +1,51 @@
self.addEventListener('install', (event) => {
event.waitUntil(
caches.open('task-manager-cache').then((cache) => {
return cache.addAll([
const CACHE_NAME = 'org-todo-pwa-cache-v1';
const urlsToCache = [
'/',
'/index.html',
'/style.css',
'/app.js',
'/manifest.json',
'/icons/icon-192x192.png',
'/icons/icon-512x512.png'
]);
'/manifest.json'
];
self.addEventListener('install', event => {
event.waitUntil(
caches.open(CACHE_NAME)
.then(cache => {
return cache.addAll(urlsToCache);
})
);
self.skipWaiting(); // Force the waiting service worker to become the active service worker
});
self.addEventListener('activate', event => {
event.waitUntil(
caches.keys().then(cacheNames => {
return Promise.all(
cacheNames.map(cacheName => {
if (cacheName !== CACHE_NAME) {
return caches.delete(cacheName);
}
})
);
})
);
self.clients.claim(); // Take control of all clients immediately
});
self.addEventListener('fetch', event => {
event.respondWith(
caches.match(event.request)
.then(response => {
if (response) {
return response;
}
return fetch(event.request);
})
);
});
self.addEventListener('fetch', (event) => {
event.respondWith(
caches.match(event.request).then((cachedResponse) => {
return cachedResponse || fetch(event.request);
})
);
self.addEventListener('message', event => {
if (event.data === 'skipWaiting') {
self.skipWaiting();
}
});

View File

@@ -1,11 +1,5 @@
body {
font-family: Arial, sans-serif;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background-color: #f4f4f9;
}
.container {
@@ -22,5 +16,47 @@ h1 {
#responseMessage {
text-align: center;
color: green;
color: green;}
.menu {
position: relative;
display: inline-block;
}
.hamburger {
font-size: 24px;
cursor: pointer;
background: none;
border: none;
}
.menu-content {
display: none;
position: absolute;
background-color: #f9f9f9;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
z-index: 1;
}
.menu-content button {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
background: none;
border: none;
width: 100%;
text-align: left;
}
.menu-content button:hover {
background-color: #f1f1f1;
}
.menu.show .menu-content {
display: block;
}
nav, .sidenav {
display: none;
}

36
routes/auth.js Normal file
View File

@@ -0,0 +1,36 @@
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.clearCookie('connect.sid');
res.status(200).send('Logout successful');
});
});
router.get('/check-session', (req, res) => {
if (req.session.user) {
res.json({ loggedIn: true });
} else {
res.json({ loggedIn: false });
}
});
module.exports = router;

93
routes/tasks.js Normal file
View File

@@ -0,0 +1,93 @@
const express = require('express');
const fs = require('fs');
const path = require('path');
const auth = require('../middleware/auth');
const logger = require('../logger');
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(/\..+/, '');
// Format the scheduled date and time for Org mode
const scheduledDate = new Date(scheduled);
const dayNames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
const dayName = dayNames[scheduledDate.getUTCDay()];
let formattedScheduled;
if (scheduledDate.getUTCHours() === 0 && scheduledDate.getUTCMinutes() === 0) {
// No time provided, format without time
formattedScheduled = `<${scheduledDate.getUTCFullYear()}-${String(scheduledDate.getUTCMonth() + 1).padStart(2, '0')}-${String(scheduledDate.getUTCDate()).padStart(2, '0')} ${dayName}>`;
} else {
// Time provided, format with time
formattedScheduled = `<${scheduledDate.getUTCFullYear()}-${String(scheduledDate.getUTCMonth() + 1).padStart(2, '0')}-${String(scheduledDate.getUTCDate()).padStart(2, '0')} ${dayName} ${String(scheduledDate.getUTCHours()).padStart(2, '0')}:${String(scheduledDate.getUTCMinutes()).padStart(2, '0')}>`;
}
let orgFormattedData = `* TODO ${subject}
SCHEDULED: ${formattedScheduled}
:LOGBOOK:
- State "TODO" from "TODO" [${currentDateTime}]
:END:
`;
if (description) {
orgFormattedData = `* TODO ${subject}
${description}
SCHEDULED: ${formattedScheduled}
:LOGBOOK:
- State "TODO" from "TODO" [${currentDateTime}]
:END:
`;
}
const filePath = path.join(dataDir, 'tasks.org');
try {
await fs.promises.appendFile(filePath, orgFormattedData);
res.json({ message: 'Task added successfully' });
} catch (error) {
logger.error('Error writing to tasks.org file:', error);
res.status(500).json({ message: 'Error adding task' });
}
});
// 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, 'utf-8');
const tags = JSON.parse(data);
res.json(tags);
} catch (err) {
logger.error('Error retrieving tags:', err);
res.status(500).json({ error: 'Error retrieving tags' });
}
});
module.exports = router;

View File

@@ -1,68 +1,41 @@
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 cookieParser = require('cookie-parser');
const SQLiteStore = require('connect-sqlite3')(session);
const debug = require('debug')('app');
const tasksRouter = require('./routes/tasks');
const authRouter = require('./routes/auth');
const authMiddleware = require('./middleware/auth');
const app = express();
const port = 3044;
app.use(bodyParser.json());
app.use(cookieParser());
app.use(express.static('public'));
// Ensure the /data directory exists
const dataDir = path.join('/data');
if (!fs.existsSync(dataDir)) {
fs.mkdirSync(dataDir, { recursive: true });
}
// 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.');
// Configure session middleware with SQLite store
app.use(session({
secret: process.env.SESSION_SECRET || 'default_secret', // Use a strong secret in production
resave: false,
saveUninitialized: false,
store: new SQLiteStore({
db: 'sessions.sqlite',
dir: '/data',
ttl: 30 * 24 * 60 * 60 // 1 month
}),
cookie: {
//secure: process.env.NODE_ENV === 'production', // Ensure cookies are only sent over HTTPS in production
secure: false,
maxAge: 30 * 24 * 60 * 60 * 1000 // 1 month
}
};
}));
// 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) {
return res.status(500).send('Error writing to file.');
}
res.send({ message: 'Task added successfully!' });
});
});
app.use('/', authRouter);
app.use('/', authMiddleware, tasksRouter);
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
debug(`Server running at http://localhost:${port}`);
});