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
1 change: 1 addition & 0 deletions src/API/src/auth/auth.controller.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Body, Controller, Get, Param, Post, UseGuards } from '@nestjs/common';

Check warning on line 1 in src/API/src/auth/auth.controller.ts

View workflow job for this annotation

GitHub Actions / Build and Test API for test deployment environment

'Param' is defined but never used
import { AuthGuard } from '@nestjs/passport';
import * as jwt from 'njwt';
import { AuthUser } from './user.decorator';
Expand All @@ -24,6 +24,7 @@
sub: userId,
scope: createScope(userEntity),
aud: process.env.AUTH0_AUDIENCE,
disable_notification: userEntity.disable_notification || false,
};
const token = jwt.create(claims, process.env.TOKEN_KEY);
token.setExpiration(new Date().getTime() + 60000 * 1000);
Expand Down Expand Up @@ -94,7 +95,7 @@
// name: '[email protected]',
// nickname: 'petergituu',
// picture:
// 'https://s.gravatar.com/avatar/4850a0a35ee31a4b2d85e102dd7ea732?s=480&r=pg&d=https%3A%2F%2Fcdn.auth0.com%2Favatars%2Fpe.png',

Check warning on line 98 in src/API/src/auth/auth.controller.ts

View workflow job for this annotation

GitHub Actions / Build and Test API for test deployment environment

This line has a length of 132. Maximum allowed is 120
// updated_at: '2024-12-05T19:16:36.556Z',
// user_id: 'auth0|633d223bd2c75a12885805a8',
// last_password_reset: '2023-02-02T12:18:03.449Z',
Expand Down
56 changes: 54 additions & 2 deletions src/API/src/db/email-registry/email-registry.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
Query,
Res,
UseGuards,
BadRequestException,
} from '@nestjs/common';
import { Response } from 'express';

Expand All @@ -22,11 +23,19 @@ import { SubscriptionResponseDto } from './dto/subscription-response.dto';
import { EmailRegistryService } from './email-registry.service';
import { GqlAuthGuard } from 'src/auth/gqlAuthGuard';
import { RolesGuard } from 'src/auth/user_role/roles.guard';
import { Queue } from 'bullmq';
import { InjectQueue } from '@nestjs/bullmq';
import { Role } from 'src/auth/user_role/role.enum';
import { Roles } from 'src/auth/user_role/roles.decorator';

@Controller()
@UseInterceptors(ClassSerializerInterceptor)
export class EmailRegistryController {
constructor(private readonly emailRegistryService: EmailRegistryService) {}
constructor(
private readonly emailRegistryService: EmailRegistryService,
@InjectQueue('subscription-queue')
private readonly subscriptionQueue: Queue,
) {}

@Post('subscribe')
@HttpCode(HttpStatus.CREATED)
Expand All @@ -35,14 +44,37 @@ export class EmailRegistryController {
): Promise<SubscriptionResponseDto> {
return this.emailRegistryService.subscribe(subscribeEmailDto);
}

@Get('subscribers')
@UseGuards(GqlAuthGuard, RolesGuard)
async getSubscribers() {
return this.emailRegistryService.findAll({});
}
@Get('verify')
@HttpCode(HttpStatus.OK)
async verify(
@Query() query: VerifyTokenDto,
): Promise<SubscriptionResponseDto> {
return this.emailRegistryService.verify(query);
}
@Post('cleanup-job')
@UseGuards(GqlAuthGuard, RolesGuard)
@Roles(Role.Admin)
async startCleanupJob() {
const job = await this.subscriptionQueue.add(
'clean-expired-subscribers',
{ timestamp: new Date() },
{
repeat: {
pattern: '0 0 * * 0',
},
},
);

return {
message: 'Weekly cleanup job added to the background queue successfully.',
jobId: job.id,
};
}

@Delete('unsubscribe')
@HttpCode(HttpStatus.NO_CONTENT)
Expand All @@ -51,6 +83,26 @@ export class EmailRegistryController {
): Promise<void> {
return this.emailRegistryService.unsubscribe(unsubscribeEmailDto);
}
@Post('manual-add')
@UseGuards(GqlAuthGuard, RolesGuard)
async manualAdd(
@Body() body: { email: string; first_name?: string; last_name?: string },
) {
if (!body.email) {
throw new BadRequestException('Email is required');
}
return this.emailRegistryService.createManual(body);
}
@Post('request-unsubscribe')
@HttpCode(HttpStatus.OK)
async requestUnsubscribe(
@Body('email') email: string,
): Promise<{ message: string; type: string }> {
if (!email) {
throw new BadRequestException('Email is required');
}
return this.emailRegistryService.requestUnsubscribe(email);
}

@Get('export')
@UseGuards(GqlAuthGuard, RolesGuard)
Expand Down
17 changes: 15 additions & 2 deletions src/API/src/db/email-registry/email-registry.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,23 @@ import { EmailRegistry } from './entities/email-registry.entity';
import { TypeOrmModule } from '@nestjs/typeorm/dist/typeorm.module';
import { EmailModule } from 'src/email/email.module';
import { EmailRegistryController } from './email-registry.controller';
import { BullModule } from '@nestjs/bullmq';
import { UserRole } from 'src/auth/user_role/user_role.entity';
import { SubscriptionProcessor } from './email-registry.processor';
import { AuthModule } from 'src/auth/auth.module';

@Module({
imports: [TypeOrmModule.forFeature([EmailRegistry]), EmailModule],
providers: [EmailRegistryService, EmailRegistryResolver],
imports: [
TypeOrmModule.forFeature([EmailRegistry, UserRole]),
EmailModule,
BullModule.registerQueue({ name: 'subscription-queue' }),
AuthModule,
],
providers: [
EmailRegistryService,
EmailRegistryResolver,
SubscriptionProcessor,
],
controllers: [EmailRegistryController],
})
export class EmailRegistryModule {}
36 changes: 36 additions & 0 deletions src/API/src/db/email-registry/email-registry.processor.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { Processor, WorkerHost } from '@nestjs/bullmq';
import { Job } from 'bullmq';
import { Injectable, Logger } from '@nestjs/common';
import { EmailRegistryService } from './email-registry.service';

@Processor('subscription-queue')
@Injectable()
export class SubscriptionProcessor extends WorkerHost {
private readonly logger = new Logger(SubscriptionProcessor.name);

constructor(private readonly emailRegistryService: EmailRegistryService) {
super();
}

async process(job: Job<any, any, string>): Promise<any> {
// this.logger.log(`Starting background job ${job.id}:${job.name}`);

if (job.name === 'clean-expired-subscribers') {
try {
// Progress logging in frontend
await job.updateProgress(10);

const deletedCount =
await this.emailRegistryService.hardDeleteInactiveSubscribers();

await job.updateProgress(100);
//this.logger.log(`Job ${job.id} completed successfully. Deleted ${deletedCount}`);

return { success: true, recordsDeleted: deletedCount };
} catch (error) {
this.logger.error(`Job ${job.id} failed`, error);
throw error;
}
}
}
}
146 changes: 144 additions & 2 deletions src/API/src/db/email-registry/email-registry.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,11 @@ import { UnsubscribeEmailDto } from './dto/unsubscribe-email.dto';
import { AccountStatus } from './entities/email-registry.entity';
import { ILike } from 'typeorm';
import * as ExcelJS from 'exceljs';
import { UserRole } from 'src/auth/user_role/user_role.entity';
import { Queue } from 'bullmq';
import { OnApplicationBootstrap } from '@nestjs/common';
import { InjectQueue } from '@nestjs/bullmq';
import { AuthService } from 'src/auth/auth.service';

/**
* Evaluates token windows against a strict 48-hour Time-To-Live validation boundary.
Expand All @@ -26,12 +31,32 @@ export class EmailRegistryService {
@InjectRepository(EmailRegistry)
private readonly emailRegistryRepository: Repository<EmailRegistry>,
private readonly emailService: EmailService,
@InjectRepository(UserRole)
private readonly userRoleRepository: Repository<UserRole>,
@InjectQueue('subscription-queue')
private readonly subscriptionQueue: Queue,
private readonly authService: AuthService,
) {}

async hardDeleteInactiveSubscribers(): Promise<number> {
const result = await this.emailRegistryRepository
.createQueryBuilder()
.delete()
.from(EmailRegistry)
.where('account_status = :unsubscribed', {
unsubscribed: AccountStatus.UNSUBSCRIBED,
})
.orWhere('(account_status = :pending AND token_expires_at < :now)', {
pending: AccountStatus.PENDING_VERIFICATION,
now: new Date(),
})
.execute();

return result.affected || 0;
}
async subscribe(payload: SubscribeEmailDto): Promise<EmailRegistry> {
const email = payload.email.trim().toLowerCase();
const verificationToken = uuidv4();
const unsubscriptionToken = uuidv4(); // Generate early so it is immediately ready
const unsubscriptionToken = uuidv4();
const codeExpiresAt = new Date(Date.now() + VERIFICATION_CODE_TTL_MS);

let entry = await this.emailRegistryRepository.findOne({
Expand Down Expand Up @@ -82,6 +107,7 @@ export class EmailRegistryService {
await this.emailService.sendEmail(
[savedEntry.email],
[],

'Verify your email subscription',
`
<p>Thanks for subscribing to updates, ${savedEntry.first_name}.</p>
Expand All @@ -101,6 +127,7 @@ export class EmailRegistryService {

async verify(query: VerifyTokenDto): Promise<EmailRegistry> {
const trimmedToken = query.token?.trim();
console.log(`Backend received token for verification: [${trimmedToken}]`);
if (!trimmedToken) {
throw new BadRequestException(
'Verification token parameter is missing from request.',
Expand Down Expand Up @@ -142,6 +169,18 @@ export class EmailRegistryService {
// NOTE: Keep the token or invalidate cleanly without breaking single-click checks
return await this.emailRegistryRepository.save(entry);
}
async deleteExpiredPendingAccounts(): Promise<number> {
const result = await this.emailRegistryRepository
.createQueryBuilder()
.delete()
.from(EmailRegistry)
.where('account_status =: status', {
status: AccountStatus.PENDING_VERIFICATION,
})
.andWhere('token_expires_at <: now', { now: new Date() })
.execute();
return result.affected || 0;
}

async unsubscribe(payload: UnsubscribeEmailDto): Promise<void> {
const targetId = payload.id?.trim();
Expand Down Expand Up @@ -171,6 +210,19 @@ export class EmailRegistryService {
await this.emailRegistryRepository.save(entry);
}

async toggleNotificationsByEmail(
email: string,
enabled: boolean,
): Promise<void> {
const record = await this.emailRegistryRepository.findOne({
where: { email: email.toLowerCase() },
});
if (record) {
record.notifications_enabled = enabled;
await this.emailRegistryRepository.save(record);
}
}

private async *streamVerified() {
const chunkSize = 500;
let lastId: string | null = null;
Expand Down Expand Up @@ -420,7 +472,97 @@ export class EmailRegistryService {
</body>
</html>`;
}
async createManualSubscrption(input: {
email: string;
first_name?: string;
last_name?: string;
}): Promise<EmailRegistry> {
const email = input.email.trim().toLowerCase();

let entry = await this.emailRegistryRepository.findOne({
where: { email },
});

if (entry) {
throw new BadRequestException('This email is already in the registry.');
}

entry = this.emailRegistryRepository.create({
id: uuidv4(),
first_name: input.first_name || '',
last_name: input.last_name || '',
email: email,
notifications_enabled: true,
account_status: AccountStatus.VERIFIED, // Admin skips pending state
verification_token: uuidv4(),
token_expires_at: new Date(Date.now() + VERIFICATION_CODE_TTL_MS),
unsubscription_token: uuidv4(),
});

return await this.emailRegistryRepository.save(entry);
}
async requestUnsubscribe(
email: string,
): Promise<{ message: string; type: string }> {
const normalizedEmail = email.trim().toLowerCase();

const entry = await this.emailRegistryRepository.findOne({
where: { email: normalizedEmail },
});

if (!entry || entry.account_status === AccountStatus.UNSUBSCRIBED) {
// 1. Initialize Auth0 client (required based on your AuthController pattern)
await this.authService.init();

// 2. Fetch all Auth0 users and find the match
const allUsers = await this.authService.getAllUsers();
const appUser = allUsers?.find((u) => u.email === normalizedEmail);

// 3. If found, turn off their notifications in UserRole
if (appUser && appUser.user_id) {
const userRole = await this.userRoleRepository.findOne({
where: { auth0_id: appUser.user_id },
});

if (userRole) {
userRole.disable_notification = true;
await this.userRoleRepository.save(userRole);
}
}

return {
message: 'Account notifications disabled.',
type: 'direct_disable',
};
}

// 2. Existing Email Registry Logic
const frontendBaseUrl =
process.env.FRONTEND_BASE_URL?.trim() || 'http://localhost:3000';
const unsubscribeLink = new URL('/unsubscribed-success', frontendBaseUrl);

unsubscribeLink.searchParams.set('id', entry.id);
unsubscribeLink.searchParams.set('token', entry.unsubscription_token);

await this.emailService.sendEmail(
[entry.email],
[],
'Vector Atlas - Unsubscribe Request',
`
<p>Hello ${entry.first_name || ''},</p>
<p>We received a request to unsubscribe you from Vector Atlas updates.</p>
<p>If you made this request, please click the link below to confirm:</p>
<p><a href="${unsubscribeLink.toString()}">Confirm Unsubscription</a></p>
<br/>
<p style="font-size: 12px; color: #888888;">If you did not request this, please ignore this email.</p>
`,
);

return {
message: 'Unsubscribe link sent.',
type: 'email_sent',
};
}
async queueDatasetCampaign(
title: string,
message: string,
Expand Down
Loading
Loading