implement user authentication with login functionality and database integration
This commit is contained in:
@@ -0,0 +1,30 @@
|
||||
import mysql from "mysql2";
|
||||
import dotenv from "dotenv";
|
||||
dotenv.config();
|
||||
|
||||
// Ein einzelner Pool reicht; der zweite Pool benutzte fälschlich DB_TABLE als Datenbank
|
||||
const pool = mysql
|
||||
.createPool({
|
||||
host: process.env.DB_HOST,
|
||||
user: process.env.DB_USER,
|
||||
password: process.env.DB_PASSWORD,
|
||||
database: process.env.DB_NAME,
|
||||
})
|
||||
.promise();
|
||||
|
||||
export const loginFunc = async (username, password) => {
|
||||
const [result] = await pool.query(
|
||||
"SELECT * FROM users WHERE username = ? AND password = ?",
|
||||
[username, password]
|
||||
);
|
||||
if (result.length > 0) return { success: true };
|
||||
return { success: false };
|
||||
};
|
||||
|
||||
export const getItemsFromDatabase = async () => {
|
||||
const [result] = await pool.query("SELECT * FROM items");
|
||||
if (result.length > 0) {
|
||||
return { success: true, data: result };
|
||||
}
|
||||
return { success: false };
|
||||
};
|
||||
|
26
backend/services/tokenService.js
Normal file
26
backend/services/tokenService.js
Normal file
@@ -0,0 +1,26 @@
|
||||
import { SignJWT, jwtVerify } from "jose";
|
||||
import env from "dotenv";
|
||||
env.config();
|
||||
const secret = new TextEncoder().encode(process.env.SECRET_KEY);
|
||||
|
||||
export async function generateToken(payload) {
|
||||
const newToken = await new SignJWT(payload)
|
||||
.setProtectedHeader({ alg: "HS256" })
|
||||
.setIssuedAt()
|
||||
.setExpirationTime("2h") // Token valid for 2 hours
|
||||
.sign(secret);
|
||||
console.log("Generated token: ", newToken);
|
||||
return newToken;
|
||||
}
|
||||
|
||||
export async function authenticate(req, res, next) {
|
||||
const authHeader = req.headers["authorization"];
|
||||
const token = authHeader && authHeader.split(" ")[1]; // Bearer <token>
|
||||
|
||||
if (token == null) return res.sendStatus(401); // No token present
|
||||
|
||||
const { payload } = await jwtVerify(token, secret);
|
||||
req.user = payload;
|
||||
|
||||
next();
|
||||
}
|
Reference in New Issue
Block a user