added jwt service. Currently it has some bugs and it is not very functional.
Also restructured the project a bit - created a service folder for the database script and the token script.
This commit is contained in:
@@ -1,4 +1,6 @@
|
|||||||
DB_HOST=mysql
|
DB_HOST=mysql
|
||||||
DB_USER=root
|
DB_USER=root
|
||||||
DB_PASSWORD=D7Ze0lwV9hMrNQHdz1Q8yi0MIQuOO8
|
DB_PASSWORD=D7Ze0lwV9hMrNQHdz1Q8yi0MIQuOO8
|
||||||
DB_NAME=bikelane
|
DB_NAME=bikelane
|
||||||
|
|
||||||
|
SECRET_KEY=vFzEmezKz5GAwVaaf02xHoSnk8toDikTgWyqwdBa2LIHORPevHDHf72eL4ylCfrDxQ2wFN5CtXj12KTTJmCg7q0kGaPeEbfDE1MxofcsEjYKCD5WsJsdKNGegx2qALgy
|
@@ -9,35 +9,35 @@ import {
|
|||||||
updateUser,
|
updateUser,
|
||||||
deleteUser,
|
deleteUser,
|
||||||
getAllUsers,
|
getAllUsers,
|
||||||
} from "./database.js";
|
} from "./services/database.js";
|
||||||
|
import { generateToken, authenticate } from "./services/tokenService.js";
|
||||||
import cookieParser from "cookie-parser";
|
import cookieParser from "cookie-parser";
|
||||||
import bodyParser from "body-parser";
|
|
||||||
import jose from "jose";
|
|
||||||
|
|
||||||
//view engine ejs
|
//view engine ejs
|
||||||
app.set("view engine", "ejs");
|
app.set("view engine", "ejs");
|
||||||
|
|
||||||
app.use(express.json());
|
app.use(express.json());
|
||||||
|
|
||||||
app.use(cors());
|
app.use(cors());
|
||||||
|
app.use(cookieParser());
|
||||||
|
|
||||||
app.post("/api/login", async (req, res) => {
|
app.post("/api/login", async (req, res) => {
|
||||||
console.log(req.body);
|
console.log(req.body);
|
||||||
|
|
||||||
loginUser(req.body.username, req.body.password)
|
try {
|
||||||
.then((result) => {
|
const result = await loginUser(req.body.username, req.body.password);
|
||||||
if (result.success) {
|
if (result.success) {
|
||||||
res.status(200).json(result, { message: "Login successful" }); // Here send the jwt token
|
const userToken = await generateToken({ username: req.body.username });
|
||||||
} else {
|
res.status(200).json(
|
||||||
res.status(401).json(result, { message: "Invalid credentials" });
|
result, // This is the user data that logged in
|
||||||
}
|
{ message: "Login successful", token: userToken }
|
||||||
})
|
);
|
||||||
.catch((err) => {
|
} else {
|
||||||
console.error("Error logging in:", err);
|
res.status(401).json(result, { message: "Invalid credentials" });
|
||||||
res
|
}
|
||||||
.status(500)
|
} catch (err) {
|
||||||
.json({ success: false, message: "Internal server error" });
|
console.error("Error logging in:", err);
|
||||||
});
|
res.status(500).json({ success: false, message: "Internal server error" });
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
app.get("/api/getAllUsers", async (req, res) => {
|
app.get("/api/getAllUsers", async (req, res) => {
|
||||||
@@ -47,7 +47,9 @@ app.get("/api/getAllUsers", async (req, res) => {
|
|||||||
})
|
})
|
||||||
.catch((err) => {
|
.catch((err) => {
|
||||||
console.error("Error fetching users:", err);
|
console.error("Error fetching users:", err);
|
||||||
res.status(500).json({ success: false, message: "Internal server error" });
|
res
|
||||||
|
.status(500)
|
||||||
|
.json({ success: false, message: "Internal server error" });
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -60,4 +62,4 @@ app.use((err, req, res, next) => {
|
|||||||
// Log the error stack and send a generic error response
|
// Log the error stack and send a generic error response
|
||||||
console.error(err.stack);
|
console.error(err.stack);
|
||||||
res.status(500).send("Something broke!");
|
res.status(500).send("Something broke!");
|
||||||
});
|
});
|
||||||
|
28
backend/services/tokenService.js
Normal file
28
backend/services/tokenService.js
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
import cookieParser from "cookie-parser";
|
||||||
|
import bodyParser from "body-parser";
|
||||||
|
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) {
|
||||||
|
return await new SignJWT(payload)
|
||||||
|
.setProtectedHeader({ alg: "HS256" })
|
||||||
|
.setIssuedAt()
|
||||||
|
.setExpirationTime("2h") // Token valid for 2 hours
|
||||||
|
.sign(secret);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function authenticate(req, res, next) {
|
||||||
|
const token = req.cookies.token;
|
||||||
|
|
||||||
|
if (!token) return res.status(401).send("No token provided");
|
||||||
|
|
||||||
|
try {
|
||||||
|
const { payload } = await jwtVerify(token, secret);
|
||||||
|
req.user = payload;
|
||||||
|
next();
|
||||||
|
} catch (e) {
|
||||||
|
return res.status(403).send("Invalid or expired token");
|
||||||
|
}
|
||||||
|
}
|
@@ -1 +0,0 @@
|
|||||||
test
|
|
@@ -34,6 +34,7 @@ const LoginCard: React.FC<LoginCardProps> = ({ onClose }) => {
|
|||||||
.then(async (response) => {
|
.then(async (response) => {
|
||||||
if (response.ok) {
|
if (response.ok) {
|
||||||
const data = await response.json();
|
const data = await response.json();
|
||||||
|
Cookies.set("token", data.token, { expires: 7 });
|
||||||
onClose();
|
onClose();
|
||||||
Cookies.set("name", data.user.first_name, { expires: 7 });
|
Cookies.set("name", data.user.first_name, { expires: 7 });
|
||||||
await fetch("http://localhost:5002/api/getAllUsers")
|
await fetch("http://localhost:5002/api/getAllUsers")
|
||||||
|
Reference in New Issue
Block a user