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
parent 5a727d530b
commit ba517b3cfe
2 changed files with 25 additions and 24 deletions

View file

@ -4,7 +4,7 @@
* SPDX-License-Identifier: AGPL-3.0-only
*/
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { Injectable } from '@nestjs/common';
import { UsersService } from '../users/users.service';
import { User } from '../users/user.entity';
import { AuthToken } from './auth-token.entity';
@ -35,7 +35,6 @@ export class AuthService {
}
async validateToken(token: string): Promise<User> {
try {
const [keyId, secret] = token.split('.');
if (secret.length > 72) {
// Only the first 72 characters of the tokens are considered by bcrypt
@ -48,15 +47,6 @@ export class AuthService {
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;
}
}
async hashPassword(cleartext: string): Promise<string> {

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;
}
}
}