it's working!!!

This commit is contained in:
MLH
2025-04-06 15:27:27 +02:00
parent 68c55593b3
commit a976c2f200
9 changed files with 506 additions and 252 deletions

2
.env
View File

@ -8,7 +8,7 @@ DB_PORT=5432 # Default PostgreSQL port
# JWT Configuration
# Use a strong, random secret for JWT signing in production
JWT_SECRET=873hfd23rh2rzr1h61rh13z1hß1r1ß4gr1fnwe5vgqwerf # Ändere dies unbedingt!
JWT_SECRET=873hfd23rh2rzr1h61rh13z1hß1r1ß4gr1fnwe5vgqwerf # geheim!!!
JWT_EXPIRES_IN=1h # How long the login token is valid
# Server Configuration

View File

@ -10,38 +10,54 @@ const authenticateToken = (req, res, next) => {
// Get token from the 'token' cookie
const token = req.cookies.token;
// Enhanced debug logging
console.log('Auth Request:', {
path: req.path,
method: req.method,
contentType: req.headers['content-type'],
accept: req.headers.accept,
hasToken: !!token, // Log if token exists (true/false)
cookies: Object.keys(req.cookies) // Log all cookie names
});
// More precise API request detection - already good
const isApiRequest = req.path.startsWith('/api/') ||
req.xhr ||
(req.headers['content-type'] && req.headers['content-type'].includes('application/json')) ||
(req.headers.accept && req.headers.accept.includes('application/json'));
// If no token is present, deny access
if (!token) {
console.log('No token found, request is API?', isApiRequest);
// If the request is for an API endpoint, return 401 Unauthorized
if (req.path.startsWith('/api/')) {
return res.status(401).json({ message: 'Zugriff verweigert. Kein Token vorhanden.' });
if (isApiRequest) {
return res.status(401).json({ message: 'Zugriff verweigert. Nicht authentifiziert.' });
}
// Otherwise, redirect to the login page
return res.redirect('/login');
}
// Verify the token
// Verify the token with better error reporting
jwt.verify(token, JWT_SECRET, (err, user) => {
if (err) {
console.error('JWT Verification Error:', err.message);
// If token is invalid or expired
if (req.path.startsWith('/api/')) {
// Clear the invalid cookie and return 403 Forbidden for API requests
res.clearCookie('token');
return res.status(403).json({ message: 'Token ungültig oder abgelaufen.' });
}
// Clear the invalid cookie and redirect to login for page requests
res.clearCookie('token');
return res.redirect('/login');
console.error('JWT Verification Error:', err.message, err.name);
// If token is invalid or expired
if (isApiRequest) {
// Clear the invalid cookie and return 403 Forbidden for API requests
res.clearCookie('token');
return res.status(403).json({ message: 'Token ungültig oder abgelaufen.' });
}
// Clear the invalid cookie and redirect to login for page requests
res.clearCookie('token');
return res.redirect('/login');
}
// If token is valid, attach the decoded user information (payload) to the request object
// The payload typically contains user ID, username, etc. (whatever was put in during login)
req.user = user; // Example: user might be { id: 1, username: 'testuser' }
// Proceed to the next middleware or route handler
req.user = user;
// Add debug logging for successful auth
console.log('Authentication successful for user:', user.username, 'user ID:', user.id);
next();
});
};
module.exports = authenticateToken;
module.exports = authenticateToken;

View File

@ -10,17 +10,26 @@
<div class="container todo-container">
<div class="header">
<h1>Meine Todo-Liste</h1>
<button id="logout-button" class="btn btn-secondary">Abmelden</button>
<div id="auth-button-container">
</div>
</div>
<form id="add-todo-form">
<input type="text" id="new-todo-input" placeholder="Neue Aufgabe hinzufügen..." required>
<button type="submit" class="btn btn-add">+</button>
</form>
<div id="todo-app-content" style="display: none;">
<form id="add-todo-form">
<input type="text" id="new-todo-input" placeholder="Neue Aufgabe hinzufügen..." required>
<button type="submit" class="btn btn-add">+</button>
</form>
<ul id="todo-list">
</ul>
<p id="error-message" class="error-message"></p>
</div>
<div id="login-prompt" style="display: none;" class="login-prompt-container">
<p>Bitte melden Sie sich an, um Ihre Todos zu sehen und zu verwalten.</p>
<a href="/login" class="btn">Zur Anmeldung</a>
</div>
<ul id="todo-list">
</ul>
<p id="error-message" class="error-message"></p>
</div>
<script src="script.js"></script> </body>

View File

@ -1,5 +1,6 @@
// public/script.js
// Handles frontend logic for login, registration, and todo management
// Version 3: Improved error handling message for JSON parse errors
document.addEventListener('DOMContentLoaded', () => {
const path = window.location.pathname;
@ -10,12 +11,12 @@ document.addEventListener('DOMContentLoaded', () => {
} else if (path === '/register' || path.endsWith('register.html')) {
setupRegisterForm();
} else if (path === '/' || path.endsWith('index.html')) {
// User should be authenticated to be here (handled by viewRoutes)
setupTodoPage();
// Main page logic: Check login status and set up UI accordingly
checkLoginStatusAndSetupPage();
}
});
// --- Authentication Form Handlers ---
// --- Authentication Form Handlers (Unchanged from previous version) ---
function setupLoginForm() {
const loginForm = document.getElementById('login-form');
@ -102,33 +103,127 @@ function setupRegisterForm() {
}
}
// --- Todo Page Logic ---
// --- Main Page Logic (index.html) ---
function setupTodoPage() {
// Global references for main page elements
let todoAppContent = null;
let loginPrompt = null;
let authButtonContainer = null;
let todoList = null;
let errorMessage = null; // Error message specifically for todo actions
// Function to check login status and set up the main page UI
async function checkLoginStatusAndSetupPage() {
// Get references to the main containers
todoAppContent = document.getElementById('todo-app-content');
loginPrompt = document.getElementById('login-prompt');
authButtonContainer = document.getElementById('auth-button-container');
todoList = document.getElementById('todo-list'); // Needed for clearing/rendering
errorMessage = document.getElementById('error-message'); // Error display within todo-app-content
if (!todoAppContent || !loginPrompt || !authButtonContainer || !todoList || !errorMessage) {
console.error('Essential page elements not found!');
return;
}
try {
const response = await fetch('/api/auth/status');
// Check if response is ok and content type is JSON before parsing
if (response.ok && response.headers.get('Content-Type')?.includes('application/json')) {
const status = await response.json();
if (status.loggedIn) {
updateUIForLoggedIn(status.username);
setupTodoListeners(); // Set up listeners only if logged in
await fetchTodos(); // Fetch todos only if logged in
} else {
updateUIForLoggedOut();
}
} else {
// Handle non-JSON or error responses from /status endpoint
console.error('Unexpected response from /api/auth/status:', response.status, response.statusText);
updateUIForLoggedOut(); // Fallback to logged out state
errorMessage.textContent = 'Fehler beim Prüfen des Login-Status (Serverantwort).';
}
} catch (error) {
console.error('Error checking login status:', error);
// Show logged out state as a fallback in case of network error etc.
updateUIForLoggedOut();
errorMessage.textContent = 'Fehler beim Prüfen des Login-Status (Netzwerk/Skript).';
}
}
// Update UI for Logged-In User
function updateUIForLoggedIn(username) {
if (!todoAppContent || !loginPrompt || !authButtonContainer) return;
// Show Todo content, hide login prompt
todoAppContent.style.display = 'block';
loginPrompt.style.display = 'none';
// Update Auth Button to "Abmelden"
authButtonContainer.innerHTML = ''; // Clear previous button
const logoutButton = document.createElement('button');
logoutButton.id = 'logout-button';
logoutButton.textContent = 'Abmelden';
logoutButton.classList.add('btn', 'btn-secondary');
logoutButton.addEventListener('click', handleLogout); // Add listener directly
authButtonContainer.appendChild(logoutButton);
// Optional: Display username (e.g., next to the button or in the header)
const welcomeMessage = document.createElement('span');
welcomeMessage.textContent = `Hallo, ${username}! `;
welcomeMessage.style.marginRight = '10px';
authButtonContainer.prepend(welcomeMessage); // Add before button
}
// Update UI for Logged-Out User
function updateUIForLoggedOut() {
if (!todoAppContent || !loginPrompt || !authButtonContainer || !todoList) return;
// Hide Todo content, show login prompt
todoAppContent.style.display = 'none';
loginPrompt.style.display = 'block';
// Update Auth Button to "Anmelden"
authButtonContainer.innerHTML = ''; // Clear previous button
const loginLink = document.createElement('a'); // Use a link for navigation
loginLink.href = '/login';
loginLink.textContent = 'Anmelden';
loginLink.classList.add('btn'); // Style as button
authButtonContainer.appendChild(loginLink);
// Clear any existing todos from the list
todoList.innerHTML = '';
// Clear any previous error messages related to todos
if(errorMessage) errorMessage.textContent = '';
}
// Set up event listeners for the todo form and list (only when logged in)
function setupTodoListeners() {
const addTodoForm = document.getElementById('add-todo-form');
const newTodoInput = document.getElementById('new-todo-input');
const todoList = document.getElementById('todo-list');
const logoutButton = document.getElementById('logout-button');
const errorMessage = document.getElementById('error-message');
// --- Event Listeners ---
// todoList reference is already global
// Add Todo Form Submission
if (addTodoForm) {
addTodoForm.addEventListener('submit', async (event) => {
// Remove previous listener if any to prevent duplicates
addTodoForm.onsubmit = null;
addTodoForm.onsubmit = async (event) => {
event.preventDefault();
const task = newTodoInput.value.trim();
if (task) {
await addTodoItem(task);
newTodoInput.value = ''; // Clear input field
}
});
};
}
// Todo List Click Handler (for checkboxes and delete buttons)
if (todoList) {
todoList.addEventListener('click', async (event) => {
// Remove previous listener if any
todoList.onclick = null;
todoList.onclick = async (event) => {
const target = event.target;
const todoItem = target.closest('.todo-item'); // Find the parent li element
@ -146,192 +241,267 @@ function setupTodoPage() {
if (target.classList.contains('btn-delete')) {
await deleteTodoItem(todoId);
}
});
};
}
// Logout Button Click
if (logoutButton) {
logoutButton.addEventListener('click', async () => {
errorMessage.textContent = ''; // Clear errors
try {
const response = await fetch('/api/auth/logout', { method: 'POST' });
if (response.ok) {
// Logout successful, redirect to login page
window.location.href = '/login';
} else {
const result = await response.json();
errorMessage.textContent = result.message || 'Logout fehlgeschlagen.';
}
} catch (error) {
console.error('Logout failed:', error);
errorMessage.textContent = 'Logout fehlgeschlagen. Netzwerkfehler.';
}
});
}
// --- API Call Functions ---
// Fetch Todos from Server
async function fetchTodos() {
errorMessage.textContent = '';
try {
const response = await fetch('/api/todos'); // GET request by default
if (response.status === 401 || response.status === 403) {
// If unauthorized (e.g., token expired), redirect to login
window.location.href = '/login';
return;
}
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const todos = await response.json();
renderTodoList(todos);
} catch (error) {
console.error('Error fetching todos:', error);
errorMessage.textContent = 'Fehler beim Laden der Todos.';
// Handle error display or potentially redirect to login if it's an auth issue
}
}
// Add a New Todo Item
async function addTodoItem(task) {
errorMessage.textContent = '';
try {
const response = await fetch('/api/todos', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ task }),
});
if (response.status === 401 || response.status === 403) {
window.location.href = '/login';
return;
}
if (!response.ok) {
const result = await response.json();
throw new Error(result.message || 'Fehler beim Hinzufügen');
}
const newTodo = await response.json();
addTodoToDOM(newTodo); // Add the new todo to the page immediately
} catch (error) {
console.error('Error adding todo:', error);
errorMessage.textContent = `Fehler beim Hinzufügen: ${error.message}`;
}
}
// Update Todo Completion Status
async function updateTodoStatus(id, isCompleted) {
errorMessage.textContent = '';
try {
const response = await fetch(`/api/todos/${id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ is_completed: isCompleted }),
});
if (response.status === 401 || response.status === 403) {
window.location.href = '/login';
return;
}
if (!response.ok) {
const result = await response.json();
throw new Error(result.message || 'Fehler beim Aktualisieren');
}
const updatedTodo = await response.json();
// Update the specific todo item in the DOM
const todoElement = todoList.querySelector(`li[data-id="${id}"]`);
if (todoElement) {
todoElement.classList.toggle('completed', updatedTodo.is_completed);
const checkbox = todoElement.querySelector('input[type="checkbox"]');
if(checkbox) checkbox.checked = updatedTodo.is_completed;
}
} catch (error) {
console.error('Error updating todo status:', error);
errorMessage.textContent = `Fehler beim Aktualisieren: ${error.message}`;
// Optional: Revert checkbox state on error
const todoElement = todoList.querySelector(`li[data-id="${id}"]`);
if(todoElement) {
const checkbox = todoElement.querySelector('input[type="checkbox"]');
if(checkbox) checkbox.checked = !isCompleted; // Revert state
}
}
}
// Delete a Todo Item
async function deleteTodoItem(id) {
errorMessage.textContent = '';
try {
const response = await fetch(`/api/todos/${id}`, {
method: 'DELETE',
});
if (response.status === 401 || response.status === 403) {
window.location.href = '/login';
return;
}
if (!response.ok && response.status !== 204) { // Allow 204 No Content
const result = await response.json();
throw new Error(result.message || 'Fehler beim Löschen');
}
// Remove the todo item from the DOM
const todoElement = todoList.querySelector(`li[data-id="${id}"]`);
if (todoElement) {
todoElement.remove();
}
} catch (error) {
console.error('Error deleting todo:', error);
errorMessage.textContent = `Fehler beim Löschen: ${error.message}`;
}
}
// --- DOM Manipulation ---
// Render the entire list of todos
function renderTodoList(todos) {
if (!todoList) return;
todoList.innerHTML = ''; // Clear existing list
if (todos.length === 0) {
todoList.innerHTML = '<p style="text-align: center; color: #888;">Noch keine Aufgaben vorhanden.</p>';
} else {
todos.forEach(todo => addTodoToDOM(todo));
}
}
// Add a single todo item to the DOM
function addTodoToDOM(todo) {
if (!todoList) return;
// Remove the "no tasks" message if it exists
const noTasksMessage = todoList.querySelector('p');
if (noTasksMessage) {
noTasksMessage.remove();
}
const li = document.createElement('li');
li.classList.add('todo-item');
li.dataset.id = todo.id; // Store todo ID on the element
if (todo.is_completed) {
li.classList.add('completed');
}
const checkbox = document.createElement('input');
checkbox.type = 'checkbox';
checkbox.checked = todo.is_completed;
const span = document.createElement('span');
span.textContent = todo.task;
const deleteButton = document.createElement('button');
deleteButton.textContent = 'Löschen';
deleteButton.classList.add('btn-delete'); // Use specific class for deletion
li.appendChild(checkbox);
li.appendChild(span);
li.appendChild(deleteButton);
// Prepend to show newest todos first, or append for oldest first
todoList.prepend(li); // Add new todos to the top
}
// --- Initial Load ---
fetchTodos(); // Load todos when the page loads
}
// Handle Logout Process
async function handleLogout() {
if(errorMessage) errorMessage.textContent = ''; // Clear errors
try {
const response = await fetch('/api/auth/logout', { method: 'POST' });
if (response.ok) {
// Logout successful, update UI to logged-out state
updateUIForLoggedOut();
} else {
// Try to parse error response as JSON
let result = { message: 'Logout fehlgeschlagen (unbekannter Fehler).' };
try {
result = await response.json();
} catch (e) {
console.error("Could not parse logout error response as JSON");
}
if(errorMessage) errorMessage.textContent = result.message || 'Logout fehlgeschlagen.';
}
} catch (error) {
console.error('Logout failed:', error);
if(errorMessage) errorMessage.textContent = 'Logout fehlgeschlagen. Netzwerkfehler.';
}
}
// --- API Call Functions (Modified Error Handling) ---
// Fetch Todos from Server
async function fetchTodos() {
if(errorMessage) errorMessage.textContent = '';
try {
const response = await fetch('/api/todos'); // GET request by default
// Check for auth errors specifically (though status check should prevent this)
if (response.status === 401 || response.status === 403) {
console.warn('Auth error during fetchTodos - should have been caught by status check.');
updateUIForLoggedOut(); // Update UI to logged out state
return; // Stop processing
}
if (!response.ok) {
// Handle other potential errors (e.g., 500 server error)
const errorData = await response.json().catch(() => ({ message: 'Unbekannter Serverfehler beim Laden der Todos' }));
throw new Error(errorData.message || `HTTP error! status: ${response.status}`);
}
// Ensure response is JSON before parsing
if (!response.headers.get('Content-Type')?.includes('application/json')) {
throw new Error('Unerwartete Serverantwort (kein JSON) beim Laden der Todos.');
}
const todos = await response.json();
renderTodoList(todos);
} catch (error) {
console.error('Error fetching todos:', error);
if(errorMessage) errorMessage.textContent = `Fehler beim Laden der Todos: ${error.message}`;
// Do NOT switch to logged-out UI here, as it might be a temporary server issue
}
}
// Add a New Todo Item
async function addTodoItem(task) {
if(errorMessage) errorMessage.textContent = '';
let response;
console.log('Adding todo item:', task);
try {
response = await fetch('/api/todos/newEntry', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json' // Explicitly request JSON response
},
credentials: 'same-origin', // Explicitly include cookies/credentials
body: JSON.stringify({ task }),
});
console.log('Response status:', response.status);
// If we got redirected to the login page, the status might still be 200
// but the content type will be text/html instead of application/json
const contentType = response.headers.get('Content-Type');
console.log('Response headers:', contentType);
if (contentType && contentType.includes('text/html')) {
// We got HTML instead of JSON - this means auth failed and we were redirected
console.warn('Auth failed - received HTML instead of JSON');
updateUIForLoggedOut();
return;
}
if (response.status === 401 || response.status === 403) {
console.warn('Auth error during addTodoItem.');
updateUIForLoggedOut();
return;
}
// Clone and log response body for debugging
console.log('Response body:', await response.clone().text());
console.log('Response ok:', response.ok);
if (!response.ok) {
const result = await response.json().catch(() => ({
message: `Serverfehler (${response.status}) beim Hinzufügen.`
}));
throw new Error(result.message);
}
// We already checked content type above, so just parse JSON now
const newTodo = await response.json();
addTodoToDOM(newTodo);
} catch (error) {
console.error('Error adding todo:', error);
let displayError = `Fehler beim Hinzufügen: ${error.message}`;
if (error instanceof SyntaxError) {
displayError = 'Fehler beim Hinzufügen: Unerwartete Antwort vom Server.';
}
if(errorMessage) errorMessage.textContent = displayError;
}
}
// Update Todo Completion Status
async function updateTodoStatus(id, isCompleted) {
if(errorMessage) errorMessage.textContent = '';
let response;
try {
response = await fetch(`/api/todos/${id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ is_completed: isCompleted }),
});
if (response.status === 401 || response.status === 403) {
console.warn('Auth error during updateTodoStatus.');
updateUIForLoggedOut();
return;
}
if (!response.ok) {
const result = await response.json().catch(() => ({ message: `Serverfehler (${response.status}) beim Aktualisieren.` }));
throw new Error(result.message);
}
if (!response.headers.get('Content-Type')?.includes('application/json')) {
throw new Error('Unerwartete Serverantwort (kein JSON) nach dem Aktualisieren.');
}
const updatedTodo = await response.json();
// Update the specific todo item in the DOM
const todoElement = todoList.querySelector(`li[data-id="${id}"]`);
if (todoElement) {
todoElement.classList.toggle('completed', updatedTodo.is_completed);
const checkbox = todoElement.querySelector('input[type="checkbox"]');
if(checkbox) checkbox.checked = updatedTodo.is_completed;
}
} catch (error) {
console.error('Error updating todo status:', error);
let displayError = `Fehler beim Aktualisieren: ${error.message}`;
if (error instanceof SyntaxError) {
displayError = 'Fehler beim Aktualisieren: Unerwartete Antwort vom Server.';
}
if(errorMessage) errorMessage.textContent = displayError;
// Optional: Revert checkbox state on error
const todoElement = todoList.querySelector(`li[data-id="${id}"]`);
if(todoElement) {
const checkbox = todoElement.querySelector('input[type="checkbox"]');
if(checkbox) checkbox.checked = !isCompleted; // Revert state
}
}
}
// Delete a Todo Item
async function deleteTodoItem(id) {
if(errorMessage) errorMessage.textContent = '';
try {
const response = await fetch(`/api/todos/${id}`, {
method: 'DELETE',
});
if (response.status === 401 || response.status === 403) {
console.warn('Auth error during deleteTodoItem.');
updateUIForLoggedOut();
return;
}
// Allow 204 No Content (which might not have a JSON body)
if (!response.ok && response.status !== 204) {
const result = await response.json().catch(() => ({ message: `Serverfehler (${response.status}) beim Löschen.` }));
throw new Error(result.message);
}
// Remove the todo item from the DOM
const todoElement = todoList.querySelector(`li[data-id="${id}"]`);
if (todoElement) {
todoElement.remove();
// Check if list is now empty and show message if needed
if (todoList.children.length === 0) {
renderTodoList([]); // Will add the "empty" message
}
}
} catch (error) {
console.error('Error deleting todo:', error);
let displayError = `Fehler beim Löschen: ${error.message}`;
if (error instanceof SyntaxError) { // Should not happen for DELETE usually, but good practice
displayError = 'Fehler beim Löschen: Unerwartete Antwort vom Server.';
}
if(errorMessage) errorMessage.textContent = displayError;
}
}
// --- DOM Manipulation (Rendering Todos) ---
// Render the entire list of todos
function renderTodoList(todos) {
if (!todoList) return;
todoList.innerHTML = ''; // Clear existing list
if (todos.length === 0) {
// Display a message within the todo list area if empty
const emptyMsg = document.createElement('p');
emptyMsg.textContent = 'Noch keine Aufgaben vorhanden.';
emptyMsg.style.textAlign = 'center';
emptyMsg.style.color = '#888';
emptyMsg.style.padding = '20px 0';
todoList.appendChild(emptyMsg);
} else {
todos.forEach(todo => addTodoToDOM(todo));
}
}
// Add a single todo item to the DOM
function addTodoToDOM(todo) {
if (!todoList) return;
// Remove the "no tasks" message if it exists and we are adding the first item
const emptyMsg = todoList.querySelector('p');
if (emptyMsg && todoList.children.length === 1 && emptyMsg.parentNode === todoList) {
emptyMsg.remove();
}
const li = document.createElement('li');
li.classList.add('todo-item');
li.dataset.id = todo.id; // Store todo ID on the element
if (todo.is_completed) {
li.classList.add('completed');
}
const checkbox = document.createElement('input');
checkbox.type = 'checkbox';
checkbox.checked = todo.is_completed;
const span = document.createElement('span');
span.textContent = todo.task;
const deleteButton = document.createElement('button');
deleteButton.textContent = 'Löschen';
deleteButton.classList.add('btn-delete'); // Use specific class for deletion
li.appendChild(checkbox);
li.appendChild(span);
li.appendChild(deleteButton);
// Prepend to show newest todos first
todoList.prepend(li);
}

View File

@ -80,6 +80,13 @@ body {
padding-bottom: 15px;
}
/* Container for the auth button */
#auth-button-container {
min-width: 100px; /* Ensure space for the button */
text-align: right;
}
.todo-container h1 {
margin: 0;
color: #2c3e50;
@ -151,6 +158,8 @@ body {
transition: background-color 0.2s ease, box-shadow 0.2s ease;
background-color: #3498db; /* Primary button color */
color: white;
text-decoration: none; /* For anchor tags styled as buttons */
display: inline-block; /* For anchor tags */
}
.btn:hover {
@ -211,3 +220,19 @@ body {
min-height: 1.2em; /* Prevent layout shift */
}
/* Styling for the login prompt */
.login-prompt-container {
text-align: center;
padding: 40px 20px;
background-color: #f8f9fa;
border: 1px solid #e9ecef;
border-radius: 5px;
margin-top: 20px;
}
.login-prompt-container p {
margin-bottom: 15px;
font-size: 1.1em;
color: #555;
}

View File

@ -1,5 +1,5 @@
// routes/authRoutes.js
// Handles user registration, login, and logout
// Handles user registration, login, logout, and status check
const express = require('express');
const bcrypt = require('bcrypt');
@ -70,27 +70,22 @@ router.post('/login', async (req, res) => {
const payload = {
id: user.id,
username: user.username
// Add other relevant non-sensitive user info if needed
};
// Sign the JWT
const token = jwt.sign(payload, JWT_SECRET, { expiresIn: JWT_EXPIRES_IN });
// Sign the JWT with a 24h expiration for testing purposes
const token = jwt.sign(payload, JWT_SECRET, { expiresIn: '24h' });
// Set JWT as an HTTP-Only cookie
// HttpOnly: Prevents client-side JS access (safer against XSS)
// Secure: Transmit cookie only over HTTPS (set to true in production with HTTPS)
// SameSite: Controls cross-site request behavior ('Strict' or 'Lax' recommended)
// Set JWT as an HTTP-Only cookie with correct settings
res.cookie('token', token, {
httpOnly: true,
secure: process.env.NODE_ENV === 'production', // Use secure cookies in production
maxAge: parseInt(JWT_EXPIRES_IN) * 1000 || 3600000, // Cookie expiry in milliseconds (e.g., 1h)
sameSite: 'Lax' // Or 'Strict'
secure: false, // Set to false for local development
maxAge: 24 * 60 * 60 * 1000, // 24 hours in milliseconds
sameSite: 'Lax'
});
console.log(`User logged in: ${user.username}`);
// Send success response (client-side JS will redirect)
res.status(200).json({ message: 'Login erfolgreich.' });
// Send success response
res.status(200).json({ message: 'Login erfolgreich.', username: user.username });
} catch (error) {
console.error('Login Error:', error);
res.status(500).json({ message: 'Serverfehler beim Login.' });
@ -110,4 +105,29 @@ router.post('/logout', (req, res) => {
});
// --- NEUE Route ---
// GET /api/auth/status - Check login status without causing redirect/error
router.get('/status', (req, res) => {
const token = req.cookies.token;
if (!token) {
// No token cookie found
return res.json({ loggedIn: false });
}
// Verify the existing token
jwt.verify(token, JWT_SECRET, (err, user) => {
if (err) {
// Token is invalid (e.g., expired, tampered)
console.log('Status check: Invalid token found, clearing cookie.');
res.clearCookie('token'); // Clear the invalid cookie
return res.json({ loggedIn: false });
}
// Token is valid
// Send back loggedIn status and username
return res.json({ loggedIn: true, username: user.username });
});
});
module.exports = router;

View File

@ -27,10 +27,11 @@ router.get('/', async (req, res) => {
});
// POST /api/todos - Create a new todo for the logged-in user
router.post('/', async (req, res) => {
router.post('/newEntry', async (req, res) => {
const userId = req.user.id;
const { task } = req.body;
console.log('Received task:', task); // Log the received task for debugging
if (!task || task.trim() === '') {
return res.status(400).json({ message: 'Aufgabeninhalt darf nicht leer sein.' });
}

View File

@ -3,7 +3,8 @@
const express = require('express');
const path = require('path');
const authenticateToken = require('../middleware/authMiddleware'); // Import auth middleware
// authenticateToken wird hier für '/' nicht mehr benötigt
// const authenticateToken = require('../middleware/authMiddleware');
const jwt = require('jsonwebtoken');
require('dotenv').config();
@ -11,6 +12,7 @@ const router = express.Router();
const JWT_SECRET = process.env.JWT_SECRET;
// Helper function to check if a user is already logged in (valid token exists)
// Wird für /login und /register verwendet, um eingeloggte User zur Hauptseite umzuleiten
const checkAlreadyLoggedIn = (req, res, next) => {
const token = req.cookies.token;
if (token) {
@ -30,10 +32,9 @@ const checkAlreadyLoggedIn = (req, res, next) => {
};
// Serve the main todo app page (index.html) - Requires authentication
// The authenticateToken middleware will redirect to /login if not authenticated
router.get('/', authenticateToken, (req, res) => {
// The user is authenticated, serve the main app page
// Serve the main todo app page (index.html) - KEINE Authentifizierung mehr hier
// Die Seite wird immer geladen. Das Frontend-JS prüft den Login-Status.
router.get('/', (req, res) => {
res.sendFile(path.join(__dirname, '..', 'public', 'index.html'));
});

View File

@ -32,7 +32,7 @@ app.use(express.static(path.join(__dirname, 'public')));
// --- Routes ---
// API routes
app.use('/api/auth', authRoutes); // Authentication routes (login, register, logout)
app.use('/api/auth', authRoutes); // Authentication routes (login, register, logout, status)
app.use('/api/todos', todoRoutes); // Todo CRUD routes (protected by auth middleware inside the router)
// View routes (serving HTML pages)
@ -42,10 +42,22 @@ app.use('/', viewRoutes);
// --- Global Error Handler (Basic Example) ---
// Catches errors passed via next(error)
// Catches errors passed via next(error) or uncaught errors in route handlers
// ***** GEÄNDERT: Sendet jetzt JSON zurück *****
app.use((err, req, res, next) => {
console.error("Global Error Handler:", err.stack);
res.status(500).send('Etwas ist schiefgelaufen!');
console.error("Global Error Handler:", err.stack || err); // Log the full error stack
// Check if the response headers have already been sent
if (res.headersSent) {
return next(err); // Delegate to default Express error handler if headers are sent
}
// Send a generic JSON error response
res.status(500).json({
message: 'Ein unerwarteter Serverfehler ist aufgetreten.',
// Optional: Nur im Entwicklungsmodus detailliertere Fehler senden
// error: process.env.NODE_ENV === 'development' ? err.message : undefined
});
});
// --- Start Server ---