diff --git a/apps/backend/src/app.module.ts b/apps/backend/src/app.module.ts index 4a4710ea6..9219e513a 100644 --- a/apps/backend/src/app.module.ts +++ b/apps/backend/src/app.module.ts @@ -9,6 +9,7 @@ import { CoordinatorsModule } from './coordinators/coordinators.module'; import { VolunteersModule } from './volunteers/volunteers.module'; import { OwnersModule } from './owners/owners.module'; import { AnimalsModule } from './animals/animals.module'; +import { AuthModule } from './auth/auth.module'; @Module({ imports: [ @@ -28,6 +29,7 @@ import { AnimalsModule } from './animals/animals.module'; VolunteersModule, OwnersModule, AnimalsModule, + AuthModule, ], }) export class AppModule {} diff --git a/apps/backend/src/auth/auth.controller.spec.ts b/apps/backend/src/auth/auth.controller.spec.ts new file mode 100644 index 000000000..2da90565d --- /dev/null +++ b/apps/backend/src/auth/auth.controller.spec.ts @@ -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'), + ); + }); + }); +}); diff --git a/apps/backend/src/auth/auth.controller.ts b/apps/backend/src/auth/auth.controller.ts new file mode 100644 index 000000000..e6c792c2b --- /dev/null +++ b/apps/backend/src/auth/auth.controller.ts @@ -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 { + 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'); + } + } +} diff --git a/apps/backend/src/auth/auth.module.ts b/apps/backend/src/auth/auth.module.ts new file mode 100644 index 000000000..485e56c43 --- /dev/null +++ b/apps/backend/src/auth/auth.module.ts @@ -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 {} diff --git a/apps/backend/src/auth/auth.types.ts b/apps/backend/src/auth/auth.types.ts new file mode 100644 index 000000000..346a456a7 --- /dev/null +++ b/apps/backend/src/auth/auth.types.ts @@ -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 }; diff --git a/apps/backend/src/aws/cognito/cognito.guard.spec.ts b/apps/backend/src/aws/cognito/cognito.guard.spec.ts index 26c5d6ae8..21b1e65ef 100644 --- a/apps/backend/src/aws/cognito/cognito.guard.spec.ts +++ b/apps/backend/src/aws/cognito/cognito.guard.spec.ts @@ -106,7 +106,7 @@ function createContext(authorization?: string): { return { context, request }; } -describe.skip('CognitoJWTGuard', () => { +describe('CognitoJWTGuard', () => { let guard: CognitoJWTGuard; let reflector: jest.Mocked>; diff --git a/apps/backend/src/aws/cognito/cognito.guard.ts b/apps/backend/src/aws/cognito/cognito.guard.ts index 65ca55716..7c870e96e 100644 --- a/apps/backend/src/aws/cognito/cognito.guard.ts +++ b/apps/backend/src/aws/cognito/cognito.guard.ts @@ -85,9 +85,7 @@ export class CognitoJWTGuard implements CanActivate { return true; } - // TODO: Uncomment after easy sign-in is implemented in frontend. const request = context.switchToHttp().getRequest(); - /* const token = extractBearerToken(request); if (!token) { throw new UnauthorizedException('No bearer token provided'); @@ -95,7 +93,6 @@ export class CognitoJWTGuard implements CanActivate { const payload: AccessTokenPayload = await this.verifyToken(token, config); (request as Request & { user: AccessTokenPayload }).user = payload; - */ return true; } diff --git a/apps/backend/src/coordinators/coordinators.service.spec.ts b/apps/backend/src/coordinators/coordinators.service.spec.ts index 35f037d2a..ea051a794 100644 --- a/apps/backend/src/coordinators/coordinators.service.spec.ts +++ b/apps/backend/src/coordinators/coordinators.service.spec.ts @@ -303,6 +303,45 @@ describe('CoordinatorsService', () => { }); }); + describe('findByCognitoSubOrFail', () => { + it('returns the coordinator with the matching Cognito sub and their volunteers', async () => { + const volunteer = { + volunteerId: 4, + firstName: 'Vera', + } as FosterVolunteer; + const coordinatorWithVolunteers = { + ...coordinator, + assignedVolunteers: [volunteer], + } as FosterCoordinator; + repo.findOne.mockResolvedValue(coordinatorWithVolunteers); + + const result = await service.findByCognitoSubOrFail('cognito-sub-123'); + + expect(repo.findOne).toHaveBeenCalledWith({ + where: { cognitoSub: 'cognito-sub-123' }, + relations: ['assignedVolunteers'], + }); + expect(result).toBe(coordinatorWithVolunteers); + expect(result.assignedVolunteers).toEqual([volunteer]); + }); + + it('throws NotFoundException when no coordinator has the Cognito sub', async () => { + repo.findOne.mockResolvedValue(null); + + await expect( + service.findByCognitoSubOrFail('unknown-sub'), + ).rejects.toThrow(new NotFoundException('Coordinator not found')); + }); + + it('throws NotFoundException without querying when the sub is empty', async () => { + await expect(service.findByCognitoSubOrFail('')).rejects.toThrow( + new NotFoundException('Coordinator not found'), + ); + + expect(repo.findOne).not.toHaveBeenCalled(); + }); + }); + describe('findActiveByHomebase', () => { it('returns the active coordinators at the homebase ordered by id', async () => { const coordinators = [ diff --git a/apps/backend/src/coordinators/coordinators.service.ts b/apps/backend/src/coordinators/coordinators.service.ts index 965e804b4..c6abc6276 100644 --- a/apps/backend/src/coordinators/coordinators.service.ts +++ b/apps/backend/src/coordinators/coordinators.service.ts @@ -130,6 +130,32 @@ export class CoordinatorsService { return coordinator; } + /** + * Fetches the coordinator who owns a Cognito account, with their assigned + * volunteers. Used to look up the signed-in user from their token. + * + * @param cognitoSub - The `sub` claim from the user's Cognito access token. + * @returns The coordinator with their assigned volunteers. + * @throws {NotFoundException} If no coordinator has this Cognito sub. + */ + async findByCognitoSubOrFail(cognitoSub: string): Promise { + // Older rows default to an empty sub, so never match on ''. + if (!cognitoSub) { + throw new NotFoundException('Coordinator not found'); + } + + const coordinator = await this.repo.findOne({ + where: { cognitoSub }, + relations: ['assignedVolunteers'], + }); + + if (!coordinator) { + throw new NotFoundException('Coordinator not found'); + } + + return coordinator; + } + /** * Fetches the active Coordinators at a homebase. * diff --git a/apps/backend/src/owners/owners.service.spec.ts b/apps/backend/src/owners/owners.service.spec.ts index 2f4ada0bf..b98027e61 100644 --- a/apps/backend/src/owners/owners.service.spec.ts +++ b/apps/backend/src/owners/owners.service.spec.ts @@ -3,6 +3,7 @@ import { ConflictException, InternalServerErrorException, Logger, + NotFoundException, } from '@nestjs/common'; import { getRepositoryToken } from '@nestjs/typeorm'; import { Repository } from 'typeorm'; @@ -150,4 +151,32 @@ describe('OwnersService', () => { ); }); }); + describe('findByCognitoSubOrFail', () => { + it('returns the owner with the matching Cognito sub', async () => { + repo.findOneBy.mockResolvedValue(owner); + + const result = await service.findByCognitoSubOrFail('cognito-sub-123'); + + expect(repo.findOneBy).toHaveBeenCalledWith({ + cognitoSub: 'cognito-sub-123', + }); + expect(result).toBe(owner); + }); + + it('throws NotFoundException when no owner has the Cognito sub', async () => { + repo.findOneBy.mockResolvedValue(null); + + await expect( + service.findByCognitoSubOrFail('unknown-sub'), + ).rejects.toThrow(new NotFoundException('Owner not found')); + }); + + it('throws NotFoundException without querying when the sub is empty', async () => { + await expect(service.findByCognitoSubOrFail('')).rejects.toThrow( + new NotFoundException('Owner not found'), + ); + + expect(repo.findOneBy).not.toHaveBeenCalled(); + }); + }); }); diff --git a/apps/backend/src/owners/owners.service.ts b/apps/backend/src/owners/owners.service.ts index a11ea1e5b..b763f45a4 100644 --- a/apps/backend/src/owners/owners.service.ts +++ b/apps/backend/src/owners/owners.service.ts @@ -3,6 +3,7 @@ import { Injectable, InternalServerErrorException, Logger, + NotFoundException, } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { Repository } from 'typeorm'; @@ -66,4 +67,27 @@ export class OwnersService { throw new InternalServerErrorException('Failed to save the owner'); } } + + /** + * Fetches the owner who owns a Cognito account. Used to look up the + * signed-in user from their token. + * + * @param cognitoSub - The `sub` claim from the user's Cognito access token. + * @returns The owner. + * @throws {NotFoundException} If no owner has this Cognito sub. + */ + async findByCognitoSubOrFail(cognitoSub: string): Promise { + // Older rows default to an empty sub, so never match on ''. + if (!cognitoSub) { + throw new NotFoundException('Owner not found'); + } + + const owner = await this.repo.findOneBy({ cognitoSub }); + + if (!owner) { + throw new NotFoundException('Owner not found'); + } + + return owner; + } } diff --git a/apps/backend/src/volunteers/volunteers.service.spec.ts b/apps/backend/src/volunteers/volunteers.service.spec.ts index 7e04a5437..0e7e6be45 100644 --- a/apps/backend/src/volunteers/volunteers.service.spec.ts +++ b/apps/backend/src/volunteers/volunteers.service.spec.ts @@ -147,6 +147,45 @@ describe('VolunteersService', () => { }); }); + describe('findByCognitoSubOrFail', () => { + it('returns the volunteer with the matching Cognito sub and their coordinators', async () => { + const coordinator = { + coordinatorId: 3, + firstName: 'Cora', + } as FosterCoordinator; + const volunteer = { + ...mockVolunteer, + cognitoSub: 'cognito-sub-123', + assignedCoordinators: [coordinator], + } as FosterVolunteer; + mockRepo.findOne.mockResolvedValue(volunteer); + + const result = await service.findByCognitoSubOrFail('cognito-sub-123'); + + expect(mockRepo.findOne).toHaveBeenCalledWith({ + where: { cognitoSub: 'cognito-sub-123' }, + relations: ['assignedCoordinators'], + }); + expect(result).toBe(volunteer); + expect(result.assignedCoordinators).toEqual([coordinator]); + }); + + it('throws NotFoundException when no volunteer has the Cognito sub', async () => { + mockRepo.findOne.mockResolvedValue(null); + + await expect( + service.findByCognitoSubOrFail('unknown-sub'), + ).rejects.toThrow(new NotFoundException('Volunteer not found')); + }); + + it('throws NotFoundException without querying when the sub is empty', async () => { + await expect(service.findByCognitoSubOrFail('')).rejects.toThrow( + new NotFoundException('Volunteer not found'), + ); + + expect(mockRepo.findOne).not.toHaveBeenCalled(); + }); + }); describe('findActiveOrFail', () => { it('returns the volunteer when they are active', async () => { const volunteer = { diff --git a/apps/backend/src/volunteers/volunteers.service.ts b/apps/backend/src/volunteers/volunteers.service.ts index 3ce133407..e44c726e2 100644 --- a/apps/backend/src/volunteers/volunteers.service.ts +++ b/apps/backend/src/volunteers/volunteers.service.ts @@ -351,6 +351,35 @@ export class VolunteersService { return volunteer; } + /** + * Fetches the Volunteer who owns a Cognito account, with their assigned + * Foster Coordinators. Used to look up the signed-in user from their token. + * + * @param cognitoSub - The `sub` claim from the user's Cognito access token. + * @returns The Volunteer, without coordinator-only fields. + * @throws {NotFoundException} If no Volunteer has this Cognito sub. + */ + + async findByCognitoSubOrFail( + cognitoSub: string, + ): Promise { + // Older rows default to an empty sub, so never match on ''. + if (!cognitoSub) { + throw new NotFoundException('Volunteer not found'); + } + + const volunteer = await this.repo.findOne({ + where: { cognitoSub }, + relations: ['assignedCoordinators'], + }); + + if (!volunteer) { + throw new NotFoundException('Volunteer not found'); + } + + return this.withoutPrivateFields(volunteer); + } + /** * Ensures a Volunteer's account is active. * diff --git a/apps/frontend/src/api/apiClient.ts b/apps/frontend/src/api/apiClient.ts index 30f61ad94..4a466f91c 100644 --- a/apps/frontend/src/api/apiClient.ts +++ b/apps/frontend/src/api/apiClient.ts @@ -2,7 +2,13 @@ import axios, { type AxiosInstance } from 'axios'; import { fetchAuthSession } from 'aws-amplify/auth'; import { isAuthEnabled } from '../auth/auth.config'; -import type { Animal, CreateMatchBody, Match, Volunteer } from '../types'; +import type { + Animal, + AuthenticatedUser, + CreateMatchBody, + Match, + Volunteer, +} from '../types'; const defaultBaseUrl = import.meta.env.VITE_API_BASE_URL ?? 'http://localhost:3000'; @@ -46,6 +52,10 @@ export class ApiClient { }); } + public async getMe(): Promise { + return this.get('/api/auth/me') as Promise; + } + public async getAnimals(): Promise { return this.get('/api/animals') as Promise; } diff --git a/apps/frontend/src/app.tsx b/apps/frontend/src/app.tsx index 50e2a746b..b677c5a04 100644 --- a/apps/frontend/src/app.tsx +++ b/apps/frontend/src/app.tsx @@ -1,34 +1,60 @@ -import { useEffect } from 'react'; import { createBrowserRouter, RouterProvider, type RouteObject, } from 'react-router-dom'; -import apiClient from '@api/apiClient'; import Root from '@containers/root'; import Layout from '@containers/Layout'; import NotFound from '@containers/404'; import AnimalAvailability from '@pages/AnimalAvailability'; +import SignIn from '@pages/SignIn'; +import RequireAuth from './auth/RequireAuth'; import { ROUTES } from './routes'; -// Every page is a child of Layout so the navbar renders once, above all pages. -// Page errors are caught by the inner errorElement so the navbar stays put; -// the outer one only catches errors from the layout itself. export const routes: RouteObject[] = [ + // Public: no sign-in needed, no navbar. + { + path: ROUTES.SIGN_IN, + element: , + // Catches errors on the sign-in page. + errorElement: , + }, + + // Public: no sign-in needed, with the navbar (e.g. future landing pages). { element: , + // Catches errors in the navbar or a public page, replacing the whole screen. + errorElement: , + children: [ + // Add public pages here. + ], + }, + + // Signed in: any role. + { + element: , + // Catches errors in RequireAuth itself, while checking who is signed in. errorElement: , children: [ { + element: , + // Catches errors in the layout itself (e.g. the navbar), replacing the + // whole screen. errorElement: , children: [ - { path: '/', element: }, { - path: ROUTES.ANIMAL_AVAILABILITY, - element: , + // Catches errors in a page, shown below the navbar. + errorElement: , + children: [ + { path: '/', element: }, + { + path: ROUTES.ANIMAL_AVAILABILITY, + element: , + }, + { path: '*', element: }, + ], }, - { path: '*', element: }, ], }, ], @@ -37,12 +63,6 @@ export const routes: RouteObject[] = [ const router = createBrowserRouter(routes); -export const App: React.FC = () => { - useEffect(() => { - apiClient.getHello().then((res) => console.log(res)); - }, []); - - return ; -}; +export const App: React.FC = () => ; export default App; diff --git a/apps/frontend/src/auth/RequireAuth.tsx b/apps/frontend/src/auth/RequireAuth.tsx new file mode 100644 index 000000000..48b044365 --- /dev/null +++ b/apps/frontend/src/auth/RequireAuth.tsx @@ -0,0 +1,36 @@ +import { Center, Spinner } from '@chakra-ui/react'; +import { Navigate, Outlet, useLocation } from 'react-router-dom'; + +import { ROUTES } from '../routes'; +import { useCurrentUser } from './userContext'; + +/** + * Shows the routes nested under it only to a signed-in user. Anyone else is + * sent to the sign-in page, which returns them here after they sign in. + */ +const RequireAuth: React.FC = () => { + const { currentUser, loading } = useCurrentUser(); + const location = useLocation(); + + if (loading) { + return ( +
+ +
+ ); + } + + if (!currentUser) { + return ( + + ); + } + + return ; +}; + +export default RequireAuth; diff --git a/apps/frontend/src/auth/signInErrors.spec.ts b/apps/frontend/src/auth/signInErrors.spec.ts new file mode 100644 index 000000000..dd7e6348e --- /dev/null +++ b/apps/frontend/src/auth/signInErrors.spec.ts @@ -0,0 +1,58 @@ +import { getSignInErrorMessage } from './signInErrors'; + +// Builds an error with the given name, like the ones Amplify's signIn throws. +const errorNamed = (name: string): Error => { + const error = new Error('Message from Cognito'); + error.name = name; + return error; +}; + +describe('getSignInErrorMessage', () => { + it('returns a generic message for a wrong password', () => { + expect(getSignInErrorMessage(errorNamed('NotAuthorizedException'))).toBe( + 'Incorrect email or password', + ); + }); + + it('returns the same message for an unknown email', () => { + expect(getSignInErrorMessage(errorNamed('UserNotFoundException'))).toBe( + 'Incorrect email or password', + ); + }); + + it('asks unconfirmed users to verify their email', () => { + expect(getSignInErrorMessage(errorNamed('UserNotConfirmedException'))).toBe( + 'Please verify your email before signing in', + ); + }); + + it('asks for an email when it is empty', () => { + expect(getSignInErrorMessage(errorNamed('EmptySignInUsername'))).toBe( + 'Please enter your email', + ); + }); + + it('asks for a password when it is empty', () => { + expect(getSignInErrorMessage(errorNamed('EmptySignInPassword'))).toBe( + 'Please enter your password', + ); + }); + + it('tells the user to wait after too many attempts', () => { + expect(getSignInErrorMessage(errorNamed('LimitExceededException'))).toBe( + 'Too many attempts. Please wait a moment and try again', + ); + }); + + it('falls back to a generic message for unknown errors', () => { + expect(getSignInErrorMessage(errorNamed('SomethingElse'))).toBe( + 'Something went wrong. Please try again', + ); + }); + + it('falls back to a generic message for values that are not errors', () => { + expect(getSignInErrorMessage('oops')).toBe( + 'Something went wrong. Please try again', + ); + }); +}); diff --git a/apps/frontend/src/auth/signInErrors.ts b/apps/frontend/src/auth/signInErrors.ts new file mode 100644 index 000000000..9ade7f358 --- /dev/null +++ b/apps/frontend/src/auth/signInErrors.ts @@ -0,0 +1,43 @@ +/** The names of errors from Amplify's signIn that get their own message. */ +enum SignInErrorName { + NOT_AUTHORIZED = 'NotAuthorizedException', + USER_NOT_FOUND = 'UserNotFoundException', + USER_NOT_CONFIRMED = 'UserNotConfirmedException', + EMPTY_USERNAME = 'EmptySignInUsername', + EMPTY_PASSWORD = 'EmptySignInPassword', + LIMIT_EXCEEDED = 'LimitExceededException', + TOO_MANY_REQUESTS = 'TooManyRequestsException', +} + +// A wrong password and an unknown email get the same message, so the sign-in +// form doesn't reveal which emails have accounts. +const SIGN_IN_ERROR_MESSAGES: Record = { + [SignInErrorName.NOT_AUTHORIZED]: 'Incorrect email or password', + [SignInErrorName.USER_NOT_FOUND]: 'Incorrect email or password', + [SignInErrorName.USER_NOT_CONFIRMED]: + 'Please verify your email before signing in', + [SignInErrorName.EMPTY_USERNAME]: 'Please enter your email', + [SignInErrorName.EMPTY_PASSWORD]: 'Please enter your password', + [SignInErrorName.LIMIT_EXCEEDED]: + 'Too many attempts. Please wait a moment and try again', + [SignInErrorName.TOO_MANY_REQUESTS]: + 'Too many attempts. Please wait a moment and try again', +}; + +const DEFAULT_SIGN_IN_ERROR_MESSAGE = 'Something went wrong. Please try again'; + +const isSignInErrorName = (name: string): name is SignInErrorName => + (Object.values(SignInErrorName) as string[]).includes(name); + +/** + * Turns an error thrown by Amplify's signIn into a message for the user. + * + * @param error - The error thrown by signIn. + * @returns The message to show on the sign-in form. + */ +export const getSignInErrorMessage = (error: unknown): string => { + const name = error instanceof Error ? error.name : ''; + return isSignInErrorName(name) + ? SIGN_IN_ERROR_MESSAGES[name] + : DEFAULT_SIGN_IN_ERROR_MESSAGE; +}; diff --git a/apps/frontend/src/auth/userContext.tsx b/apps/frontend/src/auth/userContext.tsx new file mode 100644 index 000000000..6b4f0babf --- /dev/null +++ b/apps/frontend/src/auth/userContext.tsx @@ -0,0 +1,116 @@ +import { createContext, useContext, useEffect, useState } from 'react'; +import { useAuthenticator } from '@aws-amplify/ui-react'; + +import apiClient from '@api/apiClient'; +import type { AuthenticatedUser } from '../types'; +import { isAuthEnabled } from './auth.config'; + +type UserContextValue = { + /** The signed-in user and their role, or null if no one is signed in. */ + currentUser: AuthenticatedUser | null; + /** True while we're still finding out who is signed in. */ + loading: boolean; +}; + +/** Where the GET /api/auth/me request for the signed-in user is at. */ +type FetchState = + | { status: 'idle' } + | { status: 'loading' } + | { status: 'done'; user: AuthenticatedUser | null }; + +const UserContext = createContext({ + currentUser: null, + loading: false, +}); + +/** + * Loads the signed-in user from GET /api/auth/me whenever someone signs in, + * and shares them through UserContext. + * + * Must be rendered inside Amplify's Authenticator.Provider. + */ +const SignedInUserProvider: React.FC<{ children: React.ReactNode }> = ({ + children, +}) => { + const { authStatus } = useAuthenticator((context) => [context.authStatus]); + // Starts as loading, since the request begins as soon as someone signs in. + const [fetchState, setFetchState] = useState({ + status: 'loading', + }); + + // This component subscribes to authStatus through useAuthenticator, so + // React runs this effect again whenever authStatus changes, i.e. whenever + // Amplify signs a user in or out. + useEffect(() => { + if (authStatus !== 'authenticated') return; + + // Ignores a response that arrives after the user has signed out. + let cancelled = false; + + const loadCurrentUser = async () => { + try { + const user = await apiClient.getMe(); + if (!cancelled) setFetchState({ status: 'done', user }); + } catch (error) { + if (!cancelled) { + // TODO: replace with an error toast once we have one. + console.error('Failed to load the signed-in user', error); + setFetchState({ status: 'done', user: null }); + } + } + }; + + loadCurrentUser(); + + return () => { + cancelled = true; + // Forget this user, so the next sign-in starts loading from scratch. + setFetchState({ status: 'loading' }); + }; + }, [authStatus]); + + // authStatus is Amplify's client-side sign-in state, based on the JWT + // stored in the browser. A /me result only counts while it says someone is + // signed in; otherwise there's nothing to fetch, so the state is idle. + const state: FetchState = + authStatus === 'authenticated' ? fetchState : { status: 'idle' }; + + const currentUser = state.status === 'done' ? state.user : null; + const loading = authStatus === 'configuring' || state.status === 'loading'; + + // This is where the value is written to UserContext. React stores it with + // this Provider and gives it to every component below that reads + // UserContext (through useCurrentUser), re-rendering them when it changes. + return ( + + {children} + + ); +}; + +/** + * Shares the signed-in user with every component inside it. Without the + * VITE_ Cognito variables no one can sign in, so it shares no user. + * + * Must be rendered inside Amplify's Authenticator.Provider. + */ +export const UserProvider: React.FC<{ children: React.ReactNode }> = ({ + children, +}) => { + if (!isAuthEnabled()) { + return ( + + {children} + + ); + } + + return {children}; +}; + +/** + * The signed-in user and whether they're still loading. This is where + * UserContext is read: React finds the nearest UserContext.Provider above the + * calling component and returns the value it was given. + */ +export const useCurrentUser = (): UserContextValue => useContext(UserContext); diff --git a/apps/frontend/src/components/Navbar.tsx b/apps/frontend/src/components/Navbar.tsx index c944ec82a..408662749 100644 --- a/apps/frontend/src/components/Navbar.tsx +++ b/apps/frontend/src/components/Navbar.tsx @@ -1,33 +1,28 @@ -import { useEffect, useState } from 'react'; import { Button, Flex, Image, Text } from '@chakra-ui/react'; -import apiClient from '@api/apiClient'; -import type { Volunteer } from '../types'; -import { getAvatarColor, getInitials, useVolunteerId } from '@utils/volunteer'; +import { useNavigate } from 'react-router-dom'; +import { signOut } from 'aws-amplify/auth'; +import { ROUTES } from '../routes'; +import { useCurrentUser } from '../auth/userContext'; +import { getUserId } from '@utils/user'; +import { getAvatarColor, getInitials } from '@utils/volunteer'; import logo from '../assets/mspca-logo.png'; -/** Site-wide header: MSPCA logo and the current volunteer's profile button. */ +/** Site-wide header: MSPCA logo and the signed-in user's profile button. */ const Navbar: React.FC = () => { - const volunteerId = useVolunteerId(); - const [loaded, setLoaded] = useState(null); - const volunteer = loaded?.volunteerId === volunteerId ? loaded : null; + const { currentUser } = useCurrentUser(); - useEffect(() => { - if (volunteerId === null) return; + const navigate = useNavigate(); - let cancelled = false; - apiClient - .getVolunteer(volunteerId) - .then((result) => { - if (!cancelled) setLoaded(result); - }) - .catch((err: unknown) => { - console.warn(`Could not load volunteer ${volunteerId}`, err); - }); - return () => { - cancelled = true; - }; - }, [volunteerId]); + const handleSignOut = async () => { + try { + await signOut(); + navigate(ROUTES.SIGN_IN, { replace: true }); + } catch (err) { + // TODO: replace with an error toast once we have one. + console.error('Failed to sign out', err); + } + }; return ( { h={{ base: '64px', md: '88px' }} objectFit="contain" /> - {/* TODO: link to the volunteer profile page once it exists. */} - + + {currentUser + ? getInitials( + currentUser.user.firstName, + currentUser.user.lastName, + ) + : ''} + + + My Profile + + + ); }; diff --git a/apps/frontend/src/components/modals/AnimalModal.tsx b/apps/frontend/src/components/modals/AnimalModal.tsx index 2643d94d5..5cd3c63b4 100644 --- a/apps/frontend/src/components/modals/AnimalModal.tsx +++ b/apps/frontend/src/components/modals/AnimalModal.tsx @@ -12,11 +12,11 @@ import { import { ExternalLink, House } from 'lucide-react'; import apiClient from '@api/apiClient'; -import type { Animal } from '../../types'; +import { UserRole, type Animal } from '../../types'; import { HOMEBASE_ADDRESSES, formatAge } from '@utils/animals'; -import { useVolunteerId } from '@utils/volunteer'; import { PLACEHOLDER_IMAGE } from '../AnimalCard'; import RestrictionTag from '../RestrictionTag'; +import { useCurrentUser } from '../../auth/userContext'; interface AnimalModalProps { animal: Animal | null; @@ -38,8 +38,11 @@ const AnimalModal: React.FC = ({ animal, onClose }) => { const [comments, setComments] = useState(''); const [submitting, setSubmitting] = useState(false); const [error, setError] = useState(null); - // TODO: remove after login implemented. - const volunteerId = useVolunteerId(); + const { currentUser } = useCurrentUser(); + const volunteerId = + currentUser?.role === UserRole.FOSTER_VOLUNTEER + ? currentUser.user.volunteerId + : null; const handleClose = () => { setComments(''); @@ -221,6 +224,11 @@ const AnimalModal: React.FC = ({ animal, onClose }) => { _placeholder={{ color: 'fg.muted' }} /> {error && {error}} + {volunteerId === null && ( + + Only foster volunteers can apply. + + )} + + ) : ( +
+ + + + } + > + setEmail(event.target.value)} + /> + + + + + {/* The Lo-Fi uses the envelope icon for the password too. */} + + } + > + setPassword(event.target.value)} + /> + + {error} + + + + {/* TODO: implement remember me and forgot password. */} + + + Remember me + + + Forgot password + + + + + + {/* TODO: link to the create account flow. */} + + +
+ )} + + + + {/* Placeholder from the Lo-Fi; desktop only. */} + +
+ ); +}; + +export default SignIn; diff --git a/apps/frontend/src/routes.ts b/apps/frontend/src/routes.ts index d2a866b2b..19dcbf71e 100644 --- a/apps/frontend/src/routes.ts +++ b/apps/frontend/src/routes.ts @@ -1,3 +1,4 @@ export enum ROUTES { ANIMAL_AVAILABILITY = '/animal-availability', + SIGN_IN = '/sign-in', } diff --git a/apps/frontend/src/types.ts b/apps/frontend/src/types.ts index f6369194f..e72bde22b 100644 --- a/apps/frontend/src/types.ts +++ b/apps/frontend/src/types.ts @@ -84,6 +84,8 @@ export interface Coordinator { homebase: Homebase; active: boolean; cognitoSub: string; + // Only included when a coordinator is loaded with their volunteers (e.g. /api/auth/me). + assignedVolunteers?: Volunteer[]; } export interface Volunteer { @@ -109,3 +111,29 @@ export interface Volunteer { animalPreferences: string[]; assignedCoordinators: Coordinator[]; } + +// Must match the backend's CognitoRole values exactly, since /api/auth/me +// returns these strings as the user's role. +export enum UserRole { + FOSTER_VOLUNTEER = 'FosterVolunteer', + FOSTER_COORDINATOR = 'FosterCoordinator', + OWNER = 'Owner', +} + +export interface Owner { + ownerId: number; + firstName: string; + lastName: string; + phone: string; + secondaryPhone: string | null; + email: string; + active: boolean; + cognitoSub: string; +} + +// The signed-in user returned by GET /api/auth/me: their role, plus their +// record from the table that matches that role. +export type AuthenticatedUser = + | { role: UserRole.FOSTER_VOLUNTEER; user: Volunteer } + | { role: UserRole.FOSTER_COORDINATOR; user: Coordinator } + | { role: UserRole.OWNER; user: Owner }; diff --git a/apps/frontend/src/utils/useVolunteerId.spec.tsx b/apps/frontend/src/utils/useVolunteerId.spec.tsx deleted file mode 100644 index 80b47ab08..000000000 --- a/apps/frontend/src/utils/useVolunteerId.spec.tsx +++ /dev/null @@ -1,27 +0,0 @@ -import { render } from '@testing-library/react'; -import { MemoryRouter } from 'react-router-dom'; - -import { useVolunteerId } from './volunteer'; - -const Probe: React.FC = () => {String(useVolunteerId())}; - -const renderAt = (route: string) => - render( - - - , - ); - -describe('useVolunteerId', () => { - it('reads volunteerId from the query string', () => { - expect(renderAt('/x?volunteerId=7').getByText('7')).toBeTruthy(); - }); - - it('returns null when volunteerId is missing', () => { - expect(renderAt('/x').getByText('null')).toBeTruthy(); - }); - - it('returns null when volunteerId is not a valid ID', () => { - expect(renderAt('/x?volunteerId=abc').getByText('null')).toBeTruthy(); - }); -}); diff --git a/apps/frontend/src/utils/user.spec.ts b/apps/frontend/src/utils/user.spec.ts new file mode 100644 index 000000000..2f6a7feae --- /dev/null +++ b/apps/frontend/src/utils/user.spec.ts @@ -0,0 +1,31 @@ +import { UserRole, type AuthenticatedUser } from '../types'; +import { getUserId } from './user'; + +describe('getUserId', () => { + it('returns the volunteer ID for a volunteer', () => { + const currentUser = { + role: UserRole.FOSTER_VOLUNTEER, + user: { volunteerId: 4 }, + } as AuthenticatedUser; + + expect(getUserId(currentUser)).toBe(4); + }); + + it('returns the coordinator ID for a coordinator', () => { + const currentUser = { + role: UserRole.FOSTER_COORDINATOR, + user: { coordinatorId: 7 }, + } as AuthenticatedUser; + + expect(getUserId(currentUser)).toBe(7); + }); + + it('returns the owner ID for an owner', () => { + const currentUser = { + role: UserRole.OWNER, + user: { ownerId: 9 }, + } as AuthenticatedUser; + + expect(getUserId(currentUser)).toBe(9); + }); +}); diff --git a/apps/frontend/src/utils/user.ts b/apps/frontend/src/utils/user.ts new file mode 100644 index 000000000..b63427edf --- /dev/null +++ b/apps/frontend/src/utils/user.ts @@ -0,0 +1,18 @@ +import { UserRole, type AuthenticatedUser } from '../types'; + +/** + * The signed-in user's ID from their role's table: their volunteerId, + * coordinatorId, or ownerId. + * + * @param currentUser - The signed-in user, from useCurrentUser. + * @returns The user's ID. + */ +export const getUserId = (currentUser: AuthenticatedUser): number => { + if (currentUser.role === UserRole.FOSTER_VOLUNTEER) { + return currentUser.user.volunteerId; + } + if (currentUser.role === UserRole.FOSTER_COORDINATOR) { + return currentUser.user.coordinatorId; + } + return currentUser.user.ownerId; +}; diff --git a/apps/frontend/src/utils/volunteer.spec.ts b/apps/frontend/src/utils/volunteer.spec.ts index 2b9f7c2a2..5f966bd1a 100644 --- a/apps/frontend/src/utils/volunteer.spec.ts +++ b/apps/frontend/src/utils/volunteer.spec.ts @@ -1,10 +1,5 @@ import { colors } from '../theme'; -import { - AVATAR_COLORS, - getAvatarColor, - getInitials, - parseVolunteerId, -} from './volunteer'; +import { AVATAR_COLORS, getAvatarColor, getInitials } from './volunteer'; describe('getInitials', () => { it('uses the first letter of each name', () => { @@ -44,22 +39,3 @@ describe('getAvatarColor', () => { expect(getAvatarColor(42)).toBe(getAvatarColor(42)); }); }); - -describe('parseVolunteerId', () => { - it('parses a positive integer', () => { - expect(parseVolunteerId('12')).toBe(12); - }); - - it.each([ - null, - '', - 'abc', - '0', - '-3', - '1.5', - '12abc', - '99999999999999999999999', - ])('returns null for %j', (raw) => { - expect(parseVolunteerId(raw)).toBeNull(); - }); -}); diff --git a/apps/frontend/src/utils/volunteer.ts b/apps/frontend/src/utils/volunteer.ts index 186c63f68..f29329473 100644 --- a/apps/frontend/src/utils/volunteer.ts +++ b/apps/frontend/src/utils/volunteer.ts @@ -1,5 +1,3 @@ -import { useSearchParams } from 'react-router-dom'; - import { colors } from '../theme'; // Avatars reuse the Trello label colors, so changing those in theme.ts @@ -15,18 +13,3 @@ export const getInitials = (firstName: string, lastName: string): string => export const getAvatarColor = (volunteerId: number): string => AVATAR_COLORS[volunteerId % AVATAR_COLORS.length]; - -export const parseVolunteerId = (raw: string | null): number | null => { - if (raw === null || !/^\d+$/.test(raw)) return null; - const id = Number(raw); - return id > 0 && Number.isSafeInteger(id) ? id : null; -}; - -/** - * The current volunteer's ID, read from the `?volunteerId=` query param. - * TEMPORARY: replace with the signed-in volunteer once sign-in is implemented. - */ -export const useVolunteerId = (): number | null => { - const [searchParams] = useSearchParams(); - return parseVolunteerId(searchParams.get('volunteerId')); -};