Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions apps/backend/src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 { StaffModule } from './staff/staff.module';
import { AuthModule } from './auth/auth.module';

@Module({
Expand All @@ -29,6 +30,7 @@ import { AuthModule } from './auth/auth.module';
VolunteersModule,
OwnersModule,
AnimalsModule,
StaffModule,
AuthModule,
],
})
Expand Down
28 changes: 27 additions & 1 deletion apps/backend/src/auth/auth.controller.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,22 +10,26 @@ 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 { StaffService } from '../staff/staff.service';
import { CoordinatorsService } from '../coordinators/coordinators.service';
import { OwnersService } from '../owners/owners.service';
import { FosterVolunteer } from '../volunteers/volunteers.entity';
import { FosterStaff } from '../staff/staff.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 staffService: { 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 staffMember = { staffId: 4, firstName: 'Sam' } as FosterStaff;
const coordinator = {
coordinatorId: 2,
firstName: 'Cora',
Expand All @@ -47,6 +51,7 @@ describe('AuthController', () => {
beforeEach(async () => {
cognitoService = { getUser: jest.fn() };
volunteersService = { findByCognitoSubOrFail: jest.fn() };
staffService = { findByCognitoSubOrFail: jest.fn() };
coordinatorsService = { findByCognitoSubOrFail: jest.fn() };
ownersService = { findByCognitoSubOrFail: jest.fn() };

Expand All @@ -55,6 +60,7 @@ describe('AuthController', () => {
providers: [
{ provide: CognitoService, useValue: cognitoService },
{ provide: VolunteersService, useValue: volunteersService },
{ provide: StaffService, useValue: staffService },
{ provide: CoordinatorsService, useValue: coordinatorsService },
{ provide: OwnersService, useValue: ownersService },
],
Expand Down Expand Up @@ -88,6 +94,23 @@ describe('AuthController', () => {
expect(warnSpy).not.toHaveBeenCalled();
});

it('returns the staff member for a Staff user', async () => {
cognitoService.getUser.mockReturnValue(
payloadWithGroups([CognitoRole.Staff]),
);
staffService.findByCognitoSubOrFail.mockResolvedValue(staffMember);

const result = await controller.getMe(request);

expect(staffService.findByCognitoSubOrFail).toHaveBeenCalledWith(
'cognito-sub-123',
);
expect(result).toEqual({
role: CognitoRole.Staff,
user: staffMember,
});
});

it('returns the coordinator for a FosterCoordinator', async () => {
cognitoService.getUser.mockReturnValue(
payloadWithGroups([CognitoRole.FosterCoordinator]),
Expand Down Expand Up @@ -124,6 +147,7 @@ describe('AuthController', () => {
payloadWithGroups([
CognitoRole.Owner,
CognitoRole.FosterCoordinator,
CognitoRole.Staff,
CognitoRole.FosterVolunteer,
]),
);
Expand All @@ -132,10 +156,11 @@ describe('AuthController', () => {
const result = await controller.getMe(request);

expect(result.role).toBe(CognitoRole.FosterVolunteer);
expect(staffService.findByCognitoSubOrFail).not.toHaveBeenCalled();
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',
'User cognito-sub-123 is in multiple groups (FosterVolunteer, Staff, FosterCoordinator, Owner); using the least privileged role',
);
});

Expand All @@ -146,6 +171,7 @@ describe('AuthController', () => {
new UnauthorizedException('No user attached to the request'),
);
expect(volunteersService.findByCognitoSubOrFail).not.toHaveBeenCalled();
expect(staffService.findByCognitoSubOrFail).not.toHaveBeenCalled();
expect(coordinatorsService.findByCognitoSubOrFail).not.toHaveBeenCalled();
expect(ownersService.findByCognitoSubOrFail).not.toHaveBeenCalled();
});
Expand Down
7 changes: 7 additions & 0 deletions apps/backend/src/auth/auth.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ 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 { StaffService } from '../staff/staff.service';
import { CoordinatorsService } from '../coordinators/coordinators.service';
import { OwnersService } from '../owners/owners.service';
import { AuthenticatedUser } from './auth.types';
Expand All @@ -24,6 +25,7 @@ export class AuthController {
constructor(
private readonly cognitoService: CognitoService,
private readonly volunteersService: VolunteersService,
private readonly staffService: StaffService,
private readonly coordinatorsService: CoordinatorsService,
private readonly ownersService: OwnersService,
) {}
Expand Down Expand Up @@ -91,6 +93,11 @@ export class AuthController {
payload.sub,
),
};
case CognitoRole.Staff:
return {
role: CognitoRole.Staff,
user: await this.staffService.findByCognitoSubOrFail(payload.sub),
};
case CognitoRole.FosterCoordinator:
return {
role: CognitoRole.FosterCoordinator,
Expand Down
9 changes: 8 additions & 1 deletion apps/backend/src/auth/auth.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,18 @@ import { Module } from '@nestjs/common';
import { AuthController } from './auth.controller';
import { CognitoModule } from '../aws/cognito/cognito.module';
import { VolunteersModule } from '../volunteers/volunteers.module';
import { StaffModule } from '../staff/staff.module';
import { CoordinatorsModule } from '../coordinators/coordinators.module';
import { OwnersModule } from '../owners/owners.module';

@Module({
imports: [CognitoModule, VolunteersModule, CoordinatorsModule, OwnersModule],
imports: [
CognitoModule,
VolunteersModule,
StaffModule,
CoordinatorsModule,
OwnersModule,
],
controllers: [AuthController],
})
export class AuthModule {}
2 changes: 2 additions & 0 deletions apps/backend/src/auth/auth.types.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { CognitoRole } from '../aws/cognito/cognito.types';
import { FosterCoordinator } from '../coordinators/coordinators.entity';
import { Owner } from '../owners/owners.entity';
import { FosterStaff } from '../staff/staff.entity';
import { VolunteerWithoutPrivateFields } from '../volunteers/dtos/volunteer-without-private-fields.dto';

/**
Expand All @@ -9,5 +10,6 @@ import { VolunteerWithoutPrivateFields } from '../volunteers/dtos/volunteer-with
*/
export type AuthenticatedUser =
| { role: CognitoRole.FosterVolunteer; user: VolunteerWithoutPrivateFields }
| { role: CognitoRole.Staff; user: FosterStaff }
| { role: CognitoRole.FosterCoordinator; user: FosterCoordinator }
| { role: CognitoRole.Owner; user: Owner };
1 change: 1 addition & 0 deletions apps/backend/src/aws/cognito/cognito.types.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Cognito user pool group names that map to application roles.
export enum CognitoRole {
FosterVolunteer = 'FosterVolunteer',
Staff = 'Staff',
FosterCoordinator = 'FosterCoordinator',
Owner = 'Owner',
}
Expand Down
2 changes: 2 additions & 0 deletions apps/backend/src/config/migrations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { AddAnimalUpdatesAndFosterTypeArray1793163582751 } from '../migrations/1
import { AddFarmAnimalsToFosterType1793476100199 } from '../migrations/1793476100199-AddFarmAnimalsToFosterType';
import { RenameAdminUsersToOwners1793485161630 } from '../migrations/1793485161630-RenameAdminUsersToOwners';
import { AddFosterTypePreferences1793600000000 } from '../migrations/1793600000000-AddFosterTypePreferences';
import { AddStaffAndUpdateMatches1795372304908 } from '../migrations/1795372304908-AddStaffAndUpdateMatches';
import { AddPetsAndHouseholdDetails1794408338094 } from '../migrations/1794408338094-AddPetsAndHouseholdDetails';
import { AddMatchAdditionalComments1794784721012 } from '../migrations/1794784721012-AddMatchAdditionalComments';

Expand All @@ -32,6 +33,7 @@ const schemaMigrations = [
AddFosterTypePreferences1793600000000,
AddPetsAndHouseholdDetails1794408338094,
AddMatchAdditionalComments1794784721012,
AddStaffAndUpdateMatches1795372304908,
];

export default schemaMigrations;
10 changes: 9 additions & 1 deletion apps/backend/src/matches/dtos/create-match.dto.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,18 @@
import { IsInt, IsPositive, MaxLength, ValidateIf } from 'class-validator';
import { IsNonEmptyString } from '../../utils/decorators/is-non-empty-string.decorator';
import { ExactlyOne } from './validators/exactly-one.validator';

@ExactlyOne<CreateMatchDto>(['volunteerId', 'staffId'])
export class CreateMatchDto {
@ValidateIf((o) => o.volunteerId !== undefined)
@IsInt()
@IsPositive()
volunteerId!: number;
volunteerId?: number;

@ValidateIf((o) => o.staffId !== undefined)
@IsInt()
@IsPositive()
staffId?: number;

@IsNonEmptyString()
@MaxLength(255)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { validate } from 'class-validator';
import { ExactlyOne } from './exactly-one.validator';

@ExactlyOne<TestDto>(['a', 'b'])
class TestDto {
a?: number;
b?: number;
}

describe('ExactlyOne', () => {
it('passes when only the first field is provided', async () => {
const dto = Object.assign(new TestDto(), { a: 1 });

expect(await validate(dto)).toHaveLength(0);
});

it('passes when only the second field is provided', async () => {
const dto = Object.assign(new TestDto(), { b: 2 });

expect(await validate(dto)).toHaveLength(0);
});

it('fails when both fields are provided', async () => {
const dto = Object.assign(new TestDto(), { a: 1, b: 2 });
const errors = await validate(dto);

expect(errors).toHaveLength(1);
expect(errors[0].constraints).toEqual({
exactlyOne: 'Exactly one of a, b must be provided',
});
});

it('fails when neither field is provided', async () => {
const errors = await validate(new TestDto());

expect(errors).toHaveLength(1);
expect(errors[0].constraints).toEqual({
exactlyOne: 'Exactly one of a, b must be provided',
});
});

it('fails when both fields are explicitly undefined', async () => {
const dto = Object.assign(new TestDto(), { a: undefined, b: undefined });
const errors = await validate(dto);

expect(errors).toHaveLength(1);
});
});
29 changes: 29 additions & 0 deletions apps/backend/src/matches/dtos/validators/exactly-one.validator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { registerDecorator, ValidationArguments } from 'class-validator';

/**
* Class decorator that rejects the DTO unless exactly one of the given fields
* is provided (i.e. not undefined).
*
* It only checks presence. The decorators on each field still validate the
* values themselves.
*/
export function ExactlyOne<T extends object>(
fields: (keyof T & string)[],
): ClassDecorator {
return (target) => {
registerDecorator({
name: 'exactlyOne',
target,
propertyName: 'exactlyOne',
validator: {
validate(_: unknown, args: ValidationArguments): boolean {
const dto = args.object as Record<string, unknown>;
return fields.filter((f) => dto[f] !== undefined).length === 1;
},
defaultMessage(): string {
return `Exactly one of ${fields.join(', ')} must be provided`;
},
},
});
};
}
18 changes: 14 additions & 4 deletions apps/backend/src/matches/matches.entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
JoinColumn,
} from 'typeorm';
import { FosterVolunteer } from '../volunteers/volunteers.entity';
import { FosterStaff } from '../staff/staff.entity';
import { Animal } from '../animals/animals.entity';
import { MatchStatus } from './matches.types';

Expand All @@ -15,13 +16,22 @@ export class Match {
matchId!: number;

@ManyToOne(() => FosterVolunteer, (volunteer) => volunteer.matches, {
nullable: false,
nullable: true,
})
@JoinColumn({ name: 'volunteer_id' })
volunteer!: FosterVolunteer;
volunteer!: FosterVolunteer | null;

@Column({ name: 'volunteer_id' })
volunteerId!: number;
@Column({ name: 'volunteer_id', nullable: true })
volunteerId!: number | null;

@ManyToOne(() => FosterStaff, (staff) => staff.matches, {
nullable: true,
})
@JoinColumn({ name: 'staff_id' })
staff!: FosterStaff | null;

@Column({ name: 'staff_id', nullable: true })
staffId!: number | null;

@ManyToOne(() => Animal, { nullable: false })
@JoinColumn({
Expand Down
2 changes: 2 additions & 0 deletions apps/backend/src/matches/matches.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,15 @@ import { MatchesService } from './matches.service';
import { VolunteersModule } from '../volunteers/volunteers.module';
import { AWSSESModule } from '../aws/ses/email.module';
import { AnimalsModule } from '../animals/animals.module';
import { StaffModule } from '../staff/staff.module';

@Module({
imports: [
TypeOrmModule.forFeature([Match]),
forwardRef(() => VolunteersModule),
AWSSESModule,
AnimalsModule,
StaffModule,
],
controllers: [MatchesController],
providers: [MatchesService],
Expand Down
Loading
Loading