2020-07-28 10:03:25 +02:00
|
|
|
import ApplicationComponent from "../ApplicationComponent";
|
|
|
|
import {Request, Router} from "express";
|
|
|
|
import {ServerError} from "../HttpError";
|
|
|
|
import onFinished from "on-finished";
|
|
|
|
|
2020-09-25 22:03:22 +02:00
|
|
|
export default class RedirectBackComponent extends ApplicationComponent {
|
2020-07-28 10:03:25 +02:00
|
|
|
public static getPreviousURL(req: Request, defaultUrl?: string): string | undefined {
|
|
|
|
return req.session?.previousUrl || defaultUrl;
|
|
|
|
}
|
|
|
|
|
|
|
|
public async handle(router: Router): Promise<void> {
|
|
|
|
router.use((req, res, next) => {
|
2020-09-25 23:42:15 +02:00
|
|
|
res.redirectBack = (defaultUrl?: string): void => {
|
2020-07-28 10:03:25 +02:00
|
|
|
const previousUrl = RedirectBackComponent.getPreviousURL(req, defaultUrl);
|
|
|
|
if (!previousUrl) throw new ServerError(`Couldn't redirect you back.`);
|
|
|
|
res.redirect(previousUrl);
|
|
|
|
};
|
|
|
|
|
|
|
|
res.locals.getPreviousURL = (defaultUrl?: string) => {
|
|
|
|
return RedirectBackComponent.getPreviousURL(req, defaultUrl);
|
|
|
|
};
|
|
|
|
|
|
|
|
onFinished(res, (err) => {
|
2020-09-25 23:42:15 +02:00
|
|
|
const session = req.session;
|
|
|
|
if (session) {
|
|
|
|
const contentType = res.getHeader('content-type');
|
|
|
|
if (!err && res.statusCode === 200 && (
|
|
|
|
contentType && typeof contentType !== 'number' && contentType.indexOf('text/html') >= 0
|
|
|
|
)) {
|
|
|
|
session.previousUrl = req.originalUrl;
|
2020-11-02 17:48:52 +01:00
|
|
|
req.log.debug('Prev url set to', session.previousUrl);
|
2020-09-25 23:42:15 +02:00
|
|
|
session.save((err) => {
|
2020-07-28 10:03:25 +02:00
|
|
|
if (err) {
|
2020-11-02 17:48:52 +01:00
|
|
|
req.log.error(err, 'Error while saving session');
|
2020-07-28 10:03:25 +02:00
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
next();
|
|
|
|
});
|
|
|
|
}
|
2020-09-25 23:42:15 +02:00
|
|
|
}
|