-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
214 lines (191 loc) · 7.84 KB
/
server.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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
// Express Modules
import express from "express";
import cors from "cors";
import compression from "compression";
import morgan from "morgan";
// SuperTokens Modules
import SuperTokens from "supertokens-node";
import Session from "supertokens-node/recipe/session/index.js";
import ThirdParty from "supertokens-node/recipe/thirdparty/index.js";
import Passwordless from "supertokens-node/recipe/passwordless/index.js";
import EmailPassword from "supertokens-node/recipe/emailpassword/index.js";
// Miscellaneous + Local Modules
import { createRequestHandler } from "@remix-run/express";
import { installGlobals } from "@remix-run/node";
import { serialize, parse } from "cookie";
import "dotenv/config"; // Side effect
import { commonRoutes } from "./app/utils/constants.js";
import {
authCookieNames,
deleteCookieSettings,
deleteRefreshSettings,
} from "./app/utils/supertokens/cookieHelpers.server.js";
const port = process.env.PORT || 3000;
const publicPages = [
"/",
commonRoutes.login,
commonRoutes.resetPassword,
commonRoutes.emailExists,
commonRoutes.loginPasswordless,
commonRoutes.loginThirdParty,
];
const app = express();
/* -------------------- Super Tokens -------------------- */
SuperTokens.init({
framework: "express",
supertokens: {
connectionURI: /** @type {string} */ (process.env.SUPERTOKENS_CONNECTION_URI),
apiKey: process.env.SUPERTOKENS_API_KEY,
},
appInfo: {
appName: "Testing Remix with Custom Backend",
websiteDomain: process.env.SUPERTOKENS_WEBSITE_DOMAIN,
apiDomain: /** @type {string} */ (process.env.SUPERTOKENS_API_DOMAIN),
apiBasePath: process.env.SUPERTOKENS_API_BASE_PATH,
},
recipeList: [
// Initializes passwordless features
Passwordless.init({ contactMethod: "EMAIL_OR_PHONE", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK" }),
EmailPassword.init(), // Initializes signin / signup features
Session.init(), // Initializes session features
// Initializes ThirdParty auth features
ThirdParty.init({
signInAndUpFeature: {
providers: [
// Built-in Providers
{
config: {
thirdPartyId: "github",
requireEmail: true,
clients: [
{
clientId: /** @type {string} */ (process.env.GITHUB_OAUTH_CLIENT_ID),
clientSecret: /** @type {string} */ (process.env.GITHUB_OAUTH_CLIENT_SECRET),
scope: ["user:email"],
},
],
},
},
// Custom Providers
{
config: {
thirdPartyId: "planningcenter",
requireEmail: true,
authorizationEndpoint: "https://api.planningcenteronline.com/oauth/authorize",
tokenEndpoint: "https://api.planningcenteronline.com/oauth/token",
userInfoEndpoint: "https://api.planningcenteronline.com/people/v2/me/emails?where[primary]=true",
userInfoMap: {
fromUserInfoAPI: {
userId: "data.0.relationships.person.data.id",
email: "data.0.attributes.address",
emailVerified: "data.0.attributes.primary", // Weak, but the best thing that we can work with
},
// See: https://github.com/supertokens/supertokens-node/issues/954
fromIdTokenPayload: {
userId: undefined,
email: undefined,
emailVerified: undefined,
},
},
clients: [
{
clientId: /** @type {string} */ (process.env.PLANNING_CENTER_OAUTH_CLIENT_ID),
clientSecret: /** @type {string} */ (process.env.PLANNING_CENTER_OAUTH_CLIENT_SECRET),
scope: ["people"],
},
],
},
},
],
},
}),
],
});
app.use(
cors({
origin: process.env.SUPERTOKENS_WEBSITE_DOMAIN,
allowedHeaders: ["content-type", ...SuperTokens.getAllCORSHeaders()],
credentials: true,
}),
);
/* -------------------- End > Super Tokens -------------------- */
// http://expressjs.com/en/advanced/best-practice-security.html#at-a-minimum-disable-x-powered-by-header
app.disable("x-powered-by");
app.use(compression());
app.use(morgan("tiny"));
installGlobals();
const viteDevServer =
process.env.NODE_ENV === "production"
? undefined
: await import("vite").then((vite) => vite.createServer({ server: { middlewareMode: true } }));
// Handle asset requests
if (viteDevServer) app.use(viteDevServer.middlewares);
else {
// Vite fingerprints its assets so we can cache forever.
app.use("/assets", express.static("build/client/assets", { immutable: true, maxAge: "1y" }));
}
// Everything else (like favicon.ico) is cached for an hour. You may want to be more aggressive with this caching.
app.use(express.static("build/client", { maxAge: "1h" }));
app.all(
"*",
setupRemixContext,
createRequestHandler({
getLoadContext: (_, res) => /** @type {import("@remix-run/node").AppLoadContext} */ ({ ...res.locals }),
// TODO: Maybe create an issue letting Remix know that their types are a little janky...
build: viteDevServer
? () => viteDevServer.ssrLoadModule("virtual:remix/server-build")
: // @ts-expect-error -- Sometimes the build file won't exist during local development
/** @type {any} */ (await import("./build/server/index.js")),
}),
);
app.listen(port, () => {
console.log(`Express server listening on port ${port}`);
});
/* -------------------- Our Own Helpers/Functions -------------------- */
/**
* Derives all the data that needs to be passed to `Remix`'s `getLoadContext` and attaches it to `res.locals`.
* Also redirects unauthenticated and session-expired users to the proper auth route.
* @param {import("express").Request} req
* @param {import("express").Response} res
* @param {import("express").NextFunction} next
*/
async function setupRemixContext(req, res, next) {
try {
const cookies = parse(req.headers.cookie ?? "");
const accessToken = cookies[authCookieNames.access] ?? "";
const antiCsrfToken = cookies[authCookieNames.csrf];
const session = await Session.getSessionWithoutRequestResponse(accessToken, antiCsrfToken);
const userId = session.getUserId();
res.locals.user = userId ? { id: userId } : undefined;
return next();
} catch (error) {
if (!Session.Error.isErrorFromSuperTokens(error)) return res.status(500).send("An unexpected error occurred");
// URL Details
const url = new URL(`${req.protocol}://${req.get("host")}${req.originalUrl}`);
const isDataRequest = url.searchParams.has("_data");
if (isDataRequest) url.searchParams.delete("_data");
const userNeedsSessionRefresh = error.type === Session.Error.TRY_REFRESH_TOKEN;
const requestAllowed =
publicPages.includes(url.pathname) || (userNeedsSessionRefresh && url.pathname === commonRoutes.refreshSession);
if (requestAllowed) {
res.locals.user = undefined;
return next();
}
const basePath = userNeedsSessionRefresh ? commonRoutes.refreshSession : commonRoutes.login;
const returnUrl = encodeURI(`${url.pathname}${url.search}`);
const redirectUrl = `${basePath}?returnUrl=${returnUrl}`;
// Delete the user's tokens if they don't need to attempt a token refresh.
if (!userNeedsSessionRefresh) {
res.setHeader("Set-Cookie", [
serialize(authCookieNames.access, "", deleteCookieSettings),
serialize(authCookieNames.refresh, "", deleteRefreshSettings),
serialize(authCookieNames.csrf, "", deleteCookieSettings),
]);
}
// Redirect the user to the proper auth page.
return isDataRequest
? // Special handling for redirects from `Remix` data requests
res.status(204).setHeader("x-remix-redirect", redirectUrl).send()
: res.redirect(userNeedsSessionRefresh ? 307 : 303, redirectUrl);
}
}