it's working!!!
This commit is contained in:
@@ -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;
|
||||
|
@@ -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.' });
|
||||
}
|
||||
|
@@ -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'));
|
||||
});
|
||||
|
||||
|
Reference in New Issue
Block a user