61 lines
2.6 KiB
JavaScript
61 lines
2.6 KiB
JavaScript
// Shared web middleware for auth, media, and upload handling.
|
|
|
|
const express = require('express');
|
|
const fs = require('fs');
|
|
const registerErrorPageMiddleware = require('#src/web/middleware/error-page');
|
|
|
|
module.exports = function registerMiddleware(app, deps) {
|
|
const pool = deps.pool;
|
|
const loadCurrentUser = deps.loadCurrentUser;
|
|
const requireAuth = deps.requireAuth;
|
|
const mediaDir = deps.MEDIA_DIR;
|
|
const uploadsDir = deps.UPLOADS_DIR;
|
|
const thumbnailsDir = deps.THUMBNAILS_DIR;
|
|
const assetDir = deps.ASSET_DIR;
|
|
|
|
app.use(express.urlencoded({ extended: true }));
|
|
app.use(express.json());
|
|
app.use('/assets', express.static(assetDir));
|
|
app.use('/media', express.static(mediaDir));
|
|
fs.mkdirSync(uploadsDir, { recursive: true });
|
|
fs.mkdirSync(thumbnailsDir, { recursive: true });
|
|
|
|
app.use(async function (req, _res, next) {
|
|
try {
|
|
req.currentUser = await loadCurrentUser(pool, req);
|
|
req.authenticatedUser = req.currentUser && req.currentUser.authenticatedUser
|
|
? req.currentUser.authenticatedUser
|
|
: req.currentUser;
|
|
next();
|
|
} catch (error) {
|
|
next(error);
|
|
}
|
|
});
|
|
|
|
registerErrorPageMiddleware(app, deps.pages);
|
|
|
|
app.use(function (req, res, next) {
|
|
const isViewAsStop = req.method === 'POST' && req.path === '/settings/view-as/stop';
|
|
if (req.currentUser && req.currentUser.isViewingAs && !['GET', 'HEAD', 'OPTIONS'].includes(String(req.method || '').toUpperCase()) && !isViewAsStop) {
|
|
const error = new Error('This preview is read-only. Exit View as to make changes.');
|
|
error.statusCode = 403;
|
|
error.expose = true;
|
|
return next(error);
|
|
}
|
|
|
|
if (req.path === '/' || req.path === '/login' || req.path === '/logout' || req.path === '/forgot-password' || req.path === '/reset-password' || req.path === '/verify-email' || req.path === '/slides/popup-preview' || req.path.indexOf('/api/internal/slide-thumbnails/') === 0 || req.path === '/api/internal/sync/player-media' || req.path === '/api/internal/sync/player-font' || req.path === '/api/internal/sync/player-control') {
|
|
return next();
|
|
}
|
|
|
|
return requireAuth(req, res, function () {
|
|
const mustChangePassword = req.currentUser && req.currentUser.isViewingAs
|
|
? Boolean(req.authenticatedUser && req.authenticatedUser.mustChangePassword)
|
|
: Boolean(req.authenticatedUser && req.authenticatedUser.mustChangePassword || req.currentUser && req.currentUser.mustChangePassword);
|
|
if (mustChangePassword && req.path !== '/account/password' && req.path !== '/settings/view-as/stop' && req.path !== '/logout') {
|
|
return res.redirect('/account/password');
|
|
}
|
|
|
|
next();
|
|
});
|
|
});
|
|
}; |