Skip to content
Open
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
67 changes: 67 additions & 0 deletions apps/backend/src/auth/auth.service.spec.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,15 @@
import { Test, TestingModule } from '@nestjs/testing';
import { InternalServerErrorException } from '@nestjs/common';
import {
AdminDisableUserCommand,
AdminEnableUserCommand,
} from '@aws-sdk/client-cognito-identity-provider';
import { AuthService } from './auth.service';
import CognitoAuthConfig from './aws-exports';

describe('AuthService', () => {
let service: AuthService;
let sendSpy: jest.SpyInstance;

beforeEach(async () => {
process.env.AWS_ACCESS_KEY_ID = 'test';
Expand All @@ -15,9 +22,69 @@ describe('AuthService', () => {
}).compile();

service = module.get<AuthService>(AuthService);

sendSpy = jest
.spyOn(
(service as unknown as { providerClient: { send: jest.Mock } })
.providerClient,
'send',
)
.mockResolvedValue({} as never);
});

afterEach(() => {
jest.restoreAllMocks();
});

it('should be defined', () => {
expect(service).toBeDefined();
});

describe('adminDisableUser', () => {
it('sends AdminDisableUserCommand with the email as Username', async () => {
await service.adminDisableUser('volunteer@example.com');

expect(sendSpy).toHaveBeenCalledTimes(1);
const command = sendSpy.mock.calls[0][0];
expect(command).toBeInstanceOf(AdminDisableUserCommand);
expect(command.input).toEqual({
UserPoolId: CognitoAuthConfig.userPoolId,
Username: 'volunteer@example.com',
});
});

it('throws InternalServerErrorException when Cognito fails', async () => {
sendSpy.mockRejectedValueOnce(new Error('Cognito down'));

await expect(
service.adminDisableUser('volunteer@example.com'),
).rejects.toThrow(
new InternalServerErrorException('Failed to disable user'),
);
});
});

describe('adminEnableUser', () => {
it('sends AdminEnableUserCommand with the email as Username', async () => {
await service.adminEnableUser('volunteer@example.com');

expect(sendSpy).toHaveBeenCalledTimes(1);
const command = sendSpy.mock.calls[0][0];
expect(command).toBeInstanceOf(AdminEnableUserCommand);
expect(command.input).toEqual({
UserPoolId: CognitoAuthConfig.userPoolId,
Username: 'volunteer@example.com',
});
});

it('throws InternalServerErrorException when Cognito fails', async () => {
sendSpy.mockRejectedValueOnce(new Error('Cognito down'));

await expect(
service.adminEnableUser('volunteer@example.com'),
).rejects.toThrow(
new InternalServerErrorException('Failed to enable user'),
);
});
});
});
28 changes: 28 additions & 0 deletions apps/backend/src/auth/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import {
import {
CognitoIdentityProviderClient,
AdminCreateUserCommand,
AdminDisableUserCommand,
AdminEnableUserCommand,
} from '@aws-sdk/client-cognito-identity-provider';

import CognitoAuthConfig from './aws-exports';
Expand Down Expand Up @@ -70,4 +72,30 @@ export class AuthService {
}
}
}

async adminDisableUser(email: string): Promise<void> {
const disableUserCommand = new AdminDisableUserCommand({
UserPoolId: CognitoAuthConfig.userPoolId,
Username: email,
});

try {
await this.providerClient.send(disableUserCommand);
} catch {
throw new InternalServerErrorException('Failed to disable user');
}
}

async adminEnableUser(email: string): Promise<void> {
const enableUserCommand = new AdminEnableUserCommand({
UserPoolId: CognitoAuthConfig.userPoolId,
Username: email,
});

try {
await this.providerClient.send(enableUserCommand);
} catch {
throw new InternalServerErrorException('Failed to enable user');
}
}
}
3 changes: 3 additions & 0 deletions apps/backend/src/auth/jwt.strategy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,9 @@ export class JwtStrategy extends PassportStrategy(Strategy) {
async validate(payload: CognitoJwtPayload): Promise<User | null> {
try {
const user = await this.usersService.findUserByCognitoId(payload.sub);
if (!user.active) {
return null;
}
return user;
} catch {
return null; // Passport treats null as unauthenticated → clean 401
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 @@ -41,6 +41,7 @@ import { MakeFoodRescueRequired1773889925002 } from '../migrations/1773889925002
import { AddDonationItemConfirmation1774140453305 } from '../migrations/1774140453305-AddDonationItemConfirmation';
import { DonationItemsOnDeleteCascade1774214910101 } from '../migrations/1774214910101-DonationItemsOnDeleteCascade';
import { OrdersVolunteerActions1774883880543 } from '../migrations/1774883880543-OrdersVolunteerActions';
import { AddUserActiveField1780531200000 } from '../migrations/1780531200000-AddUserActiveField';

const schemaMigrations = [
User1725726359198,
Expand Down Expand Up @@ -86,6 +87,7 @@ const schemaMigrations = [
AddDonationItemConfirmation1774140453305,
DonationItemsOnDeleteCascade1774214910101,
OrdersVolunteerActions1774883880543,
AddUserActiveField1780531200000,
];

export default schemaMigrations;
17 changes: 17 additions & 0 deletions apps/backend/src/migrations/1780531200000-AddUserActiveField.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { MigrationInterface, QueryRunner } from 'typeorm';

export class AddUserActiveField1780531200000 implements MigrationInterface {
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`
ALTER TABLE users
ADD COLUMN active boolean NOT NULL DEFAULT true
`);
}

public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`
ALTER TABLE users
DROP COLUMN active
`);
}
}
24 changes: 17 additions & 7 deletions apps/backend/src/users/users.controller.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,8 @@ describe('UsersController', () => {
beforeEach(async () => {
mockUserService.findUsersByRoles.mockReset();
mockUserService.findOne.mockReset();
mockUserService.remove.mockReset();
mockUserService.deactivate.mockReset();
mockUserService.reactivate.mockReset();
mockUserService.update.mockReset();
mockUserService.create.mockReset();
mockUserService.getUserDashboardStats.mockReset();
Expand Down Expand Up @@ -64,14 +65,23 @@ describe('UsersController', () => {
});
});

describe('DELETE /:id', () => {
it('should remove a user by id', async () => {
mockUserService.remove.mockResolvedValue(mockUser1 as User);
describe('PATCH /:id/deactivate', () => {
it('should deactivate a user by id', async () => {
mockUserService.deactivate.mockResolvedValue(undefined);

const result = await controller.removeUser(1);
await controller.deactivateUser(1);

expect(result).toEqual(mockUser1);
expect(mockUserService.remove).toHaveBeenCalledWith(1);
expect(mockUserService.deactivate).toHaveBeenCalledWith(1);
});
});

describe('PATCH /:id/reactivate', () => {
it('should reactivate a user by id', async () => {
mockUserService.reactivate.mockResolvedValue(undefined);

await controller.reactivateUser(1);

expect(mockUserService.reactivate).toHaveBeenCalledWith(1);
});
});

Expand Down
18 changes: 11 additions & 7 deletions apps/backend/src/users/users.controller.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import {
Controller,
Delete,
Get,
Param,
ParseIntPipe,
Expand Down Expand Up @@ -51,12 +50,6 @@ export class UsersController {
return this.usersService.getRecentPendingApplications();
}

@Roles(Role.ADMIN)
@Delete('/:id')
async removeUser(@Param('id', ParseIntPipe) userId: number): Promise<User> {
return this.usersService.remove(userId);
}

@CheckOwnership({
idParam: 'id',
resolver: resolveUserAuthorizedUserIds,
Expand All @@ -70,6 +63,17 @@ export class UsersController {
}

@Roles(Role.ADMIN)
@Patch('/:id/deactivate')
async deactivateUser(@Param('id', ParseIntPipe) id: number): Promise<void> {
return this.usersService.deactivate(id);
}

@Roles(Role.ADMIN)
@Patch('/:id/reactivate')
async reactivateUser(@Param('id', ParseIntPipe) id: number): Promise<void> {
return this.usersService.reactivate(id);
}

@Post('/')
async createUser(@Body() createUserDto: userSchemaDto): Promise<User> {
return this.usersService.create(createUserDto);
Expand Down
6 changes: 6 additions & 0 deletions apps/backend/src/users/users.entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,12 @@ export class User {
})
userCognitoSub!: string;

@Column({
type: 'boolean',
default: true,
})
active!: boolean;
Comment thread
Juwang110 marked this conversation as resolved.

@ManyToMany(() => Pantry, (pantry) => pantry.volunteers)
@JoinTable({
name: 'volunteer_assignments',
Expand Down
Loading
Loading