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
506 changes: 497 additions & 9 deletions backend/package-lock.json

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
"reflect-metadata": "^0.2.2",
"rxjs": "^7.8.1",
"sharp": "^0.33.5",
"stellar-sdk": "^13.3.0",
"typeorm": "^1.0.0"
},
"devDependencies": {
Expand Down
33 changes: 32 additions & 1 deletion backend/src/admin/admin.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,42 @@ import { VerifyMentorBodyDto } from './dto/admin.dto';
import { ProfileHistoryQueryDto } from '../availability/dto/availability-query.dto';
import { SuspendUserDto } from './dto/suspend-user.dto';

import { UsersService } from '../users/users.service';

@Controller('admin')
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles(AuthRole.ADMIN)
export class AdminController {
constructor(private readonly adminService: AdminService) {}
constructor(
private readonly adminService: AdminService,
private readonly usersService: UsersService,
) {}

@Post('mentors/:id/feature')
featureMentor(
@Param('id') id: string,
@Req() req: Request & { user?: JwtPayload },
) {
const audit = {
ipAddress: (req.ip || req.socket?.remoteAddress || null) as string | null,
userAgent: req.headers['user-agent'] || null,
deviceFingerprint: null,
};
return this.usersService.featureMentor(id, audit);
}

@Delete('mentors/:id/unfeature')
unfeatureMentor(
@Param('id') id: string,
@Req() req: Request & { user?: JwtPayload },
) {
const audit = {
ipAddress: (req.ip || req.socket?.remoteAddress || null) as string | null,
userAgent: req.headers['user-agent'] || null,
deviceFingerprint: null,
};
return this.usersService.unfeatureMentor(id, audit);
}

@Post('mentors/:id/verify')
verifyMentor(
Expand Down
3 changes: 2 additions & 1 deletion backend/src/admin/admin.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,10 @@ import { AdminController } from './admin.controller';
import { AdminService } from './admin.service';
import { ProfileHistorySubscriber } from './profile-history.subscriber';
import { AuthModule } from '../auth/auth.module';
import { UsersModule } from '../users/users.module';

@Module({
imports: [TypeOrmModule.forFeature([User, ProfileHistory]), AuthModule],
imports: [TypeOrmModule.forFeature([User, ProfileHistory]), AuthModule, UsersModule],
controllers: [AdminController],
providers: [AdminService, ProfileHistorySubscriber],
})
Expand Down
4 changes: 2 additions & 2 deletions backend/src/admin/admin.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,8 @@ export class AdminService {
take: limit,
skip: offset,
});
return { items, total };
}

async suspendUser(
userId: string,
Expand All @@ -67,6 +69,4 @@ export class AdminService {
async listSuspendedUsers(limit = 50, offset = 0) {
return this.suspensionService.listActiveSuspensions(limit, offset);
}
return { items, total };
}
}
2 changes: 2 additions & 0 deletions backend/src/app.module.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Module, NestModule, MiddlewareConsumer } from '@nestjs/common';
import { ScheduleModule } from '@nestjs/schedule';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { TypeOrmModule } from '@nestjs/typeorm';
Expand All @@ -16,6 +17,7 @@ import { AdminModule } from './admin/admin.module';

@Module({
imports: [
ScheduleModule.forRoot(),
ConfigModule.forRoot({ isGlobal: true }),
TypeOrmModule.forRoot({
...AppDataSource.options,
Expand Down
30 changes: 18 additions & 12 deletions backend/src/auth/auth.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ describe('AuthService', () => {
beforeEach(async () => {
jest.useFakeTimers().setSystemTime(new Date('2026-01-01T00:00:00.000Z'));
repository = new InMemoryRefreshTokenRepository();
const userStore = {
userStore = {
users: [] as User[],
findOne: jest.fn(async (options: { where: { walletAddress?: string; id?: string } }) => {
if (options.where.walletAddress) {
Expand All @@ -132,6 +132,10 @@ describe('AuthService', () => {
logRefreshTokenUsage: jest.fn().mockResolvedValue(undefined),
logLoginSuccess: jest.fn().mockResolvedValue(undefined),
logLoginFailure: jest.fn().mockResolvedValue(undefined),
logLogout: jest.fn().mockResolvedValue(undefined),
logPasswordEquivalentChange: jest.fn().mockResolvedValue(undefined),
logRoleAssignment: jest.fn().mockResolvedValue(undefined),
};
suspensionServiceMock = { getActiveSuspension: jest.fn().mockResolvedValue(null) };

const module: TestingModule = await Test.createTestingModule({
Expand All @@ -152,9 +156,6 @@ describe('AuthService', () => {
transaction: (
handler: (entityManager: InMemoryEntityManager) => Promise<unknown>,
) => handler(manager),
transaction: (
handler: (entityManager: InMemoryEntityManager) => Promise<unknown>,
) => handler(manager),
},
},
{
Expand All @@ -178,6 +179,7 @@ describe('AuthService', () => {
});

it('rotates refresh tokens and invalidates the previous token', async () => {
userStore.users.push({ id: 'user-1', walletAddress: 'GABC', roles: [] } as any);
const issued = await service.issueTokenPair(
{ sub: 'user-1', walletAddress: 'GABC' },
audit(),
Expand All @@ -200,14 +202,19 @@ describe('AuthService', () => {
});

it('returns 401 when the refresh token is expired', async () => {
userStore.users.push({ id: 'user-1', walletAddress: 'GABC', roles: [] } as any);
const issued = await service.issueTokenPair({ sub: 'user-1' }, audit());
jest.setSystemTime(new Date('2026-02-01T00:00:01.000Z'));

await expect(service.refresh(issued.refreshToken, audit())).rejects.toBeInstanceOf(
UnauthorizedException,
);
expect(auditLogService.logRefreshTokenUsage).toHaveBeenCalledWith(
blocks login for suspended users with suspension reason', async () => {
expect.objectContaining({ success: false, userId: null }),
);
});

it('blocks login for suspended users with suspension reason', async () => {
userStore.users.push({
id: 'user-1',
walletAddress: 'GABC',
Expand Down Expand Up @@ -237,13 +244,15 @@ describe('AuthService', () => {

await expect(service.login('GABC', audit())).rejects.toBeInstanceOf(ForbiddenException);
expect(auditLogService.logLoginFailure).toHaveBeenCalledWith(
'GABC',
expect.anything(),
'Account suspended',
expect.objectContaining({
attemptedWalletAddress: 'GABC',
reason: 'Account suspended',
})
);
});

it('blocks refresh for suspended users with suspension reason', async () => {
userStore.users.push({ id: 'user-1', walletAddress: 'GABC', roles: [] } as any);
const issued = await service.issueTokenPair({ sub: 'user-1', walletAddress: 'GABC' }, audit());
const suspended = {
id: 'suspension-1',
Expand All @@ -264,11 +273,8 @@ describe('AuthService', () => {
);
});

it('expect.objectContaining({ success: false, userId: 'user-1' }),
);
});

it('detects refresh token reuse and revokes the token family', async () => {
userStore.users.push({ id: 'user-1', walletAddress: 'GABC', roles: [] } as any);
const issued = await service.issueTokenPair({ sub: 'user-1' }, audit());
await service.refresh(issued.refreshToken, audit());

Expand Down
2 changes: 2 additions & 0 deletions backend/src/auth/entities/audit-log.entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ export enum AuditEventType {
UNSUSPEND_USER = 'UNSUSPEND_USER',
SUSPICIOUS_ACTIVITY = 'SUSPICIOUS_ACTIVITY',
USERNAME_CHANGED = 'USERNAME_CHANGED',
MENTOR_FEATURED = 'MENTOR_FEATURED',
MENTOR_UNFEATURED = 'MENTOR_UNFEATURED',
}

@Entity({ name: 'audit_logs' })
Expand Down
10 changes: 6 additions & 4 deletions backend/src/auth/suspension.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,8 @@ describe('SuspensionService', () => {
};
const auditLogService = {
logEvent: jest.fn(),
logUserSuspension: jest.fn(),
logUserUnsuspension: jest.fn(),
};
const manager = {
create: jest.fn(),
Expand Down Expand Up @@ -129,9 +131,9 @@ describe('SuspensionService', () => {
suspendedBy: 'admin-1',
}));
expect(refreshUpdateBuilder.execute).toHaveBeenCalled();
expect(auditLogService.logEvent).toHaveBeenCalledWith(expect.objectContaining({
expect(auditLogService.logUserSuspension).toHaveBeenCalledWith(expect.objectContaining({
userId: 'user-1',
eventType: 'SUSPEND_USER',
suspendedBy: 'admin-1',
}));
});
});
Expand Down Expand Up @@ -164,9 +166,9 @@ describe('SuspensionService', () => {

expect(result.liftedAt).toBeInstanceOf(Date);
expect(result.liftedBy).toBe('admin-1');
expect(auditLogService.logEvent).toHaveBeenCalledWith(expect.objectContaining({
expect(auditLogService.logUserUnsuspension).toHaveBeenCalledWith(expect.objectContaining({
userId: 'user-1',
eventType: 'UNSUSPEND_USER',
liftedBy: 'admin-1',
}));
});
});
Expand Down
1 change: 1 addition & 0 deletions backend/src/common/filters/http-exception.filter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@ export class HttpExceptionFilter implements ExceptionFilter {
responseBody.code ?? mapHttpStatusToErrorCode(status, error.toString());

const payload: Record<string, unknown> = {
success: false,
statusCode: status,
message,
error,
Expand Down
67 changes: 67 additions & 0 deletions backend/src/common/interceptors/response.interceptor.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import {
Injectable,
NestInterceptor,
ExecutionContext,
CallHandler,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { Request, Response } from 'express';

export interface ResponseEnvelope<T> {
success: boolean;
statusCode: number;
message: string;
data: T;
timestamp: string;
path: string;
}

@Injectable()
export class ResponseInterceptor<T>
implements NestInterceptor<T, ResponseEnvelope<T>>
{
intercept(
context: ExecutionContext,
next: CallHandler,
): Observable<ResponseEnvelope<T>> {
const ctx = context.switchToHttp();
const response = ctx.getResponse<Response>();
const request = ctx.getRequest<Request>();

const statusCode = response.statusCode;
const path = request.originalUrl || request.url || '';
const timestamp = new Date().toISOString();

return next.handle().pipe(
map((data) => {
// If data is already an envelope, return it as is
if (
data &&
typeof data === 'object' &&
'success' in data &&
'statusCode' in data
) {
return data;
}

// Determine message
let message = 'Operation successful';
if (data && typeof data === 'object' && 'message' in data && typeof data.message === 'string') {
message = data.message;
// Optionally remove message from data if you don't want it duplicated
// delete data.message;
}

return {
success: true,
statusCode,
message,
data: data !== undefined ? data : null,
timestamp,
path,
};
}),
);
}
}
3 changes: 3 additions & 0 deletions backend/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import { DataSource } from 'typeorm';
import { ApiValidationException } from './common/exceptions/api-exceptions';
import { HttpExceptionFilter } from './common/filters/http-exception.filter';

import { ResponseInterceptor } from './common/interceptors/response.interceptor';

async function bootstrap() {
const app = await NestFactory.create(AppModule, {
// Disable NestJS built-in logger noise; our middleware handles request logs
Expand All @@ -28,6 +30,7 @@ async function bootstrap() {
}),
);
app.useGlobalFilters(new HttpExceptionFilter());
app.useGlobalInterceptors(new ResponseInterceptor());

// Verify database connection before starting server
const dataSource = app.get(DataSource);
Expand Down
53 changes: 53 additions & 0 deletions backend/src/users/cron/featured-mentor.cron.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import { Injectable, Logger } from '@nestjs/common';
import { Cron, CronExpression } from '@nestjs/schedule';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, LessThan } from 'typeorm';
import { User } from '../entities/user.entity';
import { AuditLogService } from '../../auth/audit-log.service';
import { AuditEventType } from '../../auth/entities/audit-log.entity';

@Injectable()
export class FeaturedMentorCron {
private readonly logger = new Logger(FeaturedMentorCron.name);

constructor(
@InjectRepository(User)
private readonly userRepo: Repository<User>,
private readonly auditLogService: AuditLogService,
) {}

@Cron(CronExpression.EVERY_DAY_AT_MIDNIGHT)
async handleCron() {
this.logger.debug('Running expired featured mentors cleanup job');

// 30 days ago
const thirtyDaysAgo = new Date();
thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);

const expiredMentors = await this.userRepo.find({
where: {
isFeatured: true,
featuredAt: LessThan(thirtyDaysAgo),
},
});

if (expiredMentors.length === 0) {
return;
}

for (const mentor of expiredMentors) {
mentor.isFeatured = false;
mentor.featuredAt = null;
mentor.featuredOrder = null;
await this.userRepo.save(mentor);

await this.auditLogService.logEvent({
userId: mentor.id,
eventType: 'MENTOR_UNFEATURED' as AuditEventType,
details: { reason: 'Expired after 30 days' },
});

this.logger.log(`Unfeatured mentor ${mentor.id} due to expiry`);
}
}
}
11 changes: 11 additions & 0 deletions backend/src/users/entities/user.entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,17 @@ export class User {
@UpdateDateColumn({ name: 'updated_at', type: 'timestamptz' })
updatedAt!: Date;

@Index()
@Column({ name: 'is_featured', type: 'boolean', default: false })
isFeatured!: boolean;

@Column({ name: 'featured_at', type: 'timestamptz', nullable: true })
featuredAt!: Date | null;

@Index()
@Column({ name: 'featured_order', type: 'int', nullable: true })
featuredOrder!: number | null;

@ManyToMany(() => Role, (role) => role.users, { eager: true })
@JoinTable({
name: 'user_roles',
Expand Down
Loading
Loading