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
230 changes: 230 additions & 0 deletions backend/src/admin/admin.controller.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,230 @@
import { Test, TestingModule } from '@nestjs/testing';
import { AdminController } from './admin.controller';
import { getRepositoryToken } from '@nestjs/typeorm';
import { User, UserRole } from '../auth/entities/user.entity';
import { Donation } from '../donations/entities/donation.entity';
import { NotFoundException } from '@nestjs/common';

describe('AdminController', () => {
let controller: AdminController;

const mockUserRepository = {
find: jest.fn(),
findOne: jest.fn(),
save: jest.fn(),
};

const mockDonationRepository = {
find: jest.fn(),
};

beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [AdminController],
providers: [
{
provide: getRepositoryToken(User),
useValue: mockUserRepository,
},
{
provide: getRepositoryToken(Donation),
useValue: mockDonationRepository,
},
],
}).compile();

controller = module.get<AdminController>(AdminController);
});

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

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

describe('getPendingNGOs', () => {
it('should return list of unverified NGOs', async () => {
const mockNGOs = [
{
id: '1',
name: 'Food Bank A',
email: 'foodbank@example.com',
role: UserRole.NGO,
isVerified: false,
organizationName: 'Food Bank A',
phone: '1234567890',
address: '123 Main St',
createdAt: new Date(),
},
];

mockUserRepository.find.mockResolvedValue(mockNGOs);

const result = await controller.getPendingNgos();

expect(mockUserRepository.find).toHaveBeenCalledWith({
where: {
role: UserRole.NGO,
isVerified: false,
},
select: ['id', 'name', 'email', 'organizationName', 'phone', 'address', 'createdAt'],
});
expect(result).toEqual(mockNGOs);
});
});

describe('verifyNgo', () => {
it('should verify an NGO and update isVerified to true', async () => {
const ngoId = '123';
const mockNGO = {
id: ngoId,
name: 'Food Bank A',
organizationName: 'Food Bank A',
isVerified: false,
};

mockUserRepository.findOne.mockResolvedValue(mockNGO);
mockUserRepository.save.mockResolvedValue({ ...mockNGO, isVerified: true });

const result = await controller.verifyNgo(ngoId);

expect(mockUserRepository.findOne).toHaveBeenCalledWith({ where: { id: ngoId } });
expect(mockUserRepository.save).toHaveBeenCalledWith({ ...mockNGO, isVerified: true });
expect(result.message).toContain('verified');
});

it('should throw NotFoundException if NGO does not exist', async () => {
mockUserRepository.findOne.mockResolvedValue(null);

await expect(controller.verifyNgo('invalid-id')).rejects.toThrow(NotFoundException);
});
});

describe('getAllUsers', () => {
it('should return all users with specific fields', async () => {
const mockUsers = [
{
id: '1',
name: 'John Donor',
email: 'john@example.com',
role: UserRole.DONOR,
isVerified: true,
isActive: true,
createdAt: new Date(),
},
{
id: '2',
name: 'NGO Helper',
email: 'ngo@example.com',
role: UserRole.NGO,
organizationName: 'Helper Org',
isVerified: false,
isActive: true,
createdAt: new Date(),
},
];

mockUserRepository.find.mockResolvedValue(mockUsers);

const result = await controller.getAllUsers();

expect(mockUserRepository.find).toHaveBeenCalledWith({
select: ['id', 'name', 'email', 'role', 'organizationName', 'isVerified', 'isActive', 'createdAt'],
order: { createdAt: 'DESC' },
});
expect(result).toEqual(mockUsers);
});
});

describe('toggleUserStatus', () => {
it('should suspend an active user', async () => {
const userId = '123';
const mockUser = {
id: userId,
name: 'John Doe',
role: UserRole.DONOR,
isActive: true,
};

mockUserRepository.findOne.mockResolvedValue(mockUser);
mockUserRepository.save.mockResolvedValue({ ...mockUser, isActive: false });

const result = await controller.toggleUserStatus(userId);

expect(mockUserRepository.save).toHaveBeenCalledWith({ ...mockUser, isActive: false });
expect(result.message).toContain('suspended');
expect(result.isActive).toBe(false);
});

it('should restore a suspended user', async () => {
const userId = '123';
const mockUser = {
id: userId,
name: 'John Doe',
role: UserRole.DONOR,
isActive: false,
};

mockUserRepository.findOne.mockResolvedValue(mockUser);
mockUserRepository.save.mockResolvedValue({ ...mockUser, isActive: true });

const result = await controller.toggleUserStatus(userId);

expect(mockUserRepository.save).toHaveBeenCalledWith({ ...mockUser, isActive: true });
expect(result.message).toContain('unbanned');
expect(result.isActive).toBe(true);
});

it('should prevent suspending an admin account', async () => {
const adminUser = {
id: 'admin-123',
name: 'System Admin',
role: UserRole.ADMIN,
isActive: true,
};

mockUserRepository.findOne.mockResolvedValue(adminUser);

await expect(controller.toggleUserStatus('admin-123')).rejects.toThrow(
'Cannot suspend an administrator account',
);
});

it('should throw NotFoundException if user does not exist', async () => {
mockUserRepository.findOne.mockResolvedValue(null);

await expect(controller.toggleUserStatus('invalid-id')).rejects.toThrow(NotFoundException);
});
});

describe('getAllDonations', () => {
it('should return all donations with donor relations', async () => {
const mockDonations = [
{
id: '1',
name: 'Rice',
quantity: 50,
unit: 'kg',
status: 'AVAILABLE',
donor: {
id: 'donor-1',
name: 'Restaurant A',
},
createdAt: new Date(),
},
];

mockDonationRepository.find.mockResolvedValue(mockDonations);

const result = await controller.getAllDonations();

expect(mockDonationRepository.find).toHaveBeenCalledWith({
relations: ['donor'],
order: { createdAt: 'DESC' },
});
expect(result).toEqual(mockDonations);
});
});
});
83 changes: 83 additions & 0 deletions backend/src/admin/admin.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
import { Controller, Get, Patch, Param, UseGuards, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User, UserRole } from '../auth/entities/user.entity';
import { Donation } from '../donations/entities/donation.entity';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { RolesGuard } from '../auth/guards/roles.guard';

@UseGuards(JwtAuthGuard, RolesGuard) // 🛡️ LOCKED DOWN!
@Controller('admin')
export class AdminController {
constructor(
@InjectRepository(User)
private userRepository: Repository<User>,
@InjectRepository(Donation)
private donationRepository: Repository<Donation>,
) {}

// 1. Get all NGOs that are waiting for approval
@Get('pending-ngos')
async getPendingNgos() {
return await this.userRepository.find({
where: {
role: UserRole.NGO,
isVerified: false,
},
select: ['id', 'name', 'email', 'organizationName', 'phone', 'address', 'createdAt'], // Don't send passwords!
});
}

// 2. Approve/Verify an NGO
@Patch('verify/:id')
async verifyNgo(@Param('id') id: string) {
const user = await this.userRepository.findOne({ where: { id } });

if (!user) {
throw new NotFoundException('User not found');
}

user.isVerified = true;
await this.userRepository.save(user);

return { message: `${user.organizationName || user.name} has been successfully verified!`, user };
}

// 3. Get ALL Users (For the main Admin User Table)
@Get('users')
async getAllUsers() {
return await this.userRepository.find({
select: ['id', 'name', 'email', 'role', 'organizationName', 'isVerified', 'isActive', 'createdAt'],
order: { createdAt: 'DESC' }
});
}

// 4. Suspend or Unsuspend a User (Moderation - Epic 7, US 2)
@Patch('users/:id/toggle-status')
async toggleUserStatus(@Param('id') id: string) {
const user = await this.userRepository.findOne({ where: { id } });
if (!user) throw new NotFoundException('User not found');

// Prevent the Super Admin from accidentally banning themselves
if (user.role === UserRole.ADMIN) {
throw new Error('Cannot suspend an administrator account');
}

user.isActive = !user.isActive; // Flip true to false, or false to true
await this.userRepository.save(user);

return {
message: `User ${user.name} has been ${user.isActive ? 'unbanned' : 'suspended'}.`,
isActive: user.isActive
};
}

// 5. Get ALL Platform Donations (For the Admin Overview)
@Get('donations')
async getAllDonations() {
return await this.donationRepository.find({
relations: ['donor'], // Loads the donor details so admin sees who posted it
order: { createdAt: 'DESC' }
});
}
}
11 changes: 11 additions & 0 deletions backend/src/admin/admin.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AdminController } from './admin.controller';
import { User } from '../auth/entities/user.entity';
import { Donation } from '../donations/entities/donation.entity';

@Module({
imports: [TypeOrmModule.forFeature([User, Donation])],
controllers: [AdminController],
})
export class AdminModule {}
4 changes: 4 additions & 0 deletions backend/src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { AppController } from './app.controller';
import { AppService } from './app.service';
import { AuthModule } from './auth/auth.module';
import { DonationsModule } from './donations/donations.module';
import { AdminModule } from './admin/admin.module';
import { User } from './auth/entities/user.entity';
import { Donation } from './donations/entities/donation.entity';
import { CacheModule } from '@nestjs/cache-manager';
Expand Down Expand Up @@ -40,6 +41,9 @@ import * as redisStore from 'cache-manager-redis-store';

AuthModule,
DonationsModule,

// Admin dashboard module
AdminModule,
],
controllers: [AppController],
providers: [AppService],
Expand Down
6 changes: 6 additions & 0 deletions backend/src/auth/entities/user.entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,12 @@ export class User {
@Column({ type: 'enum', enum: UserRole, default: UserRole.DONOR })
role: UserRole;

@Column({ default: false })
isVerified: boolean;

@Column({ default: true })
isActive: boolean; // false = suspended/banned

@Column()
name: string;

Expand Down
Loading