@apolitical/server
Version:
Node.js module to encapsulate Apolitical's express server setup
23 lines (21 loc) • 882 B
JavaScript
;
module.exports = ({ jwtApoliticalMiddleware, serverError: { Forbidden }, config }) => {
const { COOKIE_KEY } = config.JWT.APOLITICAL;
// Define external options
return ({ allowLoggedOut = false } = {}) => {
// Return middleware handler
return async function handler(req, res, next) {
// Verifies Apolitical JWT token
const user = await jwtApoliticalMiddleware(req, res);
// If logged out users are not allowed and there is no user object throws forbidden error
if (!allowLoggedOut && !user) {
return next(new Forbidden('Cannot authenticate action', ['cookie-jwt', 'logged-out']));
}
// Assigns user to the request object
Object.assign(req, { user });
// Assigns auth token to the request object
Object.assign(req, { authToken: req.cookies[COOKIE_KEY] });
return next();
};
};
};