Files
canina/backend/src/auth/auth.service.ts
T

543 lines
17 KiB
TypeScript

import {
Injectable,
BadRequestException,
UnauthorizedException,
HttpException,
HttpStatus,
} 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";
import { SmsService } from "../common/services/sms.service";
import * as bcrypt from "bcryptjs";
import * as crypto from "crypto";
import { normalizeMobile } from "../common/utils/phone.utils";
import { assertPrincipalActive } from "./stage-test-principal";
import { getJwtRefreshSecret } from "./auth.constants";
export class RegisterInput {
firstName!: string;
lastName!: string;
email?: string;
mobile!: string;
password?: string;
}
export class LoginInput {
mobile!: string;
password?: string;
}
export class AdminLoginInput {
email!: string;
password?: string;
username?: string;
}
@Injectable()
export class AuthService {
constructor(
private prisma: PrismaService,
private jwtService: JwtService,
private redisService: RedisService,
private smsService: SmsService,
) {}
private async generateTokens(payload: Record<string, any>) {
const accessToken = this.jwtService.sign(payload);
// Refresh token with 30-day lifetime signed by refresh secret
const refreshSecret = getJwtRefreshSecret();
const tokenId = crypto.randomUUID();
const refreshPayload = { ...payload, jti: tokenId };
const refreshToken = this.jwtService.sign(refreshPayload, {
secret: refreshSecret,
expiresIn: "30d",
});
// Store active refresh token in Redis (30 days TTL = 2,592,000s)
await this.redisService.set(
`refresh_token:${payload.sub}:${tokenId}`,
"1",
30 * 24 * 3600,
);
return { accessToken, refreshToken };
}
async sendOtp(sendOtpDto: SendOtpDto) {
const phoneNumber = normalizeMobile(sendOtpDto.phoneNumber);
// 1. Check 60-second cooldown per phone number
const cooldownKey = `otp:cooldown:${phoneNumber}`;
const inCooldown = await this.redisService.get(cooldownKey);
if (inCooldown) {
const remainingTtl = await this.redisService.ttl(cooldownKey);
throw new HttpException(
{
success: false,
statusCode: HttpStatus.TOO_MANY_REQUESTS,
message: `لطفاً ${Math.max(1, remainingTtl)} ثانیه دیگر مجدداً تلاش کنید.`,
code: "OTP_COOLDOWN",
remainingSeconds: Math.max(1, remainingTtl),
},
HttpStatus.TOO_MANY_REQUESTS,
);
}
// 2. Hourly rate limit: Max 5 OTP requests per hour per phone
const hourKey = `otp:rate:hour:${phoneNumber}`;
const hourlyRequests = await this.redisService.incr(hourKey, 3600);
if (hourlyRequests > 5) {
throw new HttpException(
{
success: false,
statusCode: HttpStatus.TOO_MANY_REQUESTS,
message:
"تعداد دفعات ارسال پیامک در یک ساعت بیش از حد مجاز است. لطفاً ساعتی دیگر تلاش کنید.",
code: "HOURLY_RATE_LIMIT_EXCEEDED",
},
HttpStatus.TOO_MANY_REQUESTS,
);
}
// 3. Daily rate limit: Max 10 OTP requests per 24 hours per phone
const dayKey = `otp:rate:day:${phoneNumber}`;
const dailyRequests = await this.redisService.incr(dayKey, 86400);
if (dailyRequests > 10) {
throw new HttpException(
{
success: false,
statusCode: HttpStatus.TOO_MANY_REQUESTS,
message:
"سقف ارسال روزانه پیامک برای این شماره تکمیل شده است. لطفاً فردا مجدداً تلاش کنید.",
code: "DAILY_RATE_LIMIT_EXCEEDED",
},
HttpStatus.TOO_MANY_REQUESTS,
);
}
const code = crypto.randomInt(10000, 100000).toString();
// Store OTP for 120 seconds
await this.redisService.set(`otp:${phoneNumber}`, code, 120);
// Dispatch OTP via MeliPayamak Pattern SMS
const smsSent = await this.smsService.sendOtp(phoneNumber, code);
if (!smsSent) {
// Remove OTP from Redis if SMS failed to avoid phantom codes
await this.redisService.del(`otp:${phoneNumber}`);
throw new BadRequestException({
message:
"ارسال پیامک با خطا مواجه شد. لطفاً چند لحظه دیگر دوباره تلاش کنید.",
error: "SMS_DELIVERY_FAILED",
});
}
// Set 60-second cooldown lock
await this.redisService.set(cooldownKey, "1", 60);
return {
success: true,
message: "کد تایید با موفقیت به شماره شما پیامک شد.",
expiresIn: 120,
cooldown: 60,
};
}
async verifyOtp(verifyOtpDto: VerifyOtpDto) {
const phoneNumber = normalizeMobile(verifyOtpDto.phoneNumber);
const code = String(verifyOtpDto.code).trim();
const attemptsKey = `otp_attempts:${phoneNumber}`;
// SEC-007: Check failed attempts to prevent brute-forcing OTP
const currentAttempts = await this.redisService.get(attemptsKey);
if (currentAttempts && Number(currentAttempts) >= 5) {
await this.redisService.del(`otp:${phoneNumber}`);
throw new BadRequestException({
message:
"تعداد تلاش‌های ناموفق بیش از حد مجاز است. لطفاً پس از چند دقیقه دوباره کد جدید دریافت کنید.",
error: "TOO_MANY_OTP_ATTEMPTS",
});
}
const savedCode = await this.redisService.get(`otp:${phoneNumber}`);
if (!savedCode || savedCode !== code) {
const attempts = await this.redisService.incr(attemptsKey, 300);
const remaining = Math.max(0, 5 - attempts);
if (remaining === 0) {
await this.redisService.del(`otp:${phoneNumber}`);
throw new BadRequestException({
message:
"کد تایید به دلیل ۵ بار تلاش ناموفق باطل شد. لطفاً کد جدید دریافت کنید.",
error: "TOO_MANY_OTP_ATTEMPTS",
});
}
throw new BadRequestException({
message: `کد وارد شده اشتباه یا منقضی شده است. (${remaining} تلاش باقی‌مانده)`,
error: "INVALID_OTP",
});
}
// Success - clear OTP and attempts
await this.redisService.del(`otp:${phoneNumber}`);
await this.redisService.del(attemptsKey);
let user = await this.prisma.user.findUnique({
where: { mobile: phoneNumber },
});
if (!user) {
user = await this.prisma.user.create({
data: {
mobile: phoneNumber,
firstName: "کاربر",
lastName: "جدید",
},
});
}
assertPrincipalActive(user);
const payload = { sub: user.id, phoneNumber: user.mobile, role: user.role, ...(user.stageTestSession ? {stageTestSession:user.stageTestSession, stageTestGeneration:user.stageTestGeneration} : {}) };
const tokens = await this.generateTokens(payload);
const { password: _p, ...safeUser } = user;
return {
success: true,
data: {
user: safeUser,
accessToken: tokens.accessToken,
refreshToken: tokens.refreshToken,
},
};
}
async register(registerDto: RegisterInput) {
const firstName = registerDto.firstName.trim();
const lastName = registerDto.lastName.trim();
const mobile = normalizeMobile(registerDto.mobile);
const email = registerDto.email
? registerDto.email.trim().toLowerCase()
: null;
const password = registerDto.password?.trim();
const existingUser = await this.prisma.user.findUnique({
where: { mobile },
});
if (existingUser) {
throw new BadRequestException({
message: "کاربری با این شماره موبایل قبلا ثبت نام کرده است",
error: "MOBILE_EXISTS",
});
}
if (email) {
const existingEmail = await this.prisma.user.findUnique({
where: { email },
});
if (existingEmail) {
throw new BadRequestException({
message: "کاربری با این ایمیل قبلا ثبت نام کرده است",
error: "EMAIL_EXISTS",
});
}
}
const hashedPassword = password ? await bcrypt.hash(password, 10) : "";
const user = await this.prisma.user.create({
data: {
firstName,
lastName,
email,
mobile,
password: hashedPassword,
},
});
assertPrincipalActive(user);
const payload = { sub: user.id, phoneNumber: user.mobile, role: user.role, ...(user.stageTestSession ? {stageTestSession:user.stageTestSession, stageTestGeneration:user.stageTestGeneration} : {}) };
const tokens = await this.generateTokens(payload);
const { password: _p, ...safeUser } = user;
return {
success: true,
data: {
user: safeUser,
accessToken: tokens.accessToken,
refreshToken: tokens.refreshToken,
},
};
}
async login(loginDto: LoginInput) {
const mobile = normalizeMobile(loginDto.mobile);
const password = loginDto.password ? loginDto.password.trim() : "";
const user = await this.prisma.user.findUnique({ where: { mobile } });
if (!user) {
throw new BadRequestException({
message: "نام کاربری یا رمز عبور اشتباه است",
error: "INVALID_CREDENTIALS",
});
}
if (!user.password) {
throw new BadRequestException({
message: "شما با رمز عبور ثبت نام نکرده‌اید. لطفاً با موبایل وارد شوید",
error: "NO_PASSWORD",
});
}
const isMatch = password
? await bcrypt.compare(password, user.password)
: false;
if (!isMatch) {
throw new BadRequestException({
message: "نام کاربری یا رمز عبور اشتباه است",
error: "INVALID_CREDENTIALS",
});
}
assertPrincipalActive(user);
const payload = { sub: user.id, phoneNumber: user.mobile, role: user.role, ...(user.stageTestSession ? {stageTestSession:user.stageTestSession, stageTestGeneration:user.stageTestGeneration} : {}) };
const tokens = await this.generateTokens(payload);
const { password: _pw, ...safeUser } = user;
return {
success: true,
data: {
user: safeUser,
accessToken: tokens.accessToken,
refreshToken: tokens.refreshToken,
},
};
}
async adminLogin(body: AdminLoginInput) {
// First check database for user with role 'Admin' or 'SUPER_ADMIN'
const dbAdmin = await this.prisma.user.findFirst({
where: {
email: body.email,
role: { in: ["Admin", "SUPER_ADMIN", "ADMIN"] },
},
});
if (dbAdmin && dbAdmin.password && body.password) {
const isMatch = await bcrypt.compare(body.password, dbAdmin.password);
if (isMatch) {
assertPrincipalActive(dbAdmin);
const payload = {
sub: dbAdmin.id,
email: dbAdmin.email,
role: dbAdmin.role,
...(dbAdmin.stageTestSession ? {stageTestSession:dbAdmin.stageTestSession, stageTestGeneration:dbAdmin.stageTestGeneration} : {}),
};
const tokens = await this.generateTokens(payload);
const { password: _p, ...safeUser } = dbAdmin;
return {
success: true,
data: {
user: safeUser,
accessToken: tokens.accessToken,
refreshToken: tokens.refreshToken,
},
};
}
}
// In production, fallback credentials MUST NOT be accepted
if (process.env.NODE_ENV === "production") {
throw new BadRequestException({
message: "ایمیل یا رمز عبور مدیریت اشتباه است",
error: "INVALID_ADMIN_CREDENTIALS",
});
}
// Fallback to validated environment variable credentials only in non-production
const adminEmail = process.env.ADMIN_EMAIL;
const adminPassword = process.env.ADMIN_PASSWORD;
if (
adminEmail &&
adminPassword &&
adminPassword.length >= 8 &&
body.email &&
body.password
) {
const emailMatches =
body.email.length === adminEmail.length &&
crypto.timingSafeEqual(
Buffer.from(crypto.createHash("sha256").update(body.email).digest()),
Buffer.from(crypto.createHash("sha256").update(adminEmail).digest()),
);
const passwordMatches = crypto.timingSafeEqual(
Buffer.from(crypto.createHash("sha256").update(body.password).digest()),
Buffer.from(crypto.createHash("sha256").update(adminPassword).digest()),
);
if (emailMatches && passwordMatches) {
const payload = {
sub: "12345678-1234-1234-1234-123456789012",
email: adminEmail,
role: "Admin",
};
const tokens = await this.generateTokens(payload);
return {
success: true,
data: {
user: {
id: "12345678-1234-1234-1234-123456789012",
email: body.email,
role: "Admin",
},
accessToken: tokens.accessToken,
refreshToken: tokens.refreshToken,
},
};
}
}
throw new BadRequestException({
message: "ایمیل یا رمز عبور مدیریت اشتباه است",
error: "INVALID_ADMIN_CREDENTIALS",
});
}
async refreshToken(rawRefreshToken: string) {
if (!rawRefreshToken) {
throw new UnauthorizedException("توکن تازه‌سازی یافت نشد");
}
let decoded: any;
try {
decoded = this.jwtService.verify(rawRefreshToken, {
secret: getJwtRefreshSecret(),
});
} catch {
throw new UnauthorizedException(
"توکن تازه‌سازی نامعتبر یا منقضی شده است",
);
}
const userId = decoded.sub;
const tokenId = decoded.jti;
if (!userId || !tokenId) {
throw new UnauthorizedException("اطلاعات توکن نامعتبر است");
}
// Check if token exists in Redis
const tokenKey = `refresh_token:${userId}:${tokenId}`;
const tokenValid = await this.redisService.get(tokenKey);
if (!tokenValid) {
throw new UnauthorizedException(
"توکن تازه‌سازی باطل شده است. لطفاً مجدداً وارد شوید",
);
}
// Invalidate old token (Rotation)
await this.redisService.del(tokenKey);
let userPayload: Record<string, any>;
let safeUser: any;
const user = await this.prisma.user.findUnique({ where: { id: userId } });
if (user) {
assertPrincipalActive(user);
if (user.stageTestSession && (!user.stageTestGeneration || decoded.stageTestGeneration !== user.stageTestGeneration || decoded.stageTestSession !== user.stageTestSession)) throw new UnauthorizedException("Stage session revoked");
userPayload = {
sub: user.id,
email: user.email,
phoneNumber: user.mobile,
role: user.role,
...(user.stageTestSession ? {stageTestSession:user.stageTestSession, stageTestGeneration:user.stageTestGeneration} : {}),
};
const { password: _p, ...restUser } = user;
safeUser = restUser;
} else if (userId === "12345678-1234-1234-1234-123456789012") {
if (process.env.NODE_ENV === "production") {
throw new UnauthorizedException("حساب کاربری مدیریت معتبر نیست");
}
userPayload = {
sub: userId,
email: decoded.email,
role: "Admin",
};
safeUser = {
id: userId,
email: decoded.email,
role: "Admin",
};
} else {
throw new UnauthorizedException("کاربر یافت نشد");
}
// Issue new pair of tokens
const tokens = await this.generateTokens(userPayload);
return {
success: true,
data: {
user: safeUser,
accessToken: tokens.accessToken,
refreshToken: tokens.refreshToken,
},
};
}
async refresh(user: {
id: string;
email?: string;
role?: string;
mobile?: string;
stageTestSession?: string | null;
stageTestGeneration?: string | null;
}) {
const payload = {
sub: user.id,
email: user.email,
role: user.role,
phoneNumber: user.mobile,
...(user.stageTestSession ? {stageTestSession:user.stageTestSession, stageTestGeneration:user.stageTestGeneration} : {}),
};
const tokens = await this.generateTokens(payload);
return {
success: true,
data: {
user,
accessToken: tokens.accessToken,
refreshToken: tokens.refreshToken,
},
};
}
async blacklistToken(token: string) {
try {
const decoded: any = this.jwtService.decode(token);
let ttl = 15 * 60; // 15 minutes default for access token
if (decoded && decoded.exp) {
const remaining = decoded.exp - Math.floor(Date.now() / 1000);
if (remaining > 0) {
ttl = remaining;
}
}
await this.redisService.set(`bl_token:${token}`, "1", ttl);
// If token payload has jti and sub, also invalidate the refresh token in Redis
if (decoded && decoded.sub && decoded.jti) {
await this.redisService.del(
`refresh_token:${decoded.sub}:${decoded.jti}`,
);
}
} catch {
await this.redisService.set(`bl_token:${token}`, "1", 15 * 60);
}
}
}