|
1 | | -import express, { Application } from 'express'; |
| 1 | +import express, { Application, Request, Response } from 'express'; |
2 | 2 | import cors from 'cors'; |
3 | 3 | import morgan from 'morgan'; |
4 | 4 | import bodyParser from 'body-parser'; |
5 | 5 | import healthRoutes from './routes/healthRoutes'; |
| 6 | + |
| 7 | +// Consolidated Imports |
6 | 8 | import productRoutes from "./routes/product.routes"; |
7 | 9 | import mongoose from "mongoose"; |
| 10 | +import bcrypt from "bcryptjs"; |
| 11 | +import cookieParser from "cookie-parser"; |
| 12 | +import { signAccessToken, signRefreshToken, verifyRefreshToken } from "./controllers/auth"; |
| 13 | +import { authenticate, AuthRequest } from "./middleware/authMiddleware"; |
| 14 | + |
8 | 15 | const app: Application = express(); |
9 | 16 | import dotenv from "dotenv"; |
10 | 17 | dotenv.config(); |
| 18 | + |
11 | 19 | // Middleware setup |
12 | 20 | app.use(cors()); |
13 | 21 | app.use(morgan('dev')); |
14 | 22 | app.use(bodyParser.json()); |
15 | 23 | app.use(bodyParser.urlencoded({ extended: true })); |
| 24 | +// Middleware needed for Auth |
| 25 | +app.use(cookieParser()); |
| 26 | + |
| 27 | + |
| 28 | +// 3. User Interface and Mock Data |
| 29 | +interface User { |
| 30 | + id: string; |
| 31 | + username: string; |
| 32 | + passwordHash: string; |
| 33 | + role: string; |
| 34 | +} |
| 35 | + |
| 36 | +const users: User[] = [ |
| 37 | + { id: "1", username: "alice", passwordHash: bcrypt.hashSync("password", 8), role: "admin" }, |
| 38 | +]; |
| 39 | + |
| 40 | +const refreshTokens = new Map<string, string>() |
| 41 | + |
| 42 | + |
| 43 | +// 4. Authentication API Routes |
| 44 | +app.post("/login", async (req: Request, res: Response) => { |
| 45 | + const { username, password } = req.body; |
| 46 | + const user = users.find((u) => u.username === username); |
| 47 | + if (!user) return res.status(401).json({ error: "Invalid credentials" }); |
| 48 | + |
| 49 | + const match = await bcrypt.compare(password, user.passwordHash); |
| 50 | + if (!match) return res.status(401).json({ error: "Invalid credentials" }); |
| 51 | + |
| 52 | + const payload = { sub: user.id, username: user.username, role: user.role }; |
| 53 | + const accessToken = signAccessToken(payload); |
| 54 | + const refreshToken = signRefreshToken(payload); |
| 55 | + |
| 56 | + refreshTokens.set(user.id, refreshToken); |
16 | 57 |
|
| 58 | + res.cookie("refreshToken", refreshToken, { |
| 59 | + httpOnly: true, |
| 60 | + sameSite: "strict", |
| 61 | + secure: process.env.NODE_ENV === "production", |
| 62 | + maxAge: 7 * 24 * 60 * 60 * 1000, |
| 63 | + }); |
| 64 | + |
| 65 | + res.json({ accessToken }); |
| 66 | +}); |
| 67 | + |
| 68 | +app.post("/refresh", (req: Request, res: Response) => { |
| 69 | + const token = req.cookies?.refreshToken || req.body.refreshToken; |
| 70 | + |
| 71 | + if (!token) { |
| 72 | + return res.status(401).json({ error: "Refresh token is missing" }); |
| 73 | + } |
| 74 | + |
| 75 | + try { |
| 76 | + const payload = verifyRefreshToken(token); |
| 77 | + const storedToken = refreshTokens.get(payload.sub); |
| 78 | + |
| 79 | + if (!storedToken) { |
| 80 | + return res.status(401).json({ error: "Session not found or already logged out" }); |
| 81 | + } |
| 82 | + |
| 83 | + if (storedToken !== token) { |
| 84 | + return res.status(401).json({ error: "Token used is not the latest valid token" }); |
| 85 | + } |
| 86 | + |
| 87 | + const cleanPayload = { |
| 88 | + sub: payload.sub, |
| 89 | + username: payload.username, |
| 90 | + role: payload.role |
| 91 | + }; |
| 92 | + |
| 93 | + const newAccess = signAccessToken(cleanPayload); |
| 94 | + const newRefresh = signRefreshToken(cleanPayload); |
| 95 | + |
| 96 | + refreshTokens.set(cleanPayload.sub, newRefresh); |
| 97 | + |
| 98 | + res.cookie("refreshToken", newRefresh, { |
| 99 | + httpOnly: true, |
| 100 | + sameSite: "strict", |
| 101 | + secure: process.env.NODE_ENV === "production", |
| 102 | + maxAge: 7 * 24 * 60 * 60 * 1000, |
| 103 | + }); |
| 104 | + |
| 105 | + res.json({ accessToken: newAccess }); |
| 106 | + |
| 107 | + } catch (error) { |
| 108 | + console.error("Refresh token verification failed:", error); |
| 109 | + res.status(401).json({ error: "Refresh token is expired or invalid" }); |
| 110 | + } |
| 111 | +}); |
| 112 | + |
| 113 | +app.post("/logout", authenticate, (req: AuthRequest, res: Response) => { |
| 114 | + // req.user is guaranteed to exist by the 'authenticate' middleware |
| 115 | + refreshTokens.delete(req.user!.sub); |
| 116 | + res.clearCookie("refreshToken"); |
| 117 | + res.status(204).send(); |
| 118 | +}); |
| 119 | + |
| 120 | +app.get("/protected", authenticate, (req: AuthRequest, res: Response) => { |
| 121 | + res.json({ message: "Protected route accessed", user: req.user }); |
| 122 | +}); |
17 | 123 |
|
18 | | -// API Routes |
| 124 | +// Existing API Routes |
19 | 125 | app.use('/api/health', healthRoutes); |
20 | 126 | app.use("/api/products", productRoutes); |
21 | 127 | // Default |
22 | 128 | app.get("/", (_req, res) => { |
23 | | - res.send("API is running 🚀"); |
| 129 | + res.send("API is running "); |
24 | 130 | }); |
25 | 131 |
|
26 | 132 | // MongoDB connect (optional) |
|
0 commit comments