104 lines
2.8 KiB
JavaScript
104 lines
2.8 KiB
JavaScript
const bcrypt = require("bcryptjs");
|
|
const jwt = require("jsonwebtoken");
|
|
const { Pool } = require("pg");
|
|
|
|
// Datenbankverbindung
|
|
const pool = new Pool({
|
|
user: process.env.DB_USER,
|
|
host: process.env.DB_HOST,
|
|
database: process.env.DB_NAME,
|
|
password: process.env.DB_PASSWORD,
|
|
port: 5432,
|
|
});
|
|
|
|
// Registrierungsfunktion
|
|
const registerUser = async (req, res) => {
|
|
const { username, password, email, role } = req.body;
|
|
try {
|
|
// Überprüfen, ob der Benutzer bereits existiert
|
|
|
|
const userExists = await pool.query(
|
|
"SELECT * FROM Users WHERE email = $1",
|
|
[email]
|
|
);
|
|
if (userExists.rows.length > 0) {
|
|
return res.status(400).json({ message: "Benutzer existiert bereits" });
|
|
}
|
|
|
|
// Passwort hashen
|
|
const hashedPassword = await bcrypt.hash(password, 10);
|
|
|
|
// Neuen Benutzer einfügen
|
|
const newUser = await pool.query(
|
|
"INSERT INTO Users (username, password, email, role, is_active) VALUES ($1, $2, $3, $4, $5) RETURNING *",
|
|
[username, hashedPassword, email, role, true]
|
|
);
|
|
|
|
res
|
|
.status(201)
|
|
.json({ message: "Benutzer registriert", user: newUser.rows[0] });
|
|
} catch (err) {
|
|
res
|
|
.status(500)
|
|
.json({ message: "Fehler beim Registrieren", error: err.message });
|
|
}
|
|
};
|
|
|
|
// Loginfunktion
|
|
const loginUser = async (req, res) => {
|
|
const { email, password } = req.body;
|
|
try {
|
|
// Überprüfen, ob der Benutzer existiert
|
|
const user = await pool.query("SELECT * FROM Users WHERE email = $1", [
|
|
email,
|
|
]);
|
|
if (user.rows.length === 0) {
|
|
return res.status(400).json({ message: "Benutzer nicht gefunden" });
|
|
}
|
|
|
|
// Passwort vergleichen
|
|
const validPassword = await bcrypt.compare(password, user.rows[0].password);
|
|
if (!validPassword) {
|
|
return res.status(400).json({ message: "Ungültiges Passwort" });
|
|
}
|
|
|
|
// JWT Token erstellen
|
|
const token = jwt.sign(
|
|
{ id: user.rows[0].id, role: user.rows[0].role },
|
|
process.env.JWT_SECRET,
|
|
{
|
|
expiresIn: "3h",
|
|
}
|
|
);
|
|
|
|
res.status(200).json({ message: "Login erfolgreich", token });
|
|
} catch (err) {
|
|
res.status(500).json({ message: "Fehler beim Login", error: err.message });
|
|
}
|
|
};
|
|
|
|
const updateUser = async (req, res) => {
|
|
const { id, username, password, email, role } = req.body;
|
|
try {
|
|
const updateUser = await pool.query(
|
|
"UPDATE users SET username = $1, password = $2, email = $3, role = $4 WHERE id = $5 RETURNING *",
|
|
[username, password, email, role, id]
|
|
);
|
|
res
|
|
.status(200)
|
|
.json({
|
|
message: "Benutzerdaten aktualisiert",
|
|
user: updateUser.rows[0],
|
|
});
|
|
} catch (err) {
|
|
res
|
|
.status(500)
|
|
.json({
|
|
message: "Fehler beim Aktualisieren der Benutzerdaten",
|
|
error: err.message,
|
|
});
|
|
}
|
|
};
|
|
|
|
module.exports = { registerUser, loginUser, updateUser };
|