auth: Fix UnauthorizedException throwing

Move conversion of Errors from AuthService to TokenStrategy.
This is necessary to correctly test the validateToken method.

Signed-off-by: Philip Molares <philip.molares@udo.edu>
This commit is contained in:
Philip Molares 2021-01-29 22:00:47 +01:00 committed by David Mehren
parent 46b5cdfb47
commit aa10e10412
No known key found for this signature in database
GPG key ID: 185982BA4C42B7C3
2 changed files with 25 additions and 24 deletions

View file

@ -6,9 +6,10 @@
import { Strategy } from 'passport-http-bearer';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable } from '@nestjs/common';
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { AuthService } from './auth.service';
import { User } from '../users/user.entity';
import { NotInDBError, TokenNotValidError } from '../errors/errors';
@Injectable()
export class TokenStrategy extends PassportStrategy(Strategy, 'token') {
@ -17,6 +18,16 @@ export class TokenStrategy extends PassportStrategy(Strategy, 'token') {
}
async validate(token: string): Promise<User> {
return this.authService.validateToken(token);
try {
return await this.authService.validateToken(token);
} catch (error) {
if (
error instanceof NotInDBError ||
error instanceof TokenNotValidError
) {
throw new UnauthorizedException(error.message);
}
throw error;
}
}
}