2021-01-24 22:24:04 +01:00
|
|
|
import {Router} from "express";
|
|
|
|
import onFinished from "on-finished";
|
2021-05-03 19:29:22 +02:00
|
|
|
|
|
|
|
import ApplicationComponent from "../ApplicationComponent.js";
|
|
|
|
import {logger} from "../Logger.js";
|
|
|
|
import SessionComponent from "./SessionComponent.js";
|
2021-01-24 22:24:04 +01:00
|
|
|
|
|
|
|
export default class PreviousUrlComponent extends ApplicationComponent {
|
2021-05-13 16:03:59 +02:00
|
|
|
public async handleRoutes(router: Router): Promise<void> {
|
2021-01-24 22:24:04 +01:00
|
|
|
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;
|
|
|
|
};
|
2021-11-24 22:08:38 +01:00
|
|
|
res.setLazyLocal('previousUrl', () => req.getPreviousUrl());
|
2021-01-24 22:24:04 +01:00
|
|
|
|
|
|
|
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();
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|