mirror of
https://github.com/andwati/nestjs-auth-email-phone.git
synced 2026-11-18 09:05:13 +00:00
feat: Implement OTP-based authentication with Redis, SMS, and email services, including new controllers and providers.
This commit is contained in:
+8
-3
@@ -1,10 +1,15 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { AppController } from './app.controller';
|
||||
import { AppService } from './app.service';
|
||||
import { AuthController } from './auth.controller';
|
||||
import { OtpService } from './otp.service';
|
||||
import { SmsService } from './sms.service';
|
||||
import { MailService } from './mail.service';
|
||||
import { AppRedisModule } from './redis.provider';
|
||||
|
||||
@Module({
|
||||
imports: [],
|
||||
controllers: [AppController],
|
||||
providers: [AppService],
|
||||
imports: [AppRedisModule],
|
||||
controllers: [AuthController],
|
||||
providers: [OtpService,SmsService,MailService],
|
||||
})
|
||||
export class AppModule {}
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
// auth.controller.ts
|
||||
import { Body, Controller, Post } from '@nestjs/common';
|
||||
import { OtpService } from './otp.service';
|
||||
|
||||
@Controller('auth')
|
||||
export class AuthController {
|
||||
constructor(private readonly otpService: OtpService) {}
|
||||
|
||||
@Post('request-otp')
|
||||
request(@Body() body: { identifier: string }) {
|
||||
return this.otpService.requestOtp(body.identifier);
|
||||
}
|
||||
|
||||
@Post('verify-otp')
|
||||
verify(@Body() body: { identifier: string; otp: string }) {
|
||||
return this.otpService.verifyOtp(body.identifier, body.otp);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
// mail.service.ts
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import * as nodemailer from 'nodemailer';
|
||||
|
||||
@Injectable()
|
||||
export class MailService {
|
||||
private transporter = nodemailer.createTransport({
|
||||
host: process.env.SMTP_HOST,
|
||||
port: Number(process.env.SMTP_PORT),
|
||||
secure: true,
|
||||
auth: {
|
||||
user: process.env.SMTP_USER,
|
||||
pass: process.env.SMTP_PASS
|
||||
}
|
||||
});
|
||||
|
||||
async sendOtp(email: string, otp: string) {
|
||||
await this.transporter.sendMail({
|
||||
from: '"Your App" <[email protected]>',
|
||||
to: email,
|
||||
subject: 'Your OTP Code',
|
||||
text: `Your verification code is ${otp}. It expires in 5 minutes.`
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,11 @@
|
||||
import { NestFactory } from '@nestjs/core';
|
||||
import { config } from 'dotenv';
|
||||
import { AppModule } from './app.module';
|
||||
|
||||
config();
|
||||
console.log('API Key:', process.env.AT_API_KEY);
|
||||
console.log('Username:', process.env.AT_USERNAME);
|
||||
|
||||
async function bootstrap() {
|
||||
const app = await NestFactory.create(AppModule);
|
||||
await app.listen(process.env.PORT ?? 3000);
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
// otp.service.ts
|
||||
import { BadRequestException, Injectable, HttpException, HttpStatus } from '@nestjs/common';
|
||||
import { InjectRedis } from '@nestjs-modules/ioredis';
|
||||
import { Redis } from 'ioredis';
|
||||
import { randomInt } from 'crypto';
|
||||
import * as bcrypt from 'bcrypt';
|
||||
import { SmsService } from './sms.service';
|
||||
import { MailService } from './mail.service';
|
||||
|
||||
@Injectable()
|
||||
export class OtpService {
|
||||
constructor(
|
||||
@InjectRedis() private readonly redis: Redis,
|
||||
private readonly smsService: SmsService,
|
||||
private readonly mailService: MailService
|
||||
) {}
|
||||
|
||||
async requestOtp(identifier: string) {
|
||||
const isEmail = this.isEmail(identifier);
|
||||
const isPhone = this.isPhone(identifier);
|
||||
|
||||
if (!isEmail && !isPhone) {
|
||||
throw new BadRequestException('Invalid email or phone number');
|
||||
}
|
||||
|
||||
const cooldownKey = `otp:cooldown:${identifier}`;
|
||||
const isCooling = await this.redis.get(cooldownKey);
|
||||
if (isCooling) {
|
||||
throw new HttpException('Please wait before requesting another OTP', HttpStatus.TOO_MANY_REQUESTS);
|
||||
}
|
||||
|
||||
const otp = randomInt(100000, 999999).toString();
|
||||
const hash = await bcrypt.hash(otp, 10);
|
||||
|
||||
const otpKey = `otp:code:${identifier}`;
|
||||
|
||||
await this.redis.set(otpKey, hash, 'EX', 300);
|
||||
await this.redis.set(cooldownKey, '1', 'EX', 60);
|
||||
|
||||
if (isEmail) {
|
||||
await this.mailService.sendOtp(identifier, otp);
|
||||
} else {
|
||||
await this.smsService.sendOtp(identifier, otp);
|
||||
}
|
||||
|
||||
return { message: 'OTP sent' };
|
||||
}
|
||||
|
||||
async verifyOtp(identifier: string, otp: string) {
|
||||
const key = `otp:code:${identifier}`;
|
||||
const hash = await this.redis.get(key);
|
||||
|
||||
if (!hash) {
|
||||
throw new BadRequestException('OTP expired or invalid');
|
||||
}
|
||||
|
||||
const isValid = await bcrypt.compare(otp, hash);
|
||||
if (!isValid) {
|
||||
throw new BadRequestException('OTP expired or invalid');
|
||||
}
|
||||
|
||||
await this.redis.del(key);
|
||||
|
||||
return { message: 'OTP verified' };
|
||||
}
|
||||
|
||||
private isEmail(value: string): boolean {
|
||||
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value);
|
||||
}
|
||||
|
||||
private isPhone(value: string): boolean {
|
||||
return /^\+2547\d{8}$/.test(value);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
// redis.provider.ts
|
||||
import { Module } from '@nestjs/common';
|
||||
import { RedisModule } from '@nestjs-modules/ioredis';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
RedisModule.forRoot({
|
||||
type: 'single',
|
||||
url: process.env.REDIS_URL
|
||||
})
|
||||
],
|
||||
exports: [RedisModule]
|
||||
})
|
||||
export class AppRedisModule {}
|
||||
@@ -0,0 +1,22 @@
|
||||
// sms.service.ts
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import AfricasTalking from 'africastalking';
|
||||
|
||||
@Injectable()
|
||||
export class SmsService {
|
||||
private client;
|
||||
|
||||
constructor() {
|
||||
this.client = AfricasTalking({
|
||||
apiKey: process.env.AT_API_KEY,
|
||||
username: process.env.AT_USERNAME
|
||||
});
|
||||
}
|
||||
|
||||
async sendOtp(phone: string, otp: string) {
|
||||
await this.client.SMS.send({
|
||||
to: [phone],
|
||||
message: `Your verification code is ${otp}. Expires in 5 minutes.`
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user