Login korrigiert
This commit is contained in:
parent
61956b562c
commit
304971502d
|
@ -5,7 +5,15 @@ const authRoutes = require("./routes/auth");
|
|||
const bodyParser = require("body-parser");
|
||||
|
||||
// Middleware
|
||||
app.use(bodyParser.json());
|
||||
app.use(express.json());
|
||||
app.use(express.urlencoded({ extended: true }));
|
||||
|
||||
const authenticateToken = require("./middleware/authenticateToken");
|
||||
|
||||
// Beispiel für eine geschützte Route
|
||||
app.get("/mitglieder", authenticateToken, (req, res) => {
|
||||
res.json({ message: "Dies ist eine geschützte Route", user: req.user });
|
||||
});
|
||||
|
||||
// Routes
|
||||
app.use("/auth", authRoutes);
|
||||
|
|
|
@ -14,9 +14,9 @@ const pool = new Pool({
|
|||
// 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]
|
||||
|
@ -47,7 +47,8 @@ const registerUser = async (req, res) => {
|
|||
// Loginfunktion
|
||||
const loginUser = async (req, res) => {
|
||||
const { email, password } = req.body;
|
||||
|
||||
console.log(req.body);
|
||||
console.log(email, password);
|
||||
try {
|
||||
// Überprüfen, ob der Benutzer existiert
|
||||
const user = await pool.query("SELECT * FROM Users WHERE email = $1", [
|
||||
|
@ -68,7 +69,7 @@ const loginUser = async (req, res) => {
|
|||
{ id: user.rows[0].id, role: user.rows[0].role },
|
||||
process.env.JWT_SECRET,
|
||||
{
|
||||
expiresIn: "1h",
|
||||
expiresIn: "3h",
|
||||
}
|
||||
);
|
||||
|
||||
|
|
|
@ -0,0 +1,27 @@
|
|||
const jwt = require("jsonwebtoken");
|
||||
|
||||
// Middleware zur Verifizierung des JWT-Tokens
|
||||
const authenticateToken = (req, res, next) => {
|
||||
// Holen des Tokens aus dem Authorization Header
|
||||
const authHeader = req.headers["authorization"];
|
||||
const token = authHeader && authHeader.split(" ")[1]; // 'Bearer TOKEN'
|
||||
|
||||
if (token == null) {
|
||||
return res.status(401).json({ message: "Kein Token bereitgestellt" });
|
||||
}
|
||||
|
||||
// Überprüfen des Tokens
|
||||
jwt.verify(token, process.env.JWT_SECRET, (err, user) => {
|
||||
if (err) {
|
||||
return res.status(403).json({ message: "Ungültiger Token" });
|
||||
}
|
||||
|
||||
// Wenn der Token gültig ist, wird der User in der Anfrage gespeichert
|
||||
req.user = user;
|
||||
|
||||
// Anfrage geht weiter zur nächsten Middleware/Route
|
||||
next();
|
||||
});
|
||||
};
|
||||
|
||||
module.exports = authenticateToken;
|
Loading…
Reference in New Issue