swaf/src/auth/AuthComponent.ts

67 lines
2.3 KiB
TypeScript

import ApplicationComponent from "../ApplicationComponent";
import {Express, NextFunction, Request, Response, Router} from "express";
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;
}
public async start(app: Express, router: Router): Promise<void> {
router.use(async (req, res, next) => {
req.authGuard = this.authGuard;
res.locals.user = await req.authGuard.getUserForSession(req.session!);
next();
});
}
public async stop(): Promise<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') || '/');
return;
}
req.models.user = await req.authGuard.getUserForRequest(req);
next();
};
export const REQUIRE_AUTH_MIDDLEWARE = async (req: Request, res: Response, next: NextFunction): Promise<void> => {
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();
}
};
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> => {
if (!req.models.user || !req.models.user.isAdmin()) {
throw new ForbiddenHttpError('secret tool', req.url);
}
next();
};