81 lines
2.5 KiB
TypeScript
81 lines
2.5 KiB
TypeScript
import { Injectable, BadRequestException } from '@nestjs/common';
|
|
import { JwtService } from '@nestjs/jwt';
|
|
import { PrismaService } from '../prisma/prisma.service';
|
|
import { RedisService } from '../redis/redis.service';
|
|
import { SendOtpDto } from './dto/send-otp.dto';
|
|
import { VerifyOtpDto } from './dto/verify-otp.dto';
|
|
|
|
@Injectable()
|
|
export class AuthService {
|
|
constructor(
|
|
private prisma: PrismaService,
|
|
private jwtService: JwtService,
|
|
private redisService: RedisService,
|
|
) {}
|
|
|
|
async sendOtp(sendOtpDto: SendOtpDto) {
|
|
const { phoneNumber } = sendOtpDto;
|
|
|
|
const code = Math.floor(10000 + Math.random() * 90000).toString();
|
|
console.log(`[Mock SMS] Sending OTP ${code} to ${phoneNumber}`);
|
|
|
|
await this.redisService.set(`otp:${phoneNumber}`, code, 120);
|
|
|
|
return { success: true, message: 'کد تایید ارسال شد', code };
|
|
}
|
|
|
|
async verifyOtp(verifyOtpDto: VerifyOtpDto) {
|
|
const { phoneNumber, code } = verifyOtpDto;
|
|
|
|
const savedCode = await this.redisService.get(`otp:${phoneNumber}`);
|
|
|
|
if (!savedCode) {
|
|
throw new BadRequestException({ message: 'کد تایید منقضی شده است', error: 'OTP_EXPIRED' });
|
|
}
|
|
|
|
if (savedCode !== code) {
|
|
throw new BadRequestException({ message: 'کد تایید اشتباه است', error: 'OTP_INVALID' });
|
|
}
|
|
|
|
await this.redisService.del(`otp:${phoneNumber}`);
|
|
|
|
let user = await this.prisma.user.findUnique({ where: { mobile: phoneNumber } });
|
|
|
|
if (!user) {
|
|
user = await this.prisma.user.create({
|
|
data: {
|
|
mobile: phoneNumber,
|
|
firstName: 'کاربر',
|
|
lastName: 'جدید',
|
|
email: `${phoneNumber}@temp.local`,
|
|
},
|
|
});
|
|
}
|
|
|
|
const payload = { sub: user.id, phoneNumber: user.mobile };
|
|
const accessToken = this.jwtService.sign(payload);
|
|
|
|
return {
|
|
success: true,
|
|
data: {
|
|
user,
|
|
accessToken,
|
|
},
|
|
};
|
|
}
|
|
|
|
async adminLogin(body: any) {
|
|
if (body.email === 'admin@canina-iran.com' && body.password === 'admin123') {
|
|
const payload = { sub: '12345678-1234-1234-1234-123456789012', email: body.email, role: 'Admin' };
|
|
return {
|
|
success: true,
|
|
data: {
|
|
user: { id: '12345678-1234-1234-1234-123456789012', email: body.email, role: 'Admin' },
|
|
accessToken: this.jwtService.sign(payload),
|
|
},
|
|
};
|
|
}
|
|
throw new BadRequestException({ message: 'ایمیل یا رمز عبور اشتباه است', error: 'INVALID_CREDENTIALS' });
|
|
}
|
|
}
|