-
Notifications
You must be signed in to change notification settings - Fork 0
PM-1374 - require otp when withdrawing #75
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 1 commit
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
12 changes: 12 additions & 0 deletions
12
prisma/migrations/20250618100641_drop_otp_transaction/migration.sql
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,12 @@ | ||
/* | ||
Warnings: | ||
- You are about to drop the column `transaction_id` on the `otp` table. All the data in the column will be lost. | ||
- You are about to drop the `transaction` table. If the table is not empty, all the data it contains will be lost. | ||
*/ | ||
-- AlterTable | ||
ALTER TABLE "otp" DROP COLUMN "transaction_id"; | ||
|
||
-- DropTable | ||
DROP TABLE "transaction"; | ||
vas3a marked this conversation as resolved.
Show resolved
Hide resolved
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,12 +1,15 @@ | ||
import { Global, Module } from '@nestjs/common'; | ||
import { PrismaService } from './prisma.service'; | ||
import { TrolleyService } from './trolley.service'; | ||
import { OtpService } from './otp.service'; | ||
import { TopcoderModule } from '../topcoder/topcoder.module'; | ||
vas3a marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
// Global module for providing global providers | ||
// Add any provider you want to be global here | ||
@Global() | ||
@Module({ | ||
providers: [PrismaService, TrolleyService], | ||
exports: [PrismaService, TrolleyService], | ||
imports: [TopcoderModule], | ||
providers: [PrismaService, TrolleyService, OtpService], | ||
exports: [PrismaService, TrolleyService, OtpService], | ||
}) | ||
export class GlobalProvidersModule {} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,176 @@ | ||
import { Injectable, Logger } from '@nestjs/common'; | ||
import { PrismaService } from './prisma.service'; | ||
import crypto from 'crypto'; | ||
import { reference_type } from '@prisma/client'; | ||
import { ENV_CONFIG } from 'src/config'; | ||
import { TopcoderEmailService } from '../topcoder/tc-email.service'; | ||
import { BasicMemberInfo } from '../topcoder'; | ||
|
||
const generateRandomOtp = (length: number): string => { | ||
const digits = '0123456789'; | ||
let otp = ''; | ||
for (let i = 0; i < length; i++) { | ||
otp += digits[Math.floor(Math.random() * digits.length)]; | ||
} | ||
return otp; | ||
}; | ||
|
||
const hashOtp = (otp: string): string => { | ||
const hasher = crypto.createHash('sha256'); | ||
hasher.update(otp); | ||
return hasher.digest('hex'); | ||
}; | ||
|
||
@Injectable() | ||
export class OtpService { | ||
private readonly logger = new Logger(`global/OtpService`); | ||
|
||
constructor( | ||
private readonly prisma: PrismaService, | ||
private readonly tcEmailService: TopcoderEmailService, | ||
) {} | ||
|
||
async generateOtpCode(userInfo: BasicMemberInfo, action_type: string) { | ||
const actionType = reference_type[action_type as keyof reference_type]; | ||
vas3a marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
const email = userInfo.email; | ||
|
||
const existingOtp = await this.prisma.otp.findFirst({ | ||
where: { | ||
email, | ||
action_type: actionType, | ||
verified_at: null, | ||
expiration_time: { | ||
gt: new Date(), | ||
}, | ||
}, | ||
orderBy: { | ||
expiration_time: 'desc', | ||
}, | ||
}); | ||
|
||
if (existingOtp) { | ||
this.logger.warn( | ||
`An OTP has already been sent for email ${email} and action ${action_type}.`, | ||
); | ||
return { | ||
code: 'otp_exists', | ||
message: 'An OTP has already been sent! Please check your email!', | ||
}; | ||
} | ||
|
||
// Generate a new OTP code | ||
const otpCode = generateRandomOtp(6); // Generate a 6-digit OTP | ||
const otpHash = hashOtp(otpCode); | ||
|
||
const expirationTime = new Date(); | ||
expirationTime.setMinutes( | ||
expirationTime.getMinutes() + ENV_CONFIG.OTP_CODE_VALIDITY_MINUTES, | ||
); | ||
|
||
// Save the new OTP code in the database | ||
await this.prisma.otp.create({ | ||
data: { | ||
email, | ||
action_type: actionType, | ||
otp_hash: otpHash, | ||
expiration_time: expirationTime, | ||
created_at: new Date(), | ||
}, | ||
}); | ||
|
||
// Simulate sending an email (replace with actual email service logic) | ||
await this.tcEmailService.sendEmail( | ||
email, | ||
ENV_CONFIG.SENDGRID_TEMPLATE_ID_OTP_CODE, | ||
{ | ||
data: { | ||
otp: otpCode, | ||
name: [userInfo.firstName, userInfo.lastName] | ||
.filter(Boolean) | ||
.join(' '), | ||
}, | ||
}, | ||
); | ||
this.logger.debug( | ||
`Generated and sent OTP code ${otpCode.replace(/./g, '*')} for email ${email} and action ${action_type}.`, | ||
); | ||
|
||
return { | ||
code: 'otp_required', | ||
}; | ||
} | ||
|
||
async verifyOtpCode( | ||
otpCode: string, | ||
userInfo: BasicMemberInfo, | ||
action_type: string, | ||
) { | ||
const record = await this.prisma.otp.findFirst({ | ||
vas3a marked this conversation as resolved.
Show resolved
Hide resolved
|
||
where: { | ||
otp_hash: hashOtp(otpCode), | ||
}, | ||
orderBy: { | ||
expiration_time: 'desc', | ||
}, | ||
}); | ||
|
||
if (!record) { | ||
this.logger.warn(`No OTP record found for the provided code.`); | ||
return { code: 'otp_invalid', message: `Invalid OTP code.` }; | ||
} | ||
|
||
if (record.email !== userInfo.email) { | ||
this.logger.warn(`Email mismatch for OTP verification.`); | ||
return { | ||
code: 'otp_email_mismatch', | ||
message: `Email mismatch for OTP verification.`, | ||
}; | ||
} | ||
|
||
if (record.action_type !== action_type) { | ||
this.logger.warn(`Action type mismatch for OTP verification.`); | ||
return { | ||
code: 'otp_action_type_mismatch', | ||
message: `Action type mismatch for OTP verification.`, | ||
}; | ||
} | ||
|
||
if (record.expiration_time && record.expiration_time < new Date()) { | ||
this.logger.warn(`OTP code has expired.`); | ||
return { code: 'otp_expired', message: `OTP code has expired.` }; | ||
} | ||
|
||
if (record.verified_at !== null) { | ||
this.logger.warn(`OTP code has already been verified.`); | ||
return { | ||
code: 'otp_already_verified', | ||
message: `OTP code has already been verified.`, | ||
}; | ||
} | ||
|
||
this.logger.log( | ||
`OTP code ${otpCode} verified successfully for action ${action_type}`, | ||
); | ||
|
||
await this.prisma.otp.update({ | ||
where: { | ||
id: record.id, | ||
}, | ||
data: { | ||
verified_at: new Date(), | ||
}, | ||
}); | ||
} | ||
|
||
otpCodeGuard( | ||
userInfo: BasicMemberInfo, | ||
vas3a marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
action_type: string, | ||
otpCode?: string, | ||
): Promise<{ message?: string; code?: string } | void> { | ||
if (!otpCode) { | ||
return this.generateOtpCode(userInfo, action_type); | ||
} | ||
|
||
return this.verifyOtpCode(otpCode, userInfo, action_type); | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.