Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
38 commits
Select commit Hold shift + click to select a range
d558e32
added animal entity
shreeyaadhikari Oct 25, 2026
574967c
add migration to create animal table
shreeyaadhikari Oct 25, 2026
d6f7cbf
added animal service logic w chameloen id existence checks
shreeyaadhikari Oct 25, 2026
13af06a
validate animal exists in post/recommendations
shreeyaadhikari Oct 25, 2026
c01e1ec
validate animal exists in post/matches
shreeyaadhikari Oct 25, 2026
4d31981
validate added animals exist in patch/volunteers/id/animal-preference
shreeyaadhikari Oct 25, 2026
2f8c81a
Add animal availability page with filters, animal card, and modal
pujitakalinadhabhotla Nov 3, 2026
3d04de3
Merge main and address review feedback on animal availability
pujitakalinadhabhotla Nov 7, 2026
b0280f6
Update animal availability UI to match latest designs
pujitakalinadhabhotla Nov 8, 2026
87e96be
addressed comments
pujitakalinadhabhotla Nov 10, 2026
e0b7c84
MSPCA-51 Add navbar to the app layout (#31)
Juwang110 Nov 13, 2026
cc07561
address comments
pujitakalinadhabhotla Nov 15, 2026
a992d97
merge conflicts
pujitakalinadhabhotla Nov 15, 2026
3313a35
address comments
pujitakalinadhabhotla Nov 17, 2026
cee7cef
Enable cognito JWT guard and its tests
psmolyan Nov 17, 2026
2b2ea32
Add findByCognitoSubOrFail to volunteer, coordinator, and owner services
psmolyan Nov 17, 2026
791a458
Add tests for OwnerService.findByCognitoSubOrFail
psmolyan Nov 17, 2026
2d9fc9b
add tests for findByCognitoSubOrFail in coords and volunteer services
psmolyan Nov 17, 2026
a69ff34
add GET /auth/me endpoint returning the signed-in user and role
psmolyan Nov 17, 2026
506d37a
Merge remote-tracking branch 'origin/pk/mspca-46-animal-availability-…
psmolyan Nov 17, 2026
a2424d4
Add getMe to apiClient and AuthenticatedUser types
psmolyan Nov 17, 2026
406b67a
add UserProvider that loads the signed-in user from /auth/me
psmolyan Nov 18, 2026
f6256bb
Add sign-in page and protect app routes with RequireAuth
psmolyan Nov 18, 2026
2e3a0d2
Show the signed-in user's initials in the Navbar
psmolyan Nov 18, 2026
469cd89
Use the signed-in volunteer's ID when requesting an animal
psmolyan Nov 18, 2026
d4b83ab
Remove useVolunteerId and parseVolunteerId now that the signed-in use…
psmolyan Nov 18, 2026
d9f01f9
Match the sign-in page to the Lo-Fi, with the error state
psmolyan Nov 18, 2026
1dac225
Apply team conventions: theme tokens, inputGroup, try/catch, and an e…
psmolyan Nov 18, 2026
947c9f1
ask unconfirmed users to verify their email when signing in
psmolyan Nov 18, 2026
c2a64e4
address comments
pujitakalinadhabhotla Nov 21, 2026
83cb6ba
address comments
pujitakalinadhabhotla Nov 21, 2026
0e737c0
Merge remote-tracking branch 'origin/pk/mspca-46-animal-availability-…
psmolyan Nov 22, 2026
e8515ac
review comments: load coordinator volunteers, least-priviledge role w…
psmolyan Nov 22, 2026
8ac2c42
review comments: route sections, remove nextStep, sign-in page tweaks
psmolyan Nov 22, 2026
7083b53
review comments: route sections, fetchstate and auth check in userpro…
psmolyan Nov 22, 2026
21b7409
add a temporary sign out button and assignedVolunteers to the coordin…
psmolyan Nov 22, 2026
1d34406
review comments: pick role from appRoles[0], errorElement, disabled A…
psmolyan Nov 22, 2026
f17c897
Merge remote-tracking branch 'origin/main' into ps/mspca-55-sign-in
psmolyan Nov 22, 2026
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 { AuthModule } from './auth/auth.module';

@Module({
imports: [
Expand All @@ -28,6 +29,7 @@ import { AnimalsModule } from './animals/animals.module';
VolunteersModule,
OwnersModule,
AnimalsModule,
AuthModule,
],
})
export class AppModule {}
184 changes: 184 additions & 0 deletions apps/backend/src/auth/auth.controller.spec.ts
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'),
);
});
});
});
110 changes: 110 additions & 0 deletions apps/backend/src/auth/auth.controller.ts
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'] ?? [];
Comment thread
psmolyan marked this conversation as resolved.
Resolved

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');
}
}
}
12 changes: 12 additions & 0 deletions apps/backend/src/auth/auth.module.ts
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 {}
13 changes: 13 additions & 0 deletions apps/backend/src/auth/auth.types.ts
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 };
2 changes: 1 addition & 1 deletion apps/backend/src/aws/cognito/cognito.guard.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ function createContext(authorization?: string): {
return { context, request };
}

describe.skip('CognitoJWTGuard', () => {
describe('CognitoJWTGuard', () => {
let guard: CognitoJWTGuard;
let reflector: jest.Mocked<Pick<Reflector, 'getAllAndOverride'>>;

Expand Down
3 changes: 0 additions & 3 deletions apps/backend/src/aws/cognito/cognito.guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,17 +85,14 @@ export class CognitoJWTGuard implements CanActivate {
return true;
}

// TODO: Uncomment after easy sign-in is implemented in frontend.
const request = context.switchToHttp().getRequest<Request>();
/*
const token = extractBearerToken(request);
if (!token) {
throw new UnauthorizedException('No bearer token provided');
}

const payload: AccessTokenPayload = await this.verifyToken(token, config);
(request as Request & { user: AccessTokenPayload }).user = payload;
*/
return true;
}

Expand Down
Loading
Loading