|
| 1 | +import express, { type Request, type Response } from "express" |
| 2 | +import logger from "morgan" |
| 3 | +import { join } from "node:path" |
| 4 | + |
| 5 | +import { |
| 6 | + errorHandler, |
| 7 | + errorNotFoundHandler, |
| 8 | +} from "./middleware/error.middleware.js" |
| 9 | + |
| 10 | +import { |
| 11 | + authenticatedUser, |
| 12 | + currentSession, |
| 13 | +} from "./middleware/auth.middleware.js" |
| 14 | +import { ExpressAuth } from "@auth/express" |
| 15 | +import { authConfig } from "./config/auth.config.js" |
| 16 | +import * as pug from "pug" |
| 17 | + |
| 18 | +export const app = express() |
| 19 | + |
| 20 | +app.set("port", process.env.PORT || 3004) |
| 21 | + |
| 22 | +// @ts-expect-error (https://stackoverflow.com/questions/45342307/error-cannot-find-module-pug) |
| 23 | +app.engine("pug", pug.__express) |
| 24 | +app.set("views", join(import.meta.dirname, "..", "views")) |
| 25 | +app.set("view engine", "pug") |
| 26 | + |
| 27 | +// Trust Proxy for Proxies (Heroku, Render.com, Docker behind Nginx, etc) |
| 28 | +// https://stackoverflow.com/questions/40459511/in-express-js-req-protocol-is-not-picking-up-https-for-my-secure-link-it-alwa |
| 29 | +app.set("trust proxy", true) |
| 30 | + |
| 31 | +app.use(logger("dev")) |
| 32 | + |
| 33 | +// Serve static files |
| 34 | +// NB: Uncomment this out if you want Express to serve static files for you vs. using a |
| 35 | +// hosting provider which does so for you (for example through a CDN). |
| 36 | +// app.use(express.static(join(import.meta.dirname, "..", "public"))) |
| 37 | + |
| 38 | +// Parse incoming requests data |
| 39 | +app.use(express.urlencoded({ extended: true })) |
| 40 | +app.use(express.json()) |
| 41 | + |
| 42 | +// Set session in res.locals |
| 43 | +app.use(currentSession) |
| 44 | + |
| 45 | +// Set up ExpressAuth to handle authentication |
| 46 | +// IMPORTANT: It is highly encouraged set up rate limiting on this route |
| 47 | +app.use("/api/auth/*", ExpressAuth(authConfig)) |
| 48 | + |
| 49 | +// Routes |
| 50 | +app.get("/protected", async (_req: Request, res: Response) => { |
| 51 | + res.render("protected", { session: res.locals.session }) |
| 52 | +}) |
| 53 | + |
| 54 | +app.get( |
| 55 | + "/api/protected", |
| 56 | + authenticatedUser, |
| 57 | + async (_req: Request, res: Response) => { |
| 58 | + res.json(res.locals.session) |
| 59 | + }, |
| 60 | +) |
| 61 | + |
| 62 | +app.get("/", async (_req: Request, res: Response) => { |
| 63 | + res.render("index", { |
| 64 | + title: "Express Auth Example", |
| 65 | + user: res.locals.session?.user, |
| 66 | + }) |
| 67 | +}) |
| 68 | + |
| 69 | +// Error handlers |
| 70 | +app.use(errorNotFoundHandler) |
| 71 | +app.use(errorHandler) |
0 commit comments