RedirectBackComponent: fix it and integrate it into NunjucksComponent

This commit is contained in:
Alice Gaudon 2020-07-15 10:24:01 +02:00
parent ceeff7b7b1
commit 634edda704
6 changed files with 31 additions and 48 deletions

View File

@ -1,6 +1,6 @@
{
"name": "wms-core",
"version": "0.13.9",
"version": "0.14.0",
"description": "Node web framework",
"repository": "git@gitlab.com:ArisuOngaku/wms-core.git",
"author": "Alice Gaudon <alice@gaudon.pro>",

View File

@ -3,6 +3,7 @@ import {NextFunction, Request, Response, Router} from "express";
import AuthGuard from "./AuthGuard";
import Controller from "../Controller";
import {ForbiddenHttpError} from "../HttpError";
import * as querystring from "querystring";
export default class AuthComponent extends ApplicationComponent<void> {
private readonly authGuard: AuthGuard<any>;
@ -24,7 +25,9 @@ export default class AuthComponent extends ApplicationComponent<void> {
export const REQUIRE_REQUEST_AUTH_MIDDLEWARE = async (req: Request, res: Response, next: NextFunction): Promise<void> => {
if (!await req.authGuard.isAuthenticatedViaRequest(req)) {
req.flash('error', `You must be logged in to access ${req.url}.`);
res.redirect(Controller.route('auth') || '/');
res.redirect((Controller.route('auth') || '/') + '?' + querystring.stringify({
redirect_uri: req.url,
}));
return;
}
@ -39,7 +42,9 @@ export const REQUIRE_AUTH_MIDDLEWARE = async (req: Request, res: Response, next:
} else {
if (!await req.authGuard.isAuthenticated(req.session!)) {
req.flash('error', `You must be logged in to access ${req.url}.`);
res.redirect(Controller.route('auth') || '/');
res.redirect((Controller.route('auth') || '/') + '?' + querystring.stringify({
redirect_uri: req.url,
}));
return;
}
@ -49,7 +54,7 @@ export const REQUIRE_AUTH_MIDDLEWARE = async (req: Request, res: Response, next:
};
export const REQUIRE_GUEST_MIDDLEWARE = async (req: Request, res: Response, next: NextFunction): Promise<void> => {
if (await req.authGuard.isAuthenticated(req.session!)) {
res.redirectBack('/');
res.redirectBack();
return;
}

View File

@ -1,11 +1,16 @@
import nunjucks, {Environment} from "nunjucks";
import config from "config";
import {Express, Router} from "express";
import {Express, Request, Router} from "express";
import ApplicationComponent from "../ApplicationComponent";
import Controller from "../Controller";
import {ServerError} from "../HttpError";
import * as querystring from "querystring";
export default class NunjucksComponent extends ApplicationComponent<void> {
public static getPreviousURL(req: Request, defaultUrl?: string): string {
return req.query.redirect_uri?.toString() || req.headers.referer?.[0] || defaultUrl || '/';
}
private readonly viewsPath: string;
private env?: Environment;
@ -42,6 +47,7 @@ export default class NunjucksComponent extends ApplicationComponent<void> {
})
.addGlobal('app_version', this.app!.getVersion())
.addGlobal('core_version', coreVersion)
.addGlobal('querystring', querystring)
.addFilter('hex', (v: number) => {
return v.toString(16);
});
@ -56,6 +62,14 @@ export default class NunjucksComponent extends ApplicationComponent<void> {
res.locals.app = config.get('app');
// Redirect back
res.redirectBack = (defaultUrl?: string) => {
res.redirect(NunjucksComponent.getPreviousURL(req, defaultUrl));
};
res.locals.getPreviousURL = (defaultURL?: string) => {
return NunjucksComponent.getPreviousURL(req, defaultURL);
};
next();
});
}

View File

@ -1,39 +0,0 @@
import ApplicationComponent from "../ApplicationComponent";
import {Router} from "express";
import onFinished from "on-finished";
import Logger from "../Logger";
import {ServerError} from "../HttpError";
export default class RedirectBackComponent extends ApplicationComponent<void> {
public async init(router: Router): Promise<void> {
router.use((req, res, next) => {
if (!req.session) {
throw new Error('Session is unavailable.');
}
onFinished(res, (err) => {
if (!err && res.statusCode === 200 && (req.headers['contentType'] && req.headers['contentType'].indexOf('text/html') >= 0)) {
req.session!.previousUrl = req.originalUrl;
Logger.debug('Prev url set to', req.session!.previousUrl);
req.session!.save((err) => {
if (err) {
Logger.error(err, 'Error while saving session');
}
});
}
});
res.redirectBack = (defaultUrl?: string) => {
if (req.session && typeof req.session.previousUrl === 'string') {
res.redirect(req.session.previousUrl);
} else if (typeof defaultUrl === 'string') {
res.redirect(defaultUrl);
} else {
throw new ServerError('There is no previous url and no default redirection url was provided.');
}
};
next();
});
}
}

View File

@ -8,8 +8,10 @@
{% block body %}
<div class="container">
<div class="panel">
{% set action = route('auth') + '?' + querystring.stringify({redirect_uri: req.url}) %}
{% if register_confirm_email %}
<form action="/auth" method="POST" id="register-form">
<form action="{{ action }}" method="POST" id="register-form">
<h2>Register</h2>
{{ macros.message('question', 'Do you wish to create a new account with ' + register_confirm_email + '?', false, false) }}
{{ macros.message('warning', 'If you already have an account, please log in with your existing email first and then add your new email in the Account page.', false, true) }}
@ -26,7 +28,7 @@
{{ macros.csrf(getCSRFToken) }}
</form>
{% else %}
<form action="/auth" method="POST" id="login-form">
<form action="{{ action }}" method="POST" id="login-form">
<h2>Log in or register</h2>
{# {{ macros.message('info', 'If we don\'t find your email address in our database, you will be able to register.', false, true) }}#}
<div class="input-field">

View File

@ -19,8 +19,9 @@
<div class="error-instructions">{{ error_instructions|safe }}</div>
<nav>
{% if session.previousUrl and session.previousUrl != '/' and session.previousUrl != url %}
<a href="{{ session.previousUrl }}" class="button"><i data-feather="arrow-left"></i> Go back</a>
{% set previousURL = getPreviousURL() %}
{% if previousURL and previousURL != '/' and previousURL != url %}
<a href="{{ previousURL }}" class="button"><i data-feather="arrow-left"></i> Go back</a>
{% endif %}
<a href="/" class="button"><i data-feather="home"></i> Go to homepage</a>