Repository navigation
MSPCA 55: Sign-in flow #38
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
38 commits
Select commit
Hold shift + click to select a range
d558e32
added animal entity
shreeyaadhikari 574967c
add migration to create animal table
shreeyaadhikari d6f7cbf
added animal service logic w chameloen id existence checks
shreeyaadhikari 13af06a
validate animal exists in post/recommendations
shreeyaadhikari c01e1ec
validate animal exists in post/matches
shreeyaadhikari 4d31981
validate added animals exist in patch/volunteers/id/animal-preference
shreeyaadhikari 2f8c81a
Add animal availability page with filters, animal card, and modal
pujitakalinadhabhotla 3d04de3
Merge main and address review feedback on animal availability
pujitakalinadhabhotla b0280f6
Update animal availability UI to match latest designs
pujitakalinadhabhotla 87e96be
addressed comments
pujitakalinadhabhotla e0b7c84
MSPCA-51 Add navbar to the app layout (#31)
Juwang110 cc07561
address comments
pujitakalinadhabhotla a992d97
merge conflicts
pujitakalinadhabhotla 3313a35
address comments
pujitakalinadhabhotla cee7cef
Enable cognito JWT guard and its tests
psmolyan 2b2ea32
Add findByCognitoSubOrFail to volunteer, coordinator, and owner services
psmolyan 791a458
Add tests for OwnerService.findByCognitoSubOrFail
psmolyan 2d9fc9b
add tests for findByCognitoSubOrFail in coords and volunteer services
psmolyan a69ff34
add GET /auth/me endpoint returning the signed-in user and role
psmolyan 506d37a
Merge remote-tracking branch 'origin/pk/mspca-46-animal-availability-…
psmolyan a2424d4
Add getMe to apiClient and AuthenticatedUser types
psmolyan 406b67a
add UserProvider that loads the signed-in user from /auth/me
psmolyan f6256bb
Add sign-in page and protect app routes with RequireAuth
psmolyan 2e3a0d2
Show the signed-in user's initials in the Navbar
psmolyan 469cd89
Use the signed-in volunteer's ID when requesting an animal
psmolyan d4b83ab
Remove useVolunteerId and parseVolunteerId now that the signed-in use…
psmolyan d9f01f9
Match the sign-in page to the Lo-Fi, with the error state
psmolyan 1dac225
Apply team conventions: theme tokens, inputGroup, try/catch, and an e…
psmolyan 947c9f1
ask unconfirmed users to verify their email when signing in
psmolyan c2a64e4
address comments
pujitakalinadhabhotla 83cb6ba
address comments
pujitakalinadhabhotla 0e737c0
Merge remote-tracking branch 'origin/pk/mspca-46-animal-availability-…
psmolyan e8515ac
review comments: load coordinator volunteers, least-priviledge role w…
psmolyan 8ac2c42
review comments: route sections, remove nextStep, sign-in page tweaks
psmolyan 7083b53
review comments: route sections, fetchstate and auth check in userpro…
psmolyan 21b7409
add a temporary sign out button and assignedVolunteers to the coordin…
psmolyan 1d34406
review comments: pick role from appRoles[0], errorElement, disabled A…
psmolyan f17c897
Merge remote-tracking branch 'origin/main' into ps/mspca-55-sign-in
psmolyan File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,184 @@ | ||
| import { Test, TestingModule } from '@nestjs/testing'; | ||
| import { | ||
| ForbiddenException, | ||
| Logger, | ||
| NotFoundException, | ||
| UnauthorizedException, | ||
| } from '@nestjs/common'; | ||
| import { Request } from 'express'; | ||
| import { AuthController } from './auth.controller'; | ||
| import { CognitoService } from '../aws/cognito/cognito.service'; | ||
| import { AccessTokenPayload, CognitoRole } from '../aws/cognito/cognito.types'; | ||
| import { VolunteersService } from '../volunteers/volunteers.service'; | ||
| import { CoordinatorsService } from '../coordinators/coordinators.service'; | ||
| import { OwnersService } from '../owners/owners.service'; | ||
| import { FosterVolunteer } from '../volunteers/volunteers.entity'; | ||
| import { FosterCoordinator } from '../coordinators/coordinators.entity'; | ||
| import { Owner } from '../owners/owners.entity'; | ||
|
|
||
| describe('AuthController', () => { | ||
| let controller: AuthController; | ||
| let cognitoService: { getUser: jest.Mock }; | ||
| let volunteersService: { findByCognitoSubOrFail: jest.Mock }; | ||
| let coordinatorsService: { findByCognitoSubOrFail: jest.Mock }; | ||
| let ownersService: { findByCognitoSubOrFail: jest.Mock }; | ||
| let warnSpy: jest.SpyInstance; | ||
|
|
||
| const request = {} as Request; | ||
| const volunteer = { volunteerId: 1, firstName: 'Jane' } as FosterVolunteer; | ||
| const coordinator = { | ||
| coordinatorId: 2, | ||
| firstName: 'Cora', | ||
| } as FosterCoordinator; | ||
| const owner = { ownerId: 3, firstName: 'Olive' } as Owner; | ||
|
|
||
| // Builds a verified token payload with the given Cognito groups. | ||
| const payloadWithGroups = (groups?: string[]) => | ||
| ({ | ||
| sub: 'cognito-sub-123', | ||
| 'cognito:groups': groups, | ||
| iss: 'https://cognito-idp.us-east-2.amazonaws.com/us-east-2_TestPool', | ||
| token_use: 'access', | ||
| client_id: 'test-client-id', | ||
| exp: 9999999999, | ||
| iat: 1, | ||
| } as AccessTokenPayload); | ||
|
|
||
| beforeEach(async () => { | ||
| cognitoService = { getUser: jest.fn() }; | ||
| volunteersService = { findByCognitoSubOrFail: jest.fn() }; | ||
| coordinatorsService = { findByCognitoSubOrFail: jest.fn() }; | ||
| ownersService = { findByCognitoSubOrFail: jest.fn() }; | ||
|
|
||
| const module: TestingModule = await Test.createTestingModule({ | ||
| controllers: [AuthController], | ||
| providers: [ | ||
| { provide: CognitoService, useValue: cognitoService }, | ||
| { provide: VolunteersService, useValue: volunteersService }, | ||
| { provide: CoordinatorsService, useValue: coordinatorsService }, | ||
| { provide: OwnersService, useValue: ownersService }, | ||
| ], | ||
| }).compile(); | ||
|
|
||
| controller = module.get(AuthController); | ||
| warnSpy = jest.spyOn(Logger.prototype, 'warn').mockImplementation(); | ||
| }); | ||
|
|
||
| afterEach(() => { | ||
| jest.restoreAllMocks(); | ||
| }); | ||
|
|
||
| describe('getMe', () => { | ||
| it('returns the volunteer for a FosterVolunteer', async () => { | ||
| cognitoService.getUser.mockReturnValue( | ||
| payloadWithGroups([CognitoRole.FosterVolunteer]), | ||
| ); | ||
| volunteersService.findByCognitoSubOrFail.mockResolvedValue(volunteer); | ||
|
|
||
| const result = await controller.getMe(request); | ||
|
|
||
| expect(cognitoService.getUser).toHaveBeenCalledWith(request); | ||
| expect(volunteersService.findByCognitoSubOrFail).toHaveBeenCalledWith( | ||
| 'cognito-sub-123', | ||
| ); | ||
| expect(result).toEqual({ | ||
| role: CognitoRole.FosterVolunteer, | ||
| user: volunteer, | ||
| }); | ||
| expect(warnSpy).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it('returns the coordinator for a FosterCoordinator', async () => { | ||
| cognitoService.getUser.mockReturnValue( | ||
| payloadWithGroups([CognitoRole.FosterCoordinator]), | ||
| ); | ||
| coordinatorsService.findByCognitoSubOrFail.mockResolvedValue(coordinator); | ||
|
|
||
| const result = await controller.getMe(request); | ||
|
|
||
| expect(coordinatorsService.findByCognitoSubOrFail).toHaveBeenCalledWith( | ||
| 'cognito-sub-123', | ||
| ); | ||
| expect(result).toEqual({ | ||
| role: CognitoRole.FosterCoordinator, | ||
| user: coordinator, | ||
| }); | ||
| }); | ||
|
|
||
| it('returns the owner for an Owner', async () => { | ||
| cognitoService.getUser.mockReturnValue( | ||
| payloadWithGroups([CognitoRole.Owner]), | ||
| ); | ||
| ownersService.findByCognitoSubOrFail.mockResolvedValue(owner); | ||
|
|
||
| const result = await controller.getMe(request); | ||
|
|
||
| expect(ownersService.findByCognitoSubOrFail).toHaveBeenCalledWith( | ||
| 'cognito-sub-123', | ||
| ); | ||
| expect(result).toEqual({ role: CognitoRole.Owner, user: owner }); | ||
| }); | ||
|
|
||
| it('uses the least privileged role and logs a warning when the user is in several groups', async () => { | ||
| cognitoService.getUser.mockReturnValue( | ||
| payloadWithGroups([ | ||
| CognitoRole.Owner, | ||
| CognitoRole.FosterCoordinator, | ||
| CognitoRole.FosterVolunteer, | ||
| ]), | ||
| ); | ||
| volunteersService.findByCognitoSubOrFail.mockResolvedValue(volunteer); | ||
|
|
||
| const result = await controller.getMe(request); | ||
|
|
||
| expect(result.role).toBe(CognitoRole.FosterVolunteer); | ||
| expect(coordinatorsService.findByCognitoSubOrFail).not.toHaveBeenCalled(); | ||
| expect(ownersService.findByCognitoSubOrFail).not.toHaveBeenCalled(); | ||
| expect(warnSpy).toHaveBeenCalledWith( | ||
| 'User cognito-sub-123 is in multiple groups (FosterVolunteer, FosterCoordinator, Owner); using the least privileged role', | ||
| ); | ||
| }); | ||
|
|
||
| it('throws UnauthorizedException when no verified user is attached', async () => { | ||
| cognitoService.getUser.mockReturnValue(null); | ||
|
|
||
| await expect(controller.getMe(request)).rejects.toThrow( | ||
| new UnauthorizedException('No user attached to the request'), | ||
| ); | ||
| expect(volunteersService.findByCognitoSubOrFail).not.toHaveBeenCalled(); | ||
| expect(coordinatorsService.findByCognitoSubOrFail).not.toHaveBeenCalled(); | ||
| expect(ownersService.findByCognitoSubOrFail).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it('throws ForbiddenException when the token has no groups', async () => { | ||
| cognitoService.getUser.mockReturnValue(payloadWithGroups(undefined)); | ||
|
|
||
| await expect(controller.getMe(request)).rejects.toThrow( | ||
| new ForbiddenException('User does not have an application role'), | ||
| ); | ||
| }); | ||
|
|
||
| it('throws ForbiddenException when none of the groups are app roles', async () => { | ||
| cognitoService.getUser.mockReturnValue( | ||
| payloadWithGroups(['SomeOtherGroup']), | ||
| ); | ||
|
|
||
| await expect(controller.getMe(request)).rejects.toThrow( | ||
| new ForbiddenException('User does not have an application role'), | ||
| ); | ||
| }); | ||
|
|
||
| it('propagates NotFoundException when no record matches the sub', async () => { | ||
| cognitoService.getUser.mockReturnValue( | ||
| payloadWithGroups([CognitoRole.FosterVolunteer]), | ||
| ); | ||
| volunteersService.findByCognitoSubOrFail.mockRejectedValue( | ||
| new NotFoundException('Volunteer not found'), | ||
| ); | ||
|
|
||
| await expect(controller.getMe(request)).rejects.toThrow( | ||
| new NotFoundException('Volunteer not found'), | ||
| ); | ||
| }); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,110 @@ | ||
| import { | ||
| Controller, | ||
| ForbiddenException, | ||
| Get, | ||
| HttpStatus, | ||
| Logger, | ||
| Req, | ||
| UnauthorizedException, | ||
| } from '@nestjs/common'; | ||
| import { ApiOperation, ApiResponse, ApiTags } from '@nestjs/swagger'; | ||
| import { Request } from 'express'; | ||
| import { CognitoService } from '../aws/cognito/cognito.service'; | ||
| import { CognitoRole } from '../aws/cognito/cognito.types'; | ||
| import { VolunteersService } from '../volunteers/volunteers.service'; | ||
| import { CoordinatorsService } from '../coordinators/coordinators.service'; | ||
| import { OwnersService } from '../owners/owners.service'; | ||
| import { AuthenticatedUser } from './auth.types'; | ||
|
|
||
| @ApiTags('Auth') | ||
| @Controller('auth') | ||
| export class AuthController { | ||
| private readonly logger = new Logger(AuthController.name); | ||
|
|
||
| constructor( | ||
| private readonly cognitoService: CognitoService, | ||
| private readonly volunteersService: VolunteersService, | ||
| private readonly coordinatorsService: CoordinatorsService, | ||
| private readonly ownersService: OwnersService, | ||
| ) {} | ||
|
|
||
| /** | ||
| * Returns the signed-in user, looked up by the Cognito sub in their token. | ||
| * | ||
| * The user's Cognito group decides which table they're looked up in. A user | ||
| * should only be in one group. If they're in several, a warning is logged | ||
| * and they get their least privileged role: FosterVolunteer, then | ||
| * FosterCoordinator, then Owner. | ||
| * | ||
| * @param req - The request, after CognitoJWTGuard has verified its token. | ||
| * @returns The user's role and their record. | ||
| * @throws {UnauthorizedException} If no verified user is attached to the request. | ||
| * @throws {ForbiddenException} If the user is in none of the app's groups. | ||
| * @throws {NotFoundException} If no record matches the user's Cognito sub. | ||
| */ | ||
| @Get('me') | ||
| @ApiOperation({ | ||
| summary: 'Get the signed-in user and their role', | ||
| }) | ||
| @ApiResponse({ | ||
| status: HttpStatus.OK, | ||
| description: 'The signed-in user and their role', | ||
| }) | ||
| @ApiResponse({ | ||
| status: HttpStatus.UNAUTHORIZED, | ||
| description: 'No valid access token was provided', | ||
| }) | ||
| @ApiResponse({ | ||
| status: HttpStatus.FORBIDDEN, | ||
| description: "The user is not in any of the app's groups", | ||
| }) | ||
| @ApiResponse({ | ||
| status: HttpStatus.NOT_FOUND, | ||
| description: "No user record matches the token's Cognito sub", | ||
| }) | ||
| async getMe(@Req() req: Request): Promise<AuthenticatedUser> { | ||
| const payload = this.cognitoService.getUser(req); | ||
| if (!payload) { | ||
| throw new UnauthorizedException('No user attached to the request'); | ||
| } | ||
|
|
||
| const groups = payload['cognito:groups'] ?? []; | ||
|
|
||
| const appRoles = Object.values(CognitoRole).filter((role) => | ||
| groups.includes(role), | ||
| ); | ||
| if (appRoles.length > 1) { | ||
| this.logger.warn( | ||
| `User ${payload.sub} is in multiple groups (${appRoles.join( | ||
| ', ', | ||
| )}); using the least privileged role`, | ||
| ); | ||
| } | ||
|
|
||
| // CognitoRole lists roles from least to most privileged, so the first | ||
| // match is the user's least privileged role. | ||
| switch (appRoles[0]) { | ||
| case CognitoRole.FosterVolunteer: | ||
| return { | ||
| role: CognitoRole.FosterVolunteer, | ||
| user: await this.volunteersService.findByCognitoSubOrFail( | ||
| payload.sub, | ||
| ), | ||
| }; | ||
| case CognitoRole.FosterCoordinator: | ||
| return { | ||
| role: CognitoRole.FosterCoordinator, | ||
| user: await this.coordinatorsService.findByCognitoSubOrFail( | ||
| payload.sub, | ||
| ), | ||
| }; | ||
| case CognitoRole.Owner: | ||
| return { | ||
| role: CognitoRole.Owner, | ||
| user: await this.ownersService.findByCognitoSubOrFail(payload.sub), | ||
| }; | ||
| default: | ||
| throw new ForbiddenException('User does not have an application role'); | ||
| } | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| import { Module } from '@nestjs/common'; | ||
| import { AuthController } from './auth.controller'; | ||
| import { CognitoModule } from '../aws/cognito/cognito.module'; | ||
| import { VolunteersModule } from '../volunteers/volunteers.module'; | ||
| import { CoordinatorsModule } from '../coordinators/coordinators.module'; | ||
| import { OwnersModule } from '../owners/owners.module'; | ||
|
|
||
| @Module({ | ||
| imports: [CognitoModule, VolunteersModule, CoordinatorsModule, OwnersModule], | ||
| controllers: [AuthController], | ||
| }) | ||
| export class AuthModule {} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,13 @@ | ||
| import { CognitoRole } from '../aws/cognito/cognito.types'; | ||
| import { FosterCoordinator } from '../coordinators/coordinators.entity'; | ||
| import { Owner } from '../owners/owners.entity'; | ||
| import { VolunteerWithoutPrivateFields } from '../volunteers/dtos/volunteer-without-private-fields.dto'; | ||
|
|
||
| /** | ||
| * The signed-in user returned by GET /auth/me: their role, plus their | ||
| * record from the table that matches that role. | ||
| */ | ||
| export type AuthenticatedUser = | ||
| | { role: CognitoRole.FosterVolunteer; user: VolunteerWithoutPrivateFields } | ||
| | { role: CognitoRole.FosterCoordinator; user: FosterCoordinator } | ||
| | { role: CognitoRole.Owner; user: Owner }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.