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

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;