-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.ts
98 lines (83 loc) · 2.59 KB
/
app.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
// Load environment variables
import dotenv from "dotenv";
dotenv.config();
// Connect to the database
import connectToDatabase from "./config/dbConfig.js";
connectToDatabase();
import path from "path";
import { fileURLToPath } from "url";
import express, { Request, Response, NextFunction } from "express";
import expressLayouts from "express-ejs-layouts";
import session from "express-session";
import cookieParser from "cookie-parser";
import jwt from "jsonwebtoken";
import flash from "connect-flash";
// Get __dirname in ES module
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const app = express();
// Middleware
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(
session({
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: true,
cookie: { secure: false },
})
);
app.use(cookieParser());
app.use(express.static(path.join(__dirname, "public")));
app.use(expressLayouts);
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "ejs");
app.use(flash());
// Flash message middleware
app.use((req: Request, res: Response, next: NextFunction): void => {
res.locals.successMessage = req.flash("success");
res.locals.errorMessage = req.flash("error");
next();
});
interface DecodedToken {
firstName: string;
lastName: string;
}
// Authentication middleware
app.use((req: Request, res: Response, next: NextFunction): void => {
const token = req.cookies.authToken;
if (token) {
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET) as DecodedToken;
res.locals.isLoggedIn = true;
res.locals.username = `${decoded.firstName} ${decoded.lastName}`.trim();
} catch (error) {
console.error("Invalid token:", (error as Error).message);
res.locals.isLoggedIn = false;
res.locals.username = null;
}
} else {
res.locals.isLoggedIn = false;
res.locals.username = null;
}
next();
});
// Import routes
import indexRoutes from "./routes/indexRoutes.js";
import userRoutes from "./routes/userRoutes.js";
app.use("/", indexRoutes);
app.use("/users", userRoutes);
// 404 handler
app.use((req: Request, res: Response): void => {
const locals = { title: "404 | Page Not Found" };
res.status(404).render("404", {
locals,
layout: "layouts/errorLayout",
});
});
// Start server
const PORT = process.env.PORT || 4000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
export default app;