fix(server): auth strategies (#1459)

* fix(server): auth strategies

* chore: tests
This commit is contained in:
Jason Rasmussen
2023-01-28 00:12:11 -05:00
committed by GitHub
parent 5939d79057
commit 414893a687
9 changed files with 24 additions and 37 deletions

View File

@@ -1,5 +1,5 @@
import { APIKeyEntity } from '@app/infra/db/entities';
import { BadRequestException, UnauthorizedException } from '@nestjs/common';
import { BadRequestException } from '@nestjs/common';
import { authStub, userEntityStub, newCryptoRepositoryMock, newKeyRepositoryMock } from '../../test';
import { ICryptoRepository } from '../auth';
import { IKeyRepository } from './api-key.repository';
@@ -124,7 +124,7 @@ describe(APIKeyService.name, () => {
it('should throw an error for an invalid id', async () => {
keyMock.getKey.mockResolvedValue(null);
await expect(sut.validate(token)).rejects.toBeInstanceOf(UnauthorizedException);
await expect(sut.validate(token)).resolves.toBeNull();
expect(keyMock.getKey).toHaveBeenCalledWith('bXktYXBpLWtleQ== (hashed)');
});

View File

@@ -1,4 +1,4 @@
import { BadRequestException, Inject, Injectable, UnauthorizedException } from '@nestjs/common';
import { BadRequestException, Inject, Injectable } from '@nestjs/common';
import { AuthUserDto, ICryptoRepository } from '../auth';
import { IKeyRepository } from './api-key.repository';
import { APIKeyCreateDto } from './dto/api-key-create.dto';
@@ -56,7 +56,7 @@ export class APIKeyService {
return keys.map(mapKey);
}
async validate(token: string): Promise<AuthUserDto> {
async validate(token: string): Promise<AuthUserDto | null> {
const hashedToken = this.crypto.hashSha256(token);
const keyEntity = await this.repository.getKey(hashedToken);
if (keyEntity?.user) {
@@ -71,6 +71,6 @@ export class APIKeyService {
};
}
throw new UnauthorizedException('Invalid API Key');
return null;
}
}