From e37184e5eebf9de804f3f6e28330659af3e65f3e Mon Sep 17 00:00:00 2001 From: Alice Gaudon Date: Thu, 1 Oct 2020 13:59:19 +0200 Subject: [PATCH] Add user model to RequireAuth middlewares --- src/auth/AuthComponent.ts | 48 ++++++++++++++++++++++++++++----------- 1 file changed, 35 insertions(+), 13 deletions(-) diff --git a/src/auth/AuthComponent.ts b/src/auth/AuthComponent.ts index 44509bc..bad574d 100644 --- a/src/auth/AuthComponent.ts +++ b/src/auth/AuthComponent.ts @@ -51,40 +51,62 @@ export class AuthMiddleware extends Middleware { } export class RequireRequestAuthMiddleware extends Middleware { + private user?: User; + protected async handle(req: Request, res: Response, next: NextFunction): Promise { const proof = await req.as(AuthMiddleware).getAuthGuard().isAuthenticatedViaRequest(req); - if (!proof) { - req.flash('error', `You must be logged in to access ${req.url}.`); - res.redirect(Controller.route('auth', undefined, { - redirect_uri: req.url, - })); + const user = await proof?.getResource(); + if (user) { + this.user = user; + next(); return; } - next(); + req.flash('error', `You must be logged in to access ${req.url}.`); + res.redirect(Controller.route('auth', undefined, { + redirect_uri: req.url, + })); + } + + public getUser(): User { + if (!this.user) throw new Error('user not initialized.'); + return this.user; } } export class RequireAuthMiddleware extends Middleware { + private user?: User; + protected async handle(req: Request, res: Response, next: NextFunction): Promise { const authGuard = req.as(AuthMiddleware).getAuthGuard(); // Via request - if (await authGuard.isAuthenticatedViaRequest(req)) { + let proof = await authGuard.isAuthenticatedViaRequest(req); + let user = await proof?.getResource(); + if (user) { + this.user = user; next(); return; } // Via session - if (!await authGuard.isAuthenticated(req.getSession())) { - req.flash('error', `You must be logged in to access ${req.url}.`); - res.redirect(Controller.route('auth', undefined, { - redirect_uri: req.url, - })); + proof = await authGuard.isAuthenticated(req.getSession()); + user = await proof?.getResource(); + if (user) { + this.user = user; + next(); return; } - next(); + req.flash('error', `You must be logged in to access ${req.url}.`); + res.redirect(Controller.route('auth', undefined, { + redirect_uri: req.url, + })); + } + + public getUser(): User { + if (!this.user) throw new Error('user not initialized.'); + return this.user; } }