From 8b27f6f39359e33b42a461821b73431473f5ccb7 Mon Sep 17 00:00:00 2001 From: Philip Molares Date: Wed, 27 Jan 2021 21:55:30 +0100 Subject: [PATCH] auth: Fix handling of internal server errors Catch all NotInDbErrors and TokenNotValidError and transform them to UnauthorizedException with the correct message. This prevents nest from telling the api user that an internal server error has happened and instead display the correct http error code 401. Signed-off-by: Philip Molares --- src/auth/auth.service.ts | 24 ++++++++++++++---------- src/auth/token.strategy.ts | 8 ++------ 2 files changed, 16 insertions(+), 16 deletions(-) diff --git a/src/auth/auth.service.ts b/src/auth/auth.service.ts index b4d0e794f..e6b7c3a94 100644 --- a/src/auth/auth.service.ts +++ b/src/auth/auth.service.ts @@ -4,7 +4,7 @@ * SPDX-License-Identifier: AGPL-3.0-only */ -import { Injectable } from '@nestjs/common'; +import { Injectable, UnauthorizedException } from '@nestjs/common'; import { UsersService } from '../users/users.service'; import { User } from '../users/user.entity'; import { AuthToken } from './auth-token.entity'; @@ -35,16 +35,20 @@ export class AuthService { } async validateToken(token: string): Promise { - const [keyId, secret] = token.split('.'); - const accessToken = await this.getAuthTokenAndValidate(keyId, secret); - await this.setLastUsedToken(keyId); - const user = await this.usersService.getUserByUsername( - accessToken.user.userName, - ); - if (user) { - return user; + try { + const [keyId, secret] = token.split('.'); + const accessToken = await this.getAuthTokenAndValidate(keyId, secret); + await this.setLastUsedToken(keyId); + return this.usersService.getUserByUsername(accessToken.user.userName); + } catch (error) { + if ( + error instanceof NotInDBError || + error instanceof TokenNotValidError + ) { + throw new UnauthorizedException(error.message); + } + throw error; } - return null; } async hashPassword(cleartext: string): Promise { diff --git a/src/auth/token.strategy.ts b/src/auth/token.strategy.ts index 317b255f4..4f4f4e002 100644 --- a/src/auth/token.strategy.ts +++ b/src/auth/token.strategy.ts @@ -6,7 +6,7 @@ import { Strategy } from 'passport-http-bearer'; import { PassportStrategy } from '@nestjs/passport'; -import { Injectable, UnauthorizedException } from '@nestjs/common'; +import { Injectable } from '@nestjs/common'; import { AuthService } from './auth.service'; import { User } from '../users/user.entity'; @@ -17,10 +17,6 @@ export class TokenStrategy extends PassportStrategy(Strategy, 'token') { } async validate(token: string): Promise { - const user = await this.authService.validateToken(token); - if (!user) { - throw new UnauthorizedException(); - } - return user; + return this.authService.validateToken(token); } }