import ApplicationComponent from "../ApplicationComponent"; import {NextFunction, Request, Response, Router} from "express"; import AuthGuard from "./AuthGuard"; import Controller from "../Controller"; import {ForbiddenHttpError} from "../HttpError"; export default class AuthComponent extends ApplicationComponent { private readonly authGuard: AuthGuard; public constructor(authGuard: AuthGuard) { super(); this.authGuard = authGuard; } public async init(router: Router): Promise { router.use(async (req, res, next) => { req.authGuard = this.authGuard; res.locals.user = await req.authGuard.getUserForSession(req.session!); next(); }); } } export const REQUIRE_REQUEST_AUTH_MIDDLEWARE = async (req: Request, res: Response, next: NextFunction): Promise => { 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 => { 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 => { if (await req.authGuard.isAuthenticated(req.session!)) { res.redirectBack('/'); return; } next(); }; export const REQUIRE_ADMIN_MIDDLEWARE = async (req: Request, res: Response, next: NextFunction): Promise => { if (!req.models.user || !req.models.user.is_admin) { throw new ForbiddenHttpError('secret tool', req.url); } next(); };