swaf/src/auth/AuthComponent.ts

57 lines
1.9 KiB
TypeScript
Raw Normal View History

2020-04-24 12:12:27 +02:00
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_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();
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> => {
if (!req.models.user || !req.models.user.isAdmin()) {
throw new ForbiddenHttpError('secret tool', req.url);
}
next();
};