swaf/src/auth/AuthComponent.ts

74 lines
2.4 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";
export default class AuthComponent extends ApplicationComponent<void> {
private readonly authGuard: AuthGuard<any>;
public constructor(authGuard: AuthGuard<any>) {
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;
res.locals.user = await (await req.authGuard.getProof(req))?.getResource();
2020-04-24 12:12:27 +02:00
next();
});
}
}
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
req.models.user = await proof.getResource();
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) {
req.models.user = await proof.getResource();
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
}
req.models.user = await proof.getResource();
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();
};