Skip to content

Commit 6734aff

Browse files
committed
feat: add redirectIfNotAuthenticatedMiddleware to enforce authentication before accessing app routes
We were previously relying on API calls to redirect the user on app load, but if the user does not have a session then there is no reason to server the application
1 parent 7a7bd61 commit 6734aff

File tree

2 files changed

+13
-0
lines changed

2 files changed

+13
-0
lines changed

apps/api/src/app/routes/route.middleware.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -167,6 +167,17 @@ export async function redirectIfMfaEnrollmentRequiredMiddleware(req: express.Req
167167
next();
168168
}
169169

170+
export async function redirectIfNotAuthenticatedMiddleware(req: express.Request, res: express.Response, next: express.NextFunction) {
171+
const user = req.session.user;
172+
173+
if (!user || user.id === PLACEHOLDER_USER_ID) {
174+
res.redirect(302, '/auth/login');
175+
return;
176+
}
177+
178+
next();
179+
}
180+
170181
export async function checkAuth(req: express.Request, res: express.Response, next: express.NextFunction) {
171182
const userAgent = req.get('User-Agent');
172183

apps/api/src/main.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ import {
3939
destroySessionIfPendingVerificationIsExpired,
4040
notFoundMiddleware,
4141
redirectIfMfaEnrollmentRequiredMiddleware,
42+
redirectIfNotAuthenticatedMiddleware,
4243
redirectIfPendingTosAcceptanceMiddleware,
4344
redirectIfPendingVerificationMiddleware,
4445
setApplicationCookieMiddleware,
@@ -427,6 +428,7 @@ if (ENV.NODE_ENV === 'production' && !ENV.CI && cluster.isPrimary) {
427428
app.use(
428429
'/app',
429430
spaRateLimit,
431+
redirectIfNotAuthenticatedMiddleware,
430432
redirectIfPendingVerificationMiddleware,
431433
redirectIfPendingTosAcceptanceMiddleware,
432434
redirectIfMfaEnrollmentRequiredMiddleware,

0 commit comments

Comments
 (0)