Skip to content

Commit

Permalink
fix: 🐛 return accessToken instead of hard code
Browse files Browse the repository at this point in the history
  • Loading branch information
zhumeisongsong committed Dec 2, 2024
1 parent b687b28 commit 45fb656
Show file tree
Hide file tree
Showing 5 changed files with 171 additions and 11 deletions.
50 changes: 50 additions & 0 deletions libs/auth/application/src/lib/auth.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,54 @@ describe('AuthService', () => {
it('should be defined', () => {
expect(service).toBeDefined();
});

describe('signIn', () => {
it('should return access token when credentials are valid', async () => {
const mockEmail = '[email protected]';
const mockPassword = 'password123';
const mockUser = {
id: '123',
email: mockEmail,
firstName: 'John',
lastName: 'Doe',
};
const mockAccessToken = 'mock.jwt.token';

jest.spyOn(service['awsCognitoService'], 'signIn').mockResolvedValue({});
jest
.spyOn(service['usersService'], 'findByEmail')
.mockResolvedValue(mockUser);
jest
.spyOn(service['jwtService'], 'signAsync')
.mockResolvedValue(mockAccessToken);

const result = await service.signIn(mockEmail, mockPassword);

expect(result).toEqual({ accessToken: mockAccessToken });
expect(service['awsCognitoService'].signIn).toHaveBeenCalledWith(
mockEmail,
mockPassword,
);
expect(service['usersService'].findByEmail).toHaveBeenCalledWith(
mockEmail,
);
expect(service['jwtService'].signAsync).toHaveBeenCalledWith({
sub: mockUser.id,
username: mockUser.email,
});
});

it('should throw UnauthorizedException when credentials are invalid', async () => {
const mockEmail = '[email protected]';
const mockPassword = 'wrongpassword';

jest
.spyOn(service['awsCognitoService'], 'signIn')
.mockRejectedValue(new Error('Invalid credentials'));

await expect(service.signIn(mockEmail, mockPassword)).rejects.toThrow(
'Unauthorized',
);
});
});
});
34 changes: 23 additions & 11 deletions libs/auth/application/src/lib/auth.service.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,33 @@
import { UnauthorizedException } from '@nestjs/common';
import { UsersService } from '@users/application';
import { JwtService } from '@nestjs/jwt';
import { AwsCognitoService } from '@shared/infrastructure-aws-cognito';

export class AuthService {
constructor(private readonly awsCognitoService: AwsCognitoService) {}
constructor(
private awsCognitoService: AwsCognitoService,
private usersService: UsersService,
private jwtService: JwtService,
) {}

async signIn(
username: string,
email: string,
pass: string,
): Promise<{
accessToken: string;
}> {
// TODO: Implement sign in
// Step 1: Validate user credentials via AWS Cognito
const authResponse = await this.awsCognitoService.signIn(username, pass);
// Step 2: Retrieve user from the database
// Step 3: Generate a custom JWT access token

return {
accessToken: 'accessToken',
};
try {
await this.awsCognitoService.signIn(email, pass);
const user = await this.usersService.findByEmail(email);
const accessToken = await this.jwtService.signAsync({
sub: user.id,
username: user.email,
});
return {
accessToken,
};
} catch (error) {
throw new UnauthorizedException(error);
}
}
}
5 changes: 5 additions & 0 deletions libs/users/application/src/lib/users.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,9 @@ export class UsersService {
async findById(id: string): Promise<User | null> {
return this.getUserUseCase.execute(id);
}

async findByEmail(email: string): Promise<User | null> {
// TODO: refactor getUserUseCase
return this.getUserUseCase.execute(email);
}
}
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
"@nestjs/config": "^3.3.0",
"@nestjs/core": "^10.4.7",
"@nestjs/graphql": "^12.2.1",
"@nestjs/jwt": "^10.2.0",
"@nestjs/mongoose": "^10.1.0",
"@nestjs/platform-express": "^10.4.7",
"@nestjs/throttler": "^6.2.1",
Expand Down
92 changes: 92 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 45fb656

Please sign in to comment.