Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 90d7f2a5d2 |
9
.vscode/settings.json
vendored
9
.vscode/settings.json
vendored
@@ -1,9 +0,0 @@
|
|||||||
{
|
|
||||||
"files.exclude": {
|
|
||||||
"**/*.png": true,
|
|
||||||
"**/*.jpg": true,
|
|
||||||
"**/*.gif": true,
|
|
||||||
"**/*.svg": true,
|
|
||||||
"**/*.ico": true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
13
Dockerfile
13
Dockerfile
@@ -1,24 +1,23 @@
|
|||||||
# Use the official Node.js image as the base image
|
# Use the official Node.js image as the base image
|
||||||
FROM node:14
|
FROM node:14
|
||||||
|
|
||||||
# Create app directory
|
# Set the working directory
|
||||||
WORKDIR /usr/src/app
|
WORKDIR /usr/src/app
|
||||||
|
|
||||||
# Install app dependencies
|
# Copy package.json and package-lock.json
|
||||||
COPY package*.json ./
|
COPY package*.json ./
|
||||||
|
|
||||||
|
# Install dependencies
|
||||||
RUN npm install
|
RUN npm install
|
||||||
|
|
||||||
# Copy app source code
|
# Copy the rest of the application code
|
||||||
COPY . .
|
COPY . .
|
||||||
|
|
||||||
# Run the build script to update the version number
|
|
||||||
RUN node build.js
|
|
||||||
|
|
||||||
# Expose the port the app runs on
|
# Expose the port the app runs on
|
||||||
EXPOSE 3044
|
EXPOSE 3044
|
||||||
|
|
||||||
# Set the DEBUG environment variable
|
# Set the DEBUG environment variable
|
||||||
ENV DEBUG=app
|
ENV DEBUG=app
|
||||||
|
|
||||||
# Command to run the app
|
# Command to run the application
|
||||||
CMD ["node", "server.js"]
|
CMD ["node", "server.js"]
|
||||||
17
build.js
17
build.js
@@ -1,17 +0,0 @@
|
|||||||
const fs = require('fs');
|
|
||||||
const path = require('path');
|
|
||||||
|
|
||||||
// Generate version number with timestamp
|
|
||||||
const version = new Date().toISOString().replace(/[-:.]/g, '').slice(0, 15);
|
|
||||||
|
|
||||||
// Read the HTML file
|
|
||||||
const indexPath = path.join(__dirname, 'public', 'index.html');
|
|
||||||
let indexHtml = fs.readFileSync(indexPath, 'utf8');
|
|
||||||
|
|
||||||
// Replace the version placeholder with the generated version number
|
|
||||||
indexHtml = indexHtml.replace(/<!-- VERSION_PLACEHOLDER -->/g, `Version: ${version}`);
|
|
||||||
|
|
||||||
// Write the updated HTML back to the file
|
|
||||||
fs.writeFileSync(indexPath, indexHtml);
|
|
||||||
|
|
||||||
console.log(`Version number updated to: ${version}`);
|
|
||||||
@@ -2,7 +2,7 @@ version: '3.8'
|
|||||||
|
|
||||||
services:
|
services:
|
||||||
org-todo-pwa:
|
org-todo-pwa:
|
||||||
container_name: org-todo-pwa
|
image: org-todo-pwa
|
||||||
build: .
|
build: .
|
||||||
ports:
|
ports:
|
||||||
- "3044:3044"
|
- "3044:3044"
|
||||||
@@ -13,8 +13,6 @@ services:
|
|||||||
- DEBUG=app
|
- DEBUG=app
|
||||||
- AUTH_USERNAME=fredrik
|
- AUTH_USERNAME=fredrik
|
||||||
- AUTH_PASSWORD=apa
|
- AUTH_PASSWORD=apa
|
||||||
- SESSION_SECRET=superheimlich # Add your session secret key
|
|
||||||
- NODE_ENV=production # Ensure the environment is set to production
|
|
||||||
healthcheck:
|
healthcheck:
|
||||||
test: ["CMD", "curl", "-f", "http://localhost:3044"]
|
test: ["CMD", "curl", "-f", "http://localhost:3044"]
|
||||||
interval: 5m
|
interval: 5m
|
||||||
@@ -26,4 +24,5 @@ services:
|
|||||||
- "traefik.http.routers.plan.tls=true"
|
- "traefik.http.routers.plan.tls=true"
|
||||||
- "traefik.http.routers.plan.tls.certresolver=myhttpchallenge"
|
- "traefik.http.routers.plan.tls.certresolver=myhttpchallenge"
|
||||||
- "traefik.http.routers.plan.rule=Host(`todo.casablanca.wahlberg.se`)"
|
- "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
BIN
favicon.ico
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 66 KiB |
@@ -4,13 +4,13 @@ const logger = createLogger({
|
|||||||
level: 'info',
|
level: 'info',
|
||||||
format: format.combine(
|
format: format.combine(
|
||||||
format.timestamp(),
|
format.timestamp(),
|
||||||
format.printf(info => `${info.timestamp} ${info.level}: ${info.message}`)
|
format.json()
|
||||||
),
|
),
|
||||||
transports: [
|
transports: [
|
||||||
new transports.Console(),
|
new transports.Console(),
|
||||||
new transports.File({ filename: '/data/app.log' })
|
new transports.File({ filename: 'app.log' })
|
||||||
]
|
]
|
||||||
});
|
});
|
||||||
|
|
||||||
module.exports = logger;
|
module.exports = logger;
|
||||||
|
|
||||||
|
|||||||
@@ -1,12 +1,15 @@
|
|||||||
const basicAuth = require('basic-auth');
|
const basicAuth = require('basic-auth');
|
||||||
const logger = require('../logger');
|
|
||||||
|
|
||||||
const auth = (req, res, next) => {
|
const auth = (req, res, next) => {
|
||||||
if (req.session && req.session.user) {
|
const user = basicAuth(req);
|
||||||
|
const username = process.env.AUTH_USERNAME; // Use environment variables
|
||||||
|
const password = process.env.AUTH_PASSWORD; // Use environment variables
|
||||||
|
|
||||||
|
if (user && user.name === username && user.pass === password) {
|
||||||
return next();
|
return next();
|
||||||
} else {
|
} else {
|
||||||
res.status(401).send('Authentication required.');
|
res.set('WWW-Authenticate', 'Basic realm="401"');
|
||||||
logger.error(`Unauthorized access attempted from IP: ${req.ip}`);
|
return res.status(401).send('Authentication required.');
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
1546
package-lock.json
generated
1546
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
20
package.json
20
package.json
@@ -1,25 +1,21 @@
|
|||||||
{
|
{
|
||||||
"name": "org-todo-pwa",
|
"name": "pwa",
|
||||||
"version": "1.0.0",
|
"version": "1.0.0",
|
||||||
"description": "",
|
"description": "",
|
||||||
"main": "main.js",
|
"main": "app.js",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"test": "echo \"Error: no test specified\" && exit 1",
|
"test": "echo \"Error: no test specified\" && exit 1"
|
||||||
"build": "node build.js"
|
|
||||||
},
|
},
|
||||||
"keywords": [],
|
"keywords": [],
|
||||||
"author": "",
|
"author": "",
|
||||||
"license": "ISC",
|
"license": "ISC",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"basic-auth": "^2.0.1",
|
"basic-auth": "^2.0.1",
|
||||||
"body-parser": "^1.19.0",
|
"body-parser": "^1.20.3",
|
||||||
"connect-sqlite3": "^0.9.11",
|
"debug": "^4.4.0",
|
||||||
"cookie-parser": "^1.4.5",
|
"dotenv": "^16.4.7",
|
||||||
"debug": "^4.3.1",
|
"express": "^4.21.2",
|
||||||
"dotenv": "^8.2.0",
|
|
||||||
"express": "^4.17.1",
|
|
||||||
"express-session": "^1.17.1",
|
|
||||||
"fs": "^0.0.1-security",
|
"fs": "^0.0.1-security",
|
||||||
"winston": "^3.17.0"
|
"winston": "^3.17.0"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
144
public/app.js
Normal file
144
public/app.js
Normal file
@@ -0,0 +1,144 @@
|
|||||||
|
if ('serviceWorker' in navigator) {
|
||||||
|
window.addEventListener('load', () => {
|
||||||
|
navigator.serviceWorker.register('/service-worker.js')
|
||||||
|
.then(registration => {
|
||||||
|
console.log('ServiceWorker registration successful with scope: ', registration.scope);
|
||||||
|
})
|
||||||
|
.catch(error => {
|
||||||
|
console.log('ServiceWorker registration failed: ', error);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
document.addEventListener('DOMContentLoaded', function() {
|
||||||
|
const loginForm = document.getElementById('loginForm');
|
||||||
|
const loginContainer = document.getElementById('loginContainer');
|
||||||
|
const appContainer = document.getElementById('appContainer');
|
||||||
|
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();
|
||||||
|
}
|
||||||
|
|
||||||
|
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';
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
document.getElementById('taskForm').addEventListener('submit', 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 tagsInput = document.getElementById('tags').value;
|
||||||
|
const tags = tagsInput.split(',').map(tag => tag.trim()).filter(tag => tag).join(':');
|
||||||
|
|
||||||
|
// Structure data for Org mode
|
||||||
|
const taskData = {
|
||||||
|
subject: tags ? `${subject} :${tags}:` : subject,
|
||||||
|
description,
|
||||||
|
scheduled
|
||||||
|
};
|
||||||
|
|
||||||
|
// 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
|
||||||
|
});
|
||||||
|
|
||||||
|
// Send data to backend using fetch
|
||||||
|
fetch('/add-task', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
},
|
||||||
|
body: JSON.stringify(taskData)
|
||||||
|
})
|
||||||
|
.then(response => response.json())
|
||||||
|
.then(data => {
|
||||||
|
document.getElementById('responseMessage').textContent = data.message;
|
||||||
|
})
|
||||||
|
.catch(error => {
|
||||||
|
document.getElementById('responseMessage').textContent = "Error saving task!";
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// Set tomorrow's date as the default for the date input
|
||||||
|
const today = new Date();
|
||||||
|
const tomorrow = new Date(today);
|
||||||
|
tomorrow.setDate(today.getDate() + 1);
|
||||||
|
const tomorrowString = tomorrow.toISOString().split('T')[0];
|
||||||
|
document.getElementById('scheduled').value = tomorrowString;
|
||||||
|
|
||||||
|
// Initialize flatpickr with Swedish locale and Monday as the first day of the week
|
||||||
|
flatpickr("#scheduled", {
|
||||||
|
weekNumbers: true, // Show week numbers
|
||||||
|
firstDayOfWeek: 1 // Start weeks on Monday
|
||||||
|
});
|
||||||
|
|
||||||
|
// 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 => {
|
||||||
|
console.error('Error loading tags:', error);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -1,72 +0,0 @@
|
|||||||
body {
|
|
||||||
font-family: Arial, sans-serif;
|
|
||||||
}
|
|
||||||
|
|
||||||
.container {
|
|
||||||
width: 300px;
|
|
||||||
padding: 20px;
|
|
||||||
background-color: #fff;
|
|
||||||
border-radius: 8px;
|
|
||||||
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
|
|
||||||
}
|
|
||||||
|
|
||||||
h1 {
|
|
||||||
text-align: center;
|
|
||||||
}
|
|
||||||
|
|
||||||
#responseMessage {
|
|
||||||
text-align: center;
|
|
||||||
color: green;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Add styles for the version number */
|
|
||||||
#version {
|
|
||||||
color: #888; /* Subtle gray color */
|
|
||||||
font-size: 0.8em; /* Smaller font size */
|
|
||||||
text-align: right; /* Align text to the right */
|
|
||||||
margin: 0; /* Remove any default margin */
|
|
||||||
padding: 0; /* Remove any default padding */
|
|
||||||
}
|
|
||||||
|
|
||||||
.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;
|
|
||||||
}
|
|
||||||
@@ -1,24 +1,28 @@
|
|||||||
<!DOCTYPE html>
|
<!DOCTYPE html>
|
||||||
<html lang="sv">
|
<html lang="sv-SE">
|
||||||
<head>
|
<head>
|
||||||
<meta charset="UTF-8">
|
<meta charset="UTF-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
<title>Fredriks todos</title>
|
<title>Fredriks todos</title>
|
||||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
|
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
|
||||||
<link rel="stylesheet" href="css/style.css">
|
<link rel="stylesheet" href="style.css">
|
||||||
<link rel="manifest" href="manifest.json">
|
<link rel="manifest" href="manifest.json" />
|
||||||
|
|
||||||
|
<!-- Flatpickr for dates -->
|
||||||
|
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
|
||||||
|
<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div id="loginContainer" class="container">
|
<div id="loginContainer" class="container">
|
||||||
<h1 class="center-align">Logga in</h1>
|
<h1 class="center-align">Logga in</h1>
|
||||||
<form id="loginForm">
|
<form id="loginForm">
|
||||||
<div class="input-field">
|
<div class="input-field">
|
||||||
<input type="text" id="username" placeholder="Användarnamn" required>
|
<label for="username">Användarnamn:</label>
|
||||||
<label for="username">Användarnamn</label>
|
<input type="text" id="username" required>
|
||||||
</div>
|
</div>
|
||||||
<div class="input-field">
|
<div class="input-field">
|
||||||
<input type="password" id="password" placeholder="Lösenord" required>
|
<label for="password">Lösenord:</label>
|
||||||
<label for="password">Lösenord</label>
|
<input type="password" id="password" required>
|
||||||
</div>
|
</div>
|
||||||
<button class="btn waves-effect waves-light" type="submit">Login</button>
|
<button class="btn waves-effect waves-light" type="submit">Login</button>
|
||||||
</form>
|
</form>
|
||||||
@@ -27,49 +31,43 @@
|
|||||||
|
|
||||||
<div id="appContainer" class="container" style="display:none;">
|
<div id="appContainer" class="container" style="display:none;">
|
||||||
<h1 class="center-align">TODO</h1>
|
<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">
|
<form id="taskForm">
|
||||||
<div class="input-field">
|
<div class="input-field">
|
||||||
<input type="text" id="subject" placeholder="Vad ska göras?" required autocomplete="off">
|
<label for="subject">Uppgift:</label>
|
||||||
<label for="subject">Uppgift</label>
|
<input type="text" id="subject" required>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="input-field">
|
<div class="input-field">
|
||||||
<textarea id="description" class="materialize-textarea" placeholder="Beskrivning"></textarea>
|
<label for="description">Beskrivning:</label>
|
||||||
<label for="description">Mer detaljer</label>
|
<textarea id="description" class="materialize-textarea"></textarea>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="input-field">
|
<div class="input-field">
|
||||||
<input type="text" id="scheduled" class="datepicker" required>
|
<label for="scheduled">Datum:</label>
|
||||||
<label for="scheduled">Planerat datum</label>
|
<input type="date" id="scheduled" lang="sv-SE" required>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="input-field">
|
<div class="input-field">
|
||||||
<input type="text" id="time" class="timepicker">
|
<label for="tags">Taggar (separera med komma):</label>
|
||||||
<label for="time">Tid (valfritt)</label>
|
<input type="text" id="tags" class="autocomplete">
|
||||||
</div>
|
</div>
|
||||||
<div class="input-field">
|
|
||||||
<input type="text" id="tags" placeholder="Taggar" autocomplete="off">
|
<button class="btn waves-effect waves-light" type="submit">Spara</button>
|
||||||
<label for="tags">Taggar</label>
|
|
||||||
</div>
|
|
||||||
<button class="btn waves-effect waves-light" type="submit">Spara uppgift</button>
|
|
||||||
<p id="responseMessage"></p>
|
|
||||||
<p id="version"><!-- VERSION_PLACEHOLDER --></p>
|
|
||||||
</form>
|
</form>
|
||||||
|
<p id="responseMessage" class="center-align"></p>
|
||||||
</div>
|
</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", {
|
||||||
|
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="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
|
||||||
<script src="js/auth.js" type="module"></script>
|
|
||||||
<script src="js/tasks.js" type="module"></script>
|
|
||||||
<script src="js/tags.js" type="module"></script>
|
|
||||||
<script src="js/utils.js" type="module"></script>
|
|
||||||
<script src="js/main.js" type="module"></script>
|
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -1,25 +0,0 @@
|
|||||||
export function checkSession() {
|
|
||||||
return fetch('/check-session')
|
|
||||||
.then(response => {
|
|
||||||
if (!response.ok) {
|
|
||||||
throw new Error('Network response was not ok');
|
|
||||||
}
|
|
||||||
return response.json();
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export function login(username, password) {
|
|
||||||
return fetch('/login', {
|
|
||||||
method: 'POST',
|
|
||||||
headers: {
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
'Authorization': 'Basic ' + btoa(username + ':' + password)
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export function logout() {
|
|
||||||
return fetch('/logout', {
|
|
||||||
method: 'POST'
|
|
||||||
});
|
|
||||||
}
|
|
||||||
@@ -1,218 +0,0 @@
|
|||||||
import { checkSession, login, logout } from './auth.js';
|
|
||||||
import { saveTask } from './tasks.js';
|
|
||||||
import { saveTags, loadTags } from './tags.js';
|
|
||||||
import { idb } from './utils.js';
|
|
||||||
|
|
||||||
if ('serviceWorker' in navigator) {
|
|
||||||
window.addEventListener('load', () => {
|
|
||||||
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);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
document.addEventListener('DOMContentLoaded', async 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 and disable past dates
|
|
||||||
M.Datepicker.init(document.querySelectorAll('.datepicker'), {
|
|
||||||
format: 'yyyy-mm-dd',
|
|
||||||
defaultDate: tomorrow,
|
|
||||||
setDefaultDate: true,
|
|
||||||
firstDay: 1,
|
|
||||||
minDate: today // Disable past dates
|
|
||||||
});
|
|
||||||
|
|
||||||
// Initialize timepicker
|
|
||||||
M.Timepicker.init(document.querySelectorAll('.timepicker'), {
|
|
||||||
twelveHour: false // Use 24-hour format
|
|
||||||
});
|
|
||||||
|
|
||||||
// Check if user is already logged in
|
|
||||||
checkSession()
|
|
||||||
.then(data => {
|
|
||||||
if (data.loggedIn) {
|
|
||||||
loginContainer.style.display = 'none';
|
|
||||||
appContainer.style.display = 'block';
|
|
||||||
loadTags().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(', ');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
|
||||||
} 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;
|
|
||||||
|
|
||||||
login(username, password)
|
|
||||||
.then(response => {
|
|
||||||
if (response.ok) {
|
|
||||||
sessionStorage.setItem('loggedIn', 'true');
|
|
||||||
loginContainer.style.display = 'none';
|
|
||||||
appContainer.style.display = 'block';
|
|
||||||
loadTags().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(', ');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
|
||||||
} else {
|
|
||||||
loginMessage.textContent = 'Invalid username or password';
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.catch(error => {
|
|
||||||
loginMessage.textContent = 'Error logging in';
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
logoutButton.addEventListener('click', function() {
|
|
||||||
logout()
|
|
||||||
.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: tags ? `${subject} :${tags}:` : subject,
|
|
||||||
description,
|
|
||||||
scheduled: scheduledDateTime
|
|
||||||
};
|
|
||||||
|
|
||||||
// Save tags to server
|
|
||||||
saveTags(tags.split(',').map(tag => tag.trim()).filter(tag => tag))
|
|
||||||
.then(() => {
|
|
||||||
loadTags(); // Force refresh tags after saving
|
|
||||||
});
|
|
||||||
|
|
||||||
// Save task to server or IndexedDB if offline
|
|
||||||
try {
|
|
||||||
const data = await saveTask(taskData);
|
|
||||||
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!";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// Synchronize tasks when back online
|
|
||||||
window.addEventListener('online', async () => {
|
|
||||||
const db = await idb.openDB('org-todo-pwa', 1);
|
|
||||||
const tasks = await db.getAll('tasks');
|
|
||||||
for (const task of tasks) {
|
|
||||||
try {
|
|
||||||
await saveTask(task);
|
|
||||||
await db.delete('tasks', task.id);
|
|
||||||
console.log(`Task synchronized: ${task.subject}`);
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Error synchronizing task:', error);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
export async function saveTags(newTags) {
|
|
||||||
const existingTags = await loadTags();
|
|
||||||
const allTags = Array.from(new Set([...existingTags, ...newTags]));
|
|
||||||
|
|
||||||
return fetch('/save-tags', {
|
|
||||||
method: 'POST',
|
|
||||||
headers: {
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
},
|
|
||||||
body: JSON.stringify({ tags: allTags })
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export function loadTags() {
|
|
||||||
return fetch('/get-tags')
|
|
||||||
.then(response => response.json());
|
|
||||||
}
|
|
||||||
@@ -1,30 +0,0 @@
|
|||||||
import { idb } from './utils.js';
|
|
||||||
|
|
||||||
export async function saveTask(taskData) {
|
|
||||||
if (navigator.onLine) {
|
|
||||||
try {
|
|
||||||
const response = await fetch('/add-task', {
|
|
||||||
method: 'POST',
|
|
||||||
headers: {
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
},
|
|
||||||
body: JSON.stringify(taskData)
|
|
||||||
});
|
|
||||||
return await response.json();
|
|
||||||
} catch (error) {
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
try {
|
|
||||||
const db = await idb.openDB('org-todo-pwa', 1, {
|
|
||||||
upgrade(db) {
|
|
||||||
db.createObjectStore('tasks', { keyPath: 'id', autoIncrement: true });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
await db.add('tasks', taskData);
|
|
||||||
return { message: "Task saved offline!" };
|
|
||||||
} catch (error) {
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,16 +0,0 @@
|
|||||||
export const idb = {
|
|
||||||
openDB(name, version, { upgrade }) {
|
|
||||||
return new Promise((resolve, reject) => {
|
|
||||||
const request = indexedDB.open(name, version);
|
|
||||||
request.onupgradeneeded = (event) => {
|
|
||||||
upgrade(request.result, event.oldVersion, event.newVersion, request.transaction);
|
|
||||||
};
|
|
||||||
request.onsuccess = () => {
|
|
||||||
resolve(request.result);
|
|
||||||
};
|
|
||||||
request.onerror = () => {
|
|
||||||
reject(request.error);
|
|
||||||
};
|
|
||||||
});
|
|
||||||
}
|
|
||||||
};
|
|
||||||
@@ -1,61 +1,28 @@
|
|||||||
const CACHE_NAME = 'org-todo-pwa-cache-v1';
|
self.addEventListener('install', (event) => {
|
||||||
const urlsToCache = [
|
|
||||||
'/',
|
|
||||||
'/index.html',
|
|
||||||
'/css/style.css',
|
|
||||||
'/js/auth.js',
|
|
||||||
'/js/tasks.js',
|
|
||||||
'/js/tags.js',
|
|
||||||
'/js/utils.js',
|
|
||||||
'/js/main.js',
|
|
||||||
'https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css',
|
|
||||||
'https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js'
|
|
||||||
];
|
|
||||||
|
|
||||||
self.addEventListener('install', event => {
|
|
||||||
event.waitUntil(
|
event.waitUntil(
|
||||||
caches.open(CACHE_NAME)
|
caches.open('task-manager-cache').then((cache) => {
|
||||||
.then(cache => {
|
return cache.addAll([
|
||||||
return cache.addAll(urlsToCache);
|
'/',
|
||||||
})
|
'/index.html',
|
||||||
);
|
'/style.css',
|
||||||
});
|
'/app.js',
|
||||||
|
'/manifest.json',
|
||||||
self.addEventListener('activate', event => {
|
'/icons/icon-192x192.png',
|
||||||
const cacheWhitelist = [CACHE_NAME];
|
'/icons/icon-512x512.png'
|
||||||
event.waitUntil(
|
]);
|
||||||
caches.keys().then(cacheNames => {
|
|
||||||
return Promise.all(
|
|
||||||
cacheNames.map(cacheName => {
|
|
||||||
if (!cacheWhitelist.includes(cacheName)) {
|
|
||||||
return caches.delete(cacheName);
|
|
||||||
}
|
|
||||||
})
|
|
||||||
);
|
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
self.addEventListener('fetch', event => {
|
self.addEventListener('fetch', (event) => {
|
||||||
event.respondWith(
|
if (event.request.url.includes('/get-tags') || event.request.url.includes('/save-tags')) {
|
||||||
caches.match(event.request)
|
// Bypass cache for tags endpoints
|
||||||
.then(response => {
|
event.respondWith(fetch(event.request));
|
||||||
if (response) {
|
} else {
|
||||||
return response;
|
event.respondWith(
|
||||||
}
|
caches.match(event.request).then((cachedResponse) => {
|
||||||
return fetch(event.request).then(
|
return cachedResponse || fetch(event.request);
|
||||||
response => {
|
|
||||||
if (!response || response.status !== 200 || response.type !== 'basic') {
|
|
||||||
return response;
|
|
||||||
}
|
|
||||||
const responseToCache = response.clone();
|
|
||||||
caches.open(CACHE_NAME)
|
|
||||||
.then(cache => {
|
|
||||||
cache.put(event.request, responseToCache);
|
|
||||||
});
|
|
||||||
return response;
|
|
||||||
}
|
|
||||||
);
|
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
26
public/style.css
Normal file
26
public/style.css
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
body {
|
||||||
|
font-family: Arial, sans-serif;
|
||||||
|
display: flex;
|
||||||
|
justify-content: center;
|
||||||
|
align-items: center;
|
||||||
|
height: 100vh;
|
||||||
|
margin: 0;
|
||||||
|
background-color: #f4f4f9;
|
||||||
|
}
|
||||||
|
|
||||||
|
.container {
|
||||||
|
width: 300px;
|
||||||
|
padding: 20px;
|
||||||
|
background-color: #fff;
|
||||||
|
border-radius: 8px;
|
||||||
|
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
|
||||||
|
}
|
||||||
|
|
||||||
|
h1 {
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
#responseMessage {
|
||||||
|
text-align: center;
|
||||||
|
color: green;
|
||||||
|
}
|
||||||
@@ -1,6 +1,5 @@
|
|||||||
const express = require('express');
|
const express = require('express');
|
||||||
const basicAuth = require('basic-auth');
|
const basicAuth = require('basic-auth');
|
||||||
const logger = require('../logger');
|
|
||||||
const router = express.Router();
|
const router = express.Router();
|
||||||
|
|
||||||
router.post('/login', (req, res) => {
|
router.post('/login', (req, res) => {
|
||||||
@@ -9,30 +8,10 @@ router.post('/login', (req, res) => {
|
|||||||
const password = process.env.AUTH_PASSWORD;
|
const password = process.env.AUTH_PASSWORD;
|
||||||
|
|
||||||
if (user && user.name === username && user.pass === password) {
|
if (user && user.name === username && user.pass === password) {
|
||||||
req.session.user = user.name;
|
|
||||||
res.status(200).send('Login successful');
|
res.status(200).send('Login successful');
|
||||||
logger.info(`User ${user.name} logged in`);
|
|
||||||
} else {
|
} else {
|
||||||
res.status(401).send('Authentication required');
|
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;
|
module.exports = router;
|
||||||
@@ -3,17 +3,10 @@ const fs = require('fs');
|
|||||||
const path = require('path');
|
const path = require('path');
|
||||||
const auth = require('../middleware/auth');
|
const auth = require('../middleware/auth');
|
||||||
const logger = require('../logger');
|
const logger = require('../logger');
|
||||||
const sqlite3 = require('sqlite3').verbose();
|
|
||||||
|
|
||||||
const router = express.Router();
|
const router = express.Router();
|
||||||
const dataDir = '/data';
|
const dataDir = '/data';
|
||||||
|
|
||||||
const db = new sqlite3.Database('/data/sessions.sqlite', (err) => {
|
|
||||||
if (err) {
|
|
||||||
console.error('Error opening database:', err);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// Ensure the /data directory exists
|
// Ensure the /data directory exists
|
||||||
if (!fs.existsSync(dataDir)) {
|
if (!fs.existsSync(dataDir)) {
|
||||||
fs.mkdirSync(dataDir, { recursive: true });
|
fs.mkdirSync(dataDir, { recursive: true });
|
||||||
@@ -30,76 +23,59 @@ router.post('/add-task', auth, async (req, res) => {
|
|||||||
const { subject, description, scheduled } = req.body;
|
const { subject, description, scheduled } = req.body;
|
||||||
const currentDateTime = new Date().toISOString().replace(/T/, ' ').replace(/\..+/, '');
|
const currentDateTime = new Date().toISOString().replace(/T/, ' ').replace(/\..+/, '');
|
||||||
|
|
||||||
// Format the scheduled date and time for Org mode
|
let orgFormattedData = `
|
||||||
const scheduledDate = new Date(scheduled);
|
* TODO ${subject}
|
||||||
const dayNames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
|
SCHEDULED: <${scheduled}>
|
||||||
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:
|
:LOGBOOK:
|
||||||
- State "TODO" from "TODO" [${currentDateTime}]
|
- State "TODO" from "TODO" [${currentDateTime}]
|
||||||
:END:
|
:END:
|
||||||
`;
|
`;
|
||||||
|
|
||||||
if (description) {
|
if (description) {
|
||||||
orgFormattedData = `* TODO ${subject}
|
orgFormattedData = `
|
||||||
|
* TODO ${subject}
|
||||||
${description}
|
${description}
|
||||||
SCHEDULED: ${formattedScheduled}
|
SCHEDULED: <${scheduled}>
|
||||||
:LOGBOOK:
|
:LOGBOOK:
|
||||||
- State "TODO" from "TODO" [${currentDateTime}]
|
- State "TODO" from "TODO" [${currentDateTime}]
|
||||||
:END:
|
:END:
|
||||||
`;
|
`;
|
||||||
}
|
}
|
||||||
|
|
||||||
const filePath = path.join(dataDir, 'tasks.org');
|
const filePath = path.join(dataDir, 'tasks.org');
|
||||||
try {
|
try {
|
||||||
await fs.promises.appendFile(filePath, orgFormattedData);
|
await fs.promises.appendFile(filePath, orgFormattedData);
|
||||||
res.json({ message: 'Task added successfully' });
|
res.send({ message: 'Task added successfully!' });
|
||||||
logger.info(`Task added: ${orgFormattedData}`);
|
} catch (err) {
|
||||||
} catch (error) {
|
logger.error('Error writing to file:', err);
|
||||||
logger.error('Error writing to tasks.org file:', error);
|
res.status(500).send('Error writing to file.');
|
||||||
res.status(500).json({ message: 'Error adding task' });
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// Endpoint to save tags
|
// Endpoint to save tags
|
||||||
router.post('/save-tags', auth, async (req, res) => {
|
router.post('/save-tags', auth, async (req, res) => {
|
||||||
const { tags } = req.body;
|
const { tags } = req.body;
|
||||||
const placeholders = tags.map(() => '(?)').join(',');
|
const filePath = path.join(dataDir, 'tags.json');
|
||||||
const sql = `INSERT OR IGNORE INTO tags (tag) VALUES ${placeholders}`;
|
try {
|
||||||
|
await fs.promises.writeFile(filePath, JSON.stringify(tags));
|
||||||
db.run(sql, tags, function(err) {
|
res.send({ message: 'Tags saved successfully!' });
|
||||||
if (err) {
|
} catch (err) {
|
||||||
logger.error('Error saving tags:', err);
|
logger.error('Error saving tags:', err);
|
||||||
res.status(500).send('Error saving tags.');
|
res.status(500).send('Error saving tags.');
|
||||||
} else {
|
}
|
||||||
res.send({ message: 'Tags saved successfully!' });
|
|
||||||
logger.info(`New tags saved: ${tags}`);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// Endpoint to retrieve tags
|
// Endpoint to retrieve tags
|
||||||
router.get('/get-tags', auth, async (req, res) => {
|
router.get('/get-tags', auth, async (req, res) => {
|
||||||
db.all('SELECT tag FROM tags', [], (err, rows) => {
|
const filePath = path.join(dataDir, 'tags.json');
|
||||||
if (err) {
|
try {
|
||||||
logger.error('Error retrieving tags:', err);
|
const data = await fs.promises.readFile(filePath, 'utf-8');
|
||||||
res.status(500).json({ error: 'Error retrieving tags' });
|
const tags = JSON.parse(data);
|
||||||
} else {
|
res.json(tags);
|
||||||
const tags = rows.map(row => row.tag);
|
} catch (err) {
|
||||||
res.json(tags);
|
logger.error('Error retrieving tags:', err);
|
||||||
}
|
res.status(500).json({ error: 'Error retrieving tags' });
|
||||||
});
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
module.exports = router;
|
module.exports = router;
|
||||||
46
server.js
46
server.js
@@ -1,58 +1,18 @@
|
|||||||
require('dotenv').config();
|
require('dotenv').config();
|
||||||
const express = require('express');
|
const express = require('express');
|
||||||
const bodyParser = require('body-parser');
|
const bodyParser = require('body-parser');
|
||||||
const session = require('express-session');
|
const debug = require('debug')('app');
|
||||||
const cookieParser = require('cookie-parser');
|
|
||||||
const SQLiteStore = require('connect-sqlite3')(session);
|
|
||||||
const sqlite3 = require('sqlite3').verbose();
|
|
||||||
const tasksRouter = require('./routes/tasks');
|
const tasksRouter = require('./routes/tasks');
|
||||||
const authRouter = require('./routes/auth');
|
const authRouter = require('./routes/auth');
|
||||||
const authMiddleware = require('./middleware/auth');
|
|
||||||
const logger = require('./logger');
|
|
||||||
|
|
||||||
const app = express();
|
const app = express();
|
||||||
const port = 3044;
|
const port = 3044;
|
||||||
|
|
||||||
const db = new sqlite3.Database('/data/sessions.sqlite', (err) => {
|
|
||||||
if (err) {
|
|
||||||
console.error('Error opening database:', err);
|
|
||||||
} else {
|
|
||||||
db.run(`CREATE TABLE IF NOT EXISTS tags (
|
|
||||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
||||||
tag TEXT UNIQUE
|
|
||||||
)`, (err) => {
|
|
||||||
if (err) {
|
|
||||||
console.error('Error creating tags table:', err);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
app.use(bodyParser.json());
|
app.use(bodyParser.json());
|
||||||
app.use(cookieParser());
|
|
||||||
app.use(express.static('public'));
|
app.use(express.static('public'));
|
||||||
|
app.use('/', tasksRouter);
|
||||||
// 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
|
|
||||||
maxAge: 30 * 24 * 60 * 60 * 1000 // 1 month
|
|
||||||
}
|
|
||||||
}));
|
|
||||||
|
|
||||||
app.use('/', authRouter);
|
app.use('/', authRouter);
|
||||||
app.use('/', authMiddleware, tasksRouter);
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
app.listen(port, () => {
|
app.listen(port, () => {
|
||||||
logger.info(`Server running at http://localhost:${port}`);
|
debug(`Server running at http://localhost:${port}`);
|
||||||
});
|
});
|
||||||
|
|||||||
Reference in New Issue
Block a user