swaf/src/auth/AuthComponent.ts

75 lines
2.3 KiB
TypeScript
Raw Normal View History

2020-04-24 12:12:27 +02:00
import ApplicationComponent from "../ApplicationComponent";
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";
2020-09-23 08:46:37 +02:00
export default class AuthComponent<T extends AuthGuard<any>> extends ApplicationComponent<void> {
private readonly authGuard: T;
2020-04-24 12:12:27 +02:00
2020-09-23 08:46:37 +02:00
public constructor(authGuard: T) {
2020-04-24 12:12:27 +02:00
super();
this.authGuard = authGuard;
}
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;
req.models.user = res.locals.user = await (await req.authGuard.getProof(req))?.getResource();
2020-04-24 12:12:27 +02:00
next();
});
}
2020-09-23 08:46:37 +02:00
public getAuthGuard(): T {
return this.authGuard;
}
2020-04-24 12:12:27 +02:00
}
2020-06-14 21:47:18 +02:00
export const REQUIRE_REQUEST_AUTH_MIDDLEWARE = async (req: Request, res: Response, next: NextFunction): Promise<void> => {
let proof = await req.authGuard.isAuthenticatedViaRequest(req);
if (!proof) {
2020-06-14 21:47:18 +02:00
req.flash('error', `You must be logged in to access ${req.url}.`);
2020-07-15 11:42:49 +02:00
res.redirect(Controller.route('auth', undefined, {
redirect_uri: req.url,
}));
2020-06-14 21:47:18 +02:00
return;
}
2020-06-16 11:12:58 +02:00
2020-06-14 21:47:18 +02:00
next();
};
2020-04-24 12:12:27 +02:00
export const REQUIRE_AUTH_MIDDLEWARE = async (req: Request, res: Response, next: NextFunction): Promise<void> => {
// Via request
let proof = await req.authGuard.isAuthenticatedViaRequest(req);
if (proof) {
next();
return;
}
// Via session
proof = await req.authGuard.isAuthenticated(req.session!);
if (!proof) {
req.flash('error', `You must be logged in to access ${req.url}.`);
res.redirect(Controller.route('auth', undefined, {
redirect_uri: req.url,
}));
return;
2020-04-24 12:12:27 +02:00
}
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();
2020-04-24 12:12:27 +02:00
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();
};