first test
This commit is contained in:
113
routes/authRoutes.js
Normal file
113
routes/authRoutes.js
Normal file
@ -0,0 +1,113 @@
|
||||
// routes/authRoutes.js
|
||||
// Handles user registration, login, and logout
|
||||
|
||||
const express = require('express');
|
||||
const bcrypt = require('bcrypt');
|
||||
const jwt = require('jsonwebtoken');
|
||||
const db = require('../db'); // Import database query function
|
||||
require('dotenv').config();
|
||||
|
||||
const router = express.Router();
|
||||
const JWT_SECRET = process.env.JWT_SECRET;
|
||||
const JWT_EXPIRES_IN = process.env.JWT_EXPIRES_IN || '1h';
|
||||
const SALT_ROUNDS = 10; // Cost factor for bcrypt hashing
|
||||
|
||||
// POST /api/auth/register - User Registration
|
||||
router.post('/register', async (req, res) => {
|
||||
const { username, password } = req.body;
|
||||
|
||||
// Basic validation
|
||||
if (!username || !password) {
|
||||
return res.status(400).json({ message: 'Benutzername und Passwort sind erforderlich.' });
|
||||
}
|
||||
|
||||
try {
|
||||
// Check if user already exists
|
||||
const userCheck = await db.query('SELECT * FROM users WHERE username = $1', [username]);
|
||||
if (userCheck.rows.length > 0) {
|
||||
return res.status(409).json({ message: 'Benutzername bereits vergeben.' }); // 409 Conflict
|
||||
}
|
||||
|
||||
// Hash the password
|
||||
const passwordHash = await bcrypt.hash(password, SALT_ROUNDS);
|
||||
|
||||
// Insert new user into the database
|
||||
const newUser = await db.query(
|
||||
'INSERT INTO users (username, password_hash) VALUES ($1, $2) RETURNING id, username',
|
||||
[username, passwordHash]
|
||||
);
|
||||
|
||||
console.log(`User registered: ${newUser.rows[0].username}`);
|
||||
// Respond with success message (or automatically log them in)
|
||||
// For simplicity, we just confirm registration here. User needs to login separately.
|
||||
res.status(201).json({ message: 'Registrierung erfolgreich. Bitte einloggen.' });
|
||||
|
||||
} catch (error) {
|
||||
console.error('Registration Error:', error);
|
||||
res.status(500).json({ message: 'Serverfehler bei der Registrierung.' });
|
||||
}
|
||||
});
|
||||
|
||||
// POST /api/auth/login - User Login
|
||||
router.post('/login', async (req, res) => {
|
||||
const { username, password } = req.body;
|
||||
|
||||
if (!username || !password) {
|
||||
return res.status(400).json({ message: 'Benutzername und Passwort sind erforderlich.' });
|
||||
}
|
||||
|
||||
try {
|
||||
// Find user by username
|
||||
const result = await db.query('SELECT * FROM users WHERE username = $1', [username]);
|
||||
const user = result.rows[0];
|
||||
|
||||
// Check if user exists and password is correct
|
||||
if (!user || !(await bcrypt.compare(password, user.password_hash))) {
|
||||
return res.status(401).json({ message: 'Ungültiger Benutzername oder Passwort.' }); // 401 Unauthorized
|
||||
}
|
||||
|
||||
// User authenticated successfully, create JWT payload
|
||||
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 });
|
||||
|
||||
// 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)
|
||||
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'
|
||||
});
|
||||
|
||||
console.log(`User logged in: ${user.username}`);
|
||||
// Send success response (client-side JS will redirect)
|
||||
res.status(200).json({ message: 'Login erfolgreich.' });
|
||||
|
||||
} catch (error) {
|
||||
console.error('Login Error:', error);
|
||||
res.status(500).json({ message: 'Serverfehler beim Login.' });
|
||||
}
|
||||
});
|
||||
|
||||
// POST /api/auth/logout - User Logout
|
||||
router.post('/logout', (req, res) => {
|
||||
// Clear the authentication cookie
|
||||
res.clearCookie('token', {
|
||||
httpOnly: true,
|
||||
secure: process.env.NODE_ENV === 'production',
|
||||
sameSite: 'Lax'
|
||||
});
|
||||
console.log('User logged out');
|
||||
res.status(200).json({ message: 'Logout erfolgreich.' });
|
||||
});
|
||||
|
||||
|
||||
module.exports = router;
|
Reference in New Issue
Block a user