import {Router} from "express"; import onFinished from "on-finished"; import ApplicationComponent from "../ApplicationComponent.js"; import {logger} from "../Logger.js"; import SessionComponent from "./SessionComponent.js"; export default class PreviousUrlComponent extends ApplicationComponent { public async handleRoutes(router: Router): Promise { router.use((req, res, next) => { req.getPreviousUrl = () => { let url = req.header('referer'); if (url) { if (url.indexOf('://') >= 0) url = '/' + url.split('/').slice(3).join('/'); if (url !== req.originalUrl) return url; } if (this.getApp().asOptional(SessionComponent)) { const session = req.getSessionOptional(); url = session?.previousUrl; if (url && url !== req.originalUrl) return url; } return null; }; res.setLazyLocal('previousUrl', () => req.getPreviousUrl()); req.getIntendedUrl = () => { return req.query.redirect_uri?.toString() || null; }; if (this.getApp().asOptional(SessionComponent)) { const session = req.getSessionOptional(); if (session && req.method === 'GET') { onFinished(res, (err) => { if (err) return; const contentType = res.getHeader('content-type'); if (res.statusCode === 200 && contentType && typeof contentType !== 'number' && contentType.indexOf('text/html') >= 0) { session.previousUrl = req.originalUrl; session.save((err) => { if (err) logger.error(err, 'Error while saving session'); else logger.debug('Prev url set to', session.previousUrl); }); } }); } } next(); }); } }