69 lines
2.4 KiB
TypeScript
69 lines
2.4 KiB
TypeScript
import ApplicationComponent from "../ApplicationComponent";
|
|
import {NextFunction, Request, Response, Router} from "express";
|
|
import AuthGuard from "./AuthGuard";
|
|
import Controller from "../Controller";
|
|
import {ForbiddenHttpError} from "../HttpError";
|
|
import * as querystring from "querystring";
|
|
|
|
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> {
|
|
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<void> => {
|
|
if (!await req.authGuard.isAuthenticatedViaRequest(req)) {
|
|
req.flash('error', `You must be logged in to access ${req.url}.`);
|
|
res.redirect((Controller.route('auth') || '/') + '?' + querystring.stringify({
|
|
redirect_uri: req.url,
|
|
}));
|
|
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') || '/') + '?' + querystring.stringify({
|
|
redirect_uri: req.url,
|
|
}));
|
|
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.is_admin) {
|
|
throw new ForbiddenHttpError('secret tool', req.url);
|
|
}
|
|
|
|
next();
|
|
}; |