2020-04-24 12:12:27 +02:00
|
|
|
import ApplicationComponent from "../ApplicationComponent";
|
2020-07-11 11:46:16 +02:00
|
|
|
import {NextFunction, Request, Response, Router} from "express";
|
2020-04-24 12:12:27 +02:00
|
|
|
import AuthGuard from "./AuthGuard";
|
|
|
|
import Controller from "../Controller";
|
|
|
|
import {ForbiddenHttpError} from "../HttpError";
|
|
|
|
|
|
|
|
export default class AuthComponent extends ApplicationComponent<void> {
|
|
|
|
private readonly authGuard: AuthGuard<any>;
|
|
|
|
|
|
|
|
public constructor(authGuard: AuthGuard<any>) {
|
|
|
|
super();
|
|
|
|
this.authGuard = authGuard;
|
|
|
|
}
|
|
|
|
|
2020-07-11 11:46:16 +02:00
|
|
|
public async init(router: Router): Promise<void> {
|
2020-04-24 12:12:27 +02:00
|
|
|
router.use(async (req, res, next) => {
|
|
|
|
req.authGuard = this.authGuard;
|
|
|
|
res.locals.user = await req.authGuard.getUserForSession(req.session!);
|
|
|
|
next();
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-06-14 21:47:18 +02:00
|
|
|
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') || '/');
|
|
|
|
return;
|
|
|
|
}
|
2020-06-16 11:12:58 +02:00
|
|
|
|
2020-06-14 21:47:18 +02:00
|
|
|
req.models.user = await req.authGuard.getUserForRequest(req);
|
|
|
|
next();
|
|
|
|
};
|
2020-04-24 12:12:27 +02:00
|
|
|
|
|
|
|
export const REQUIRE_AUTH_MIDDLEWARE = async (req: Request, res: Response, next: NextFunction): Promise<void> => {
|
2020-06-14 11:59:02 +02:00
|
|
|
if (await req.authGuard.isAuthenticatedViaRequest(req)) {
|
|
|
|
req.models.user = await req.authGuard.getUserForRequest(req);
|
|
|
|
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') || '/');
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
req.models.user = await req.authGuard.getUserForSession(req.session!);
|
|
|
|
next();
|
2020-04-24 12:12:27 +02:00
|
|
|
}
|
|
|
|
};
|
|
|
|
export const REQUIRE_GUEST_MIDDLEWARE = async (req: Request, res: Response, next: NextFunction): Promise<void> => {
|
|
|
|
if (await req.authGuard.isAuthenticated(req.session!)) {
|
|
|
|
res.redirectBack('/');
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
next();
|
|
|
|
};
|
|
|
|
export const REQUIRE_ADMIN_MIDDLEWARE = async (req: Request, res: Response, next: NextFunction): Promise<void> => {
|
2020-06-16 11:12:58 +02:00
|
|
|
if (!req.models.user || !req.models.user.is_admin) {
|
2020-04-24 12:12:27 +02:00
|
|
|
throw new ForbiddenHttpError('secret tool', req.url);
|
|
|
|
}
|
|
|
|
|
|
|
|
next();
|
|
|
|
};
|