-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
100 lines (86 loc) · 2.44 KB
/
index.js
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
99
100
const express = require("express");
const session = require("express-session");
const createError = require("http-errors");
const cookieParser = require("cookie-parser");
const logger = require("morgan");
const path = require("path");
const { createServer } = require("http");
const { auth, requiresAuth } = require("express-openid-connect");
const {
checkUrl,
APP_URL, // Public URL for this app
API_URL, // URL for Expenses API
ISSUER_BASE_URL, // Auth0 Tenant Url
CLIENT_ID, // Auth0 Web App Client
CLIENT_SECRET, // Auth0 Web App CLient Secret
SESSION_SECRET, // Cookie Encryption Key
PORT,
} = require("./env-config");
const app = express();
app.use(checkUrl()); // Used to normalize URL in Vercel
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "pug");
app.use(logger("combined"));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, "public")));
app.use(
auth({
secret: SESSION_SECRET,
auth0Logout: true,
baseURL: APP_URL,
authRequired: false,
})
);
const expenses = [
{
date: new Date(),
description: "Pizza for a Coding Dojo session.",
value: 102,
},
{
date: new Date(),
description: "Coffee for a Coding Dojo session.",
value: 42,
},
];
app.get("/", async (req, res) => {
res.render("home", {
user: req.oidc && req.oidc.user,
total: expenses.reduce((accum, expense) => accum + expense.value, 0),
count: expenses.length,
});
});
// 👇 add requiresAuth middlware to these private routes 👇
app.get("/user", requiresAuth(), async (req, res) => {
res.render("user", {
user: req.oidc && req.oidc.user,
id_token: req.oidc && req.oidc.idToken,
access_token: req.oidc && req.oidc.accessToken,
refresh_token: req.oidc && req.oidc.refreshToken,
});
});
app.get("/expenses", requiresAuth(), async (req, res, next) => {
res.render("expenses", {
user: req.oidc && req.oidc.user,
expenses,
});
});
// catch 404 and forward to error handler
app.use(function (req, res, next) {
next(createError(404));
});
// error handler
app.use(function (err, req, res, next) {
res.locals.message = err.message;
res.locals.error = err;
// render the error page
res.status(err.status || 500);
res.render("error", {
user: req.oidc && req.oidc.user,
});
});
createServer(app).listen(PORT, () => {
console.log(`WEB APP: ${APP_URL}`);
});