From 4db72178766455a61f444145b2aed35c4b970d2d Mon Sep 17 00:00:00 2001 From: Alice Gaudon Date: Wed, 30 Dec 2020 14:10:58 +0100 Subject: [PATCH] Controller: add useMiddleware method --- src/Controller.ts | 11 +++++++++++ src/auth/AuthController.ts | 8 +++++--- src/helpers/BackendController.ts | 13 ++++++------- 3 files changed, 22 insertions(+), 10 deletions(-) diff --git a/src/Controller.ts b/src/Controller.ts index 610d546..304b4c5 100644 --- a/src/Controller.ts +++ b/src/Controller.ts @@ -77,6 +77,17 @@ export default abstract class Controller { this.router.use(this.wrap(handler)); } + protected useMiddleware(...middlewares: MiddlewareType[]): void { + for (const middleware of middlewares) { + const instance = new middleware(this.getApp()); + if (instance instanceof FileUploadMiddleware) { + this.fileUploadFormRouter.use(this.wrap(instance.getRequestHandler())); + } else { + this.router.use(this.wrap(instance.getRequestHandler())); + } + } + } + protected get( path: PathParams, handler: RequestHandler, diff --git a/src/auth/AuthController.ts b/src/auth/AuthController.ts index 113a646..94681ba 100644 --- a/src/auth/AuthController.ts +++ b/src/auth/AuthController.ts @@ -24,9 +24,11 @@ export default class AuthController extends Controller { next(); }); - this.get('/', this.getAuth, 'auth', RequireGuestMiddleware); - this.post('/login', this.postLogin, 'login', RequireGuestMiddleware); - this.post('/register', this.postRegister, 'register', RequireGuestMiddleware); + this.useMiddleware(RequireGuestMiddleware); + + this.get('/', this.getAuth, 'auth'); + this.post('/login', this.postLogin, 'login'); + this.post('/register', this.postRegister, 'register'); } protected async getAuth(req: Request, res: Response, _next: NextFunction): Promise { diff --git a/src/helpers/BackendController.ts b/src/helpers/BackendController.ts index 107f46e..21958b1 100644 --- a/src/helpers/BackendController.ts +++ b/src/helpers/BackendController.ts @@ -38,14 +38,13 @@ export default class BackendController extends Controller { } public routes(): void { - this.get('/', this.getIndex, 'backend', RequireAuthMiddleware, RequireAdminMiddleware); + this.useMiddleware(RequireAuthMiddleware, RequireAdminMiddleware); + + this.get('/', this.getIndex, 'backend'); if (User.isApprovalMode()) { - this.get('/accounts-approval', this.getAccountApproval, 'accounts-approval', - RequireAuthMiddleware, RequireAdminMiddleware); - this.post('/accounts-approval/approve', this.postApproveAccount, 'approve-account', - RequireAuthMiddleware, RequireAdminMiddleware); - this.post('/accounts-approval/reject', this.postRejectAccount, 'reject-account', - RequireAuthMiddleware, RequireAdminMiddleware); + this.get('/accounts-approval', this.getAccountApproval, 'accounts-approval'); + this.post('/accounts-approval/approve', this.postApproveAccount, 'approve-account'); + this.post('/accounts-approval/reject', this.postRejectAccount, 'reject-account'); } }