- Add await to all generateToken() calls - Fixes empty token issue in login/register responses - Token now properly includes user role for admin access
409 lines
15 KiB
JavaScript
409 lines
15 KiB
JavaScript
"use strict";
|
|
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
if (k2 === undefined) k2 = k;
|
|
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
}
|
|
Object.defineProperty(o, k2, desc);
|
|
}) : (function(o, m, k, k2) {
|
|
if (k2 === undefined) k2 = k;
|
|
o[k2] = m[k];
|
|
}));
|
|
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
}) : function(o, v) {
|
|
o["default"] = v;
|
|
});
|
|
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
};
|
|
var __importStar = (this && this.__importStar) || (function () {
|
|
var ownKeys = function(o) {
|
|
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
var ar = [];
|
|
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
return ar;
|
|
};
|
|
return ownKeys(o);
|
|
};
|
|
return function (mod) {
|
|
if (mod && mod.__esModule) return mod;
|
|
var result = {};
|
|
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
__setModuleDefault(result, mod);
|
|
return result;
|
|
};
|
|
})();
|
|
var __metadata = (this && this.__metadata) || function (k, v) {
|
|
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
};
|
|
var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
return function (target, key) { decorator(target, key, paramIndex); }
|
|
};
|
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
};
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.AuthService = void 0;
|
|
const common_1 = require("@nestjs/common");
|
|
const jwt_1 = require("@nestjs/jwt");
|
|
const prisma_service_1 = require("../prisma/prisma.service");
|
|
const otp_service_1 = require("../otp/otp.service");
|
|
const bcrypt = __importStar(require("bcrypt"));
|
|
const fs = __importStar(require("fs"));
|
|
const path = __importStar(require("path"));
|
|
const axios_1 = __importDefault(require("axios"));
|
|
let AuthService = class AuthService {
|
|
prisma;
|
|
jwtService;
|
|
otpService;
|
|
constructor(prisma, jwtService, otpService) {
|
|
this.prisma = prisma;
|
|
this.jwtService = jwtService;
|
|
this.otpService = otpService;
|
|
}
|
|
async register(email, password, name) {
|
|
const existing = await this.prisma.user.findUnique({ where: { email } });
|
|
if (existing) {
|
|
throw new common_1.ConflictException('Email already registered');
|
|
}
|
|
const passwordHash = await bcrypt.hash(password, 10);
|
|
const user = await this.prisma.user.create({
|
|
data: {
|
|
email,
|
|
passwordHash,
|
|
name,
|
|
emailVerified: false,
|
|
},
|
|
});
|
|
const token = await this.generateToken(user.id, user.email);
|
|
return {
|
|
user: {
|
|
id: user.id,
|
|
email: user.email,
|
|
name: user.name,
|
|
avatarUrl: user.avatarUrl,
|
|
emailVerified: user.emailVerified,
|
|
},
|
|
token,
|
|
};
|
|
}
|
|
async login(email, password) {
|
|
const user = await this.prisma.user.findUnique({
|
|
where: { email },
|
|
select: {
|
|
id: true,
|
|
email: true,
|
|
passwordHash: true,
|
|
name: true,
|
|
avatarUrl: true,
|
|
emailVerified: true,
|
|
otpEmailEnabled: true,
|
|
otpWhatsappEnabled: true,
|
|
otpTotpEnabled: true,
|
|
},
|
|
});
|
|
if (!user || !user.passwordHash) {
|
|
throw new common_1.UnauthorizedException('Invalid credentials');
|
|
}
|
|
const isValid = await bcrypt.compare(password, user.passwordHash);
|
|
if (!isValid) {
|
|
throw new common_1.UnauthorizedException('Invalid credentials');
|
|
}
|
|
const requiresOtp = user.otpEmailEnabled || user.otpWhatsappEnabled || user.otpTotpEnabled;
|
|
if (requiresOtp) {
|
|
if (user.otpEmailEnabled) {
|
|
try {
|
|
await this.otpService.sendEmailOtp(user.id);
|
|
}
|
|
catch (error) {
|
|
console.error('Failed to send email OTP during login:', error);
|
|
}
|
|
}
|
|
if (user.otpWhatsappEnabled) {
|
|
try {
|
|
await this.otpService.sendWhatsappOtp(user.id, 'live');
|
|
}
|
|
catch (error) {
|
|
console.error('Failed to send WhatsApp OTP during login:', error);
|
|
}
|
|
}
|
|
return {
|
|
requiresOtp: true,
|
|
availableMethods: {
|
|
email: user.otpEmailEnabled,
|
|
whatsapp: user.otpWhatsappEnabled,
|
|
totp: user.otpTotpEnabled,
|
|
},
|
|
tempToken: this.generateTempToken(user.id, user.email),
|
|
};
|
|
}
|
|
const token = await this.generateToken(user.id, user.email);
|
|
return {
|
|
user: {
|
|
id: user.id,
|
|
email: user.email,
|
|
name: user.name,
|
|
avatarUrl: user.avatarUrl,
|
|
emailVerified: user.emailVerified,
|
|
},
|
|
token,
|
|
};
|
|
}
|
|
async googleLogin(googleProfile) {
|
|
let user = await this.prisma.user.findUnique({
|
|
where: { email: googleProfile.email },
|
|
});
|
|
if (!user) {
|
|
user = await this.prisma.user.create({
|
|
data: {
|
|
email: googleProfile.email,
|
|
name: googleProfile.name,
|
|
avatarUrl: googleProfile.avatarUrl,
|
|
emailVerified: true,
|
|
authAccounts: {
|
|
create: {
|
|
provider: 'google',
|
|
issuer: 'google.com',
|
|
subject: googleProfile.googleId,
|
|
},
|
|
},
|
|
},
|
|
});
|
|
}
|
|
else {
|
|
const existingAuth = await this.prisma.authAccount.findUnique({
|
|
where: {
|
|
issuer_subject: {
|
|
issuer: 'google.com',
|
|
subject: googleProfile.googleId,
|
|
},
|
|
},
|
|
});
|
|
if (!existingAuth) {
|
|
await this.prisma.authAccount.create({
|
|
data: {
|
|
userId: user.id,
|
|
provider: 'google',
|
|
issuer: 'google.com',
|
|
subject: googleProfile.googleId,
|
|
},
|
|
});
|
|
}
|
|
console.log('Updating user with Google profile:', {
|
|
name: googleProfile.name,
|
|
avatarUrl: googleProfile.avatarUrl,
|
|
});
|
|
let avatarUrl = user.avatarUrl;
|
|
if (googleProfile.avatarUrl) {
|
|
try {
|
|
avatarUrl = await this.downloadAndStoreAvatar(googleProfile.avatarUrl, user.id);
|
|
}
|
|
catch (error) {
|
|
console.error('Failed to download avatar:', error);
|
|
avatarUrl = googleProfile.avatarUrl;
|
|
}
|
|
}
|
|
user = await this.prisma.user.update({
|
|
where: { id: user.id },
|
|
data: {
|
|
name: googleProfile.name || user.name,
|
|
avatarUrl: avatarUrl || user.avatarUrl,
|
|
emailVerified: true,
|
|
},
|
|
});
|
|
console.log('User updated, avatar:', user.avatarUrl);
|
|
}
|
|
const requiresOtp = user.otpEmailEnabled || user.otpWhatsappEnabled || user.otpTotpEnabled;
|
|
if (requiresOtp) {
|
|
if (user.otpEmailEnabled) {
|
|
try {
|
|
await this.otpService.sendEmailOtp(user.id);
|
|
}
|
|
catch (error) {
|
|
console.error('Failed to send email OTP during Google login:', error);
|
|
}
|
|
}
|
|
if (user.otpWhatsappEnabled) {
|
|
try {
|
|
await this.otpService.sendWhatsappOtp(user.id, 'live');
|
|
}
|
|
catch (error) {
|
|
console.error('Failed to send WhatsApp OTP during Google login:', error);
|
|
}
|
|
}
|
|
return {
|
|
requiresOtp: true,
|
|
availableMethods: {
|
|
email: user.otpEmailEnabled,
|
|
whatsapp: user.otpWhatsappEnabled,
|
|
totp: user.otpTotpEnabled,
|
|
},
|
|
tempToken: this.generateTempToken(user.id, user.email),
|
|
};
|
|
}
|
|
const token = await this.generateToken(user.id, user.email);
|
|
return {
|
|
user: {
|
|
id: user.id,
|
|
email: user.email,
|
|
name: user.name,
|
|
avatarUrl: user.avatarUrl,
|
|
emailVerified: user.emailVerified,
|
|
},
|
|
token,
|
|
};
|
|
}
|
|
async verifyOtpAndLogin(tempToken, otpCode, method) {
|
|
let payload;
|
|
try {
|
|
payload = this.jwtService.verify(tempToken);
|
|
}
|
|
catch {
|
|
throw new common_1.UnauthorizedException('Invalid or expired token');
|
|
}
|
|
if (!payload.temp) {
|
|
throw new common_1.UnauthorizedException('Invalid token type');
|
|
}
|
|
const userId = payload.userId || payload.sub;
|
|
const email = payload.email;
|
|
if (!userId || !email) {
|
|
throw new common_1.UnauthorizedException('Invalid token payload');
|
|
}
|
|
const user = await this.prisma.user.findUnique({
|
|
where: { id: userId },
|
|
});
|
|
if (!user) {
|
|
throw new common_1.UnauthorizedException('User not found');
|
|
}
|
|
if (method === 'email') {
|
|
const isValid = this.otpService.verifyEmailOtpForLogin(userId, otpCode);
|
|
if (!isValid) {
|
|
throw new common_1.UnauthorizedException('Invalid or expired email OTP code');
|
|
}
|
|
}
|
|
else if (method === 'whatsapp') {
|
|
const isValid = this.otpService.verifyWhatsappOtpForLogin(userId, otpCode);
|
|
if (!isValid) {
|
|
throw new common_1.UnauthorizedException('Invalid or expired WhatsApp OTP code');
|
|
}
|
|
}
|
|
else if (method === 'totp') {
|
|
if (!user.otpTotpSecret) {
|
|
throw new common_1.UnauthorizedException('TOTP not set up');
|
|
}
|
|
const { authenticator } = await import('otplib');
|
|
const isValid = authenticator.verify({
|
|
token: otpCode,
|
|
secret: user.otpTotpSecret,
|
|
});
|
|
if (!isValid) {
|
|
throw new common_1.UnauthorizedException('Invalid TOTP code');
|
|
}
|
|
}
|
|
const token = await this.generateToken(userId, email);
|
|
return {
|
|
user: {
|
|
id: user.id,
|
|
email: user.email,
|
|
name: user.name,
|
|
avatarUrl: user.avatarUrl,
|
|
emailVerified: user.emailVerified,
|
|
},
|
|
token,
|
|
};
|
|
}
|
|
async generateToken(userId, email) {
|
|
const user = await this.prisma.user.findUnique({
|
|
where: { id: userId },
|
|
select: { role: true },
|
|
});
|
|
return this.jwtService.sign({
|
|
sub: userId,
|
|
email,
|
|
role: user?.role || 'user',
|
|
});
|
|
}
|
|
generateTempToken(userId, email) {
|
|
return this.jwtService.sign({ userId, email, temp: true }, { expiresIn: '5m' });
|
|
}
|
|
async getUserProfile(userId) {
|
|
const user = await this.prisma.user.findUnique({
|
|
where: { id: userId },
|
|
select: {
|
|
id: true,
|
|
email: true,
|
|
name: true,
|
|
avatarUrl: true,
|
|
emailVerified: true,
|
|
},
|
|
});
|
|
if (!user) {
|
|
throw new common_1.UnauthorizedException('User not found');
|
|
}
|
|
return user;
|
|
}
|
|
async changePassword(userId, currentPassword, newPassword, isSettingPassword) {
|
|
const user = await this.prisma.user.findUnique({
|
|
where: { id: userId },
|
|
select: { passwordHash: true },
|
|
});
|
|
if (!user) {
|
|
throw new common_1.BadRequestException('User not found');
|
|
}
|
|
if (isSettingPassword && !user.passwordHash) {
|
|
const newPasswordHash = await bcrypt.hash(newPassword, 10);
|
|
await this.prisma.user.update({
|
|
where: { id: userId },
|
|
data: { passwordHash: newPasswordHash },
|
|
});
|
|
return { message: 'Password set successfully' };
|
|
}
|
|
if (!user.passwordHash) {
|
|
throw new common_1.BadRequestException('Cannot change password for this account');
|
|
}
|
|
const isValid = await bcrypt.compare(currentPassword, user.passwordHash);
|
|
if (!isValid) {
|
|
throw new common_1.UnauthorizedException('Current password is incorrect');
|
|
}
|
|
const newPasswordHash = await bcrypt.hash(newPassword, 10);
|
|
await this.prisma.user.update({
|
|
where: { id: userId },
|
|
data: { passwordHash: newPasswordHash },
|
|
});
|
|
return { message: 'Password changed successfully' };
|
|
}
|
|
async downloadAndStoreAvatar(avatarUrl, userId) {
|
|
try {
|
|
const uploadsDir = path.join(process.cwd(), 'public', 'avatars');
|
|
if (!fs.existsSync(uploadsDir)) {
|
|
fs.mkdirSync(uploadsDir, { recursive: true });
|
|
}
|
|
const response = await axios_1.default.get(avatarUrl, {
|
|
responseType: 'arraybuffer',
|
|
});
|
|
const ext = 'jpg';
|
|
const filename = `${userId}.${ext}`;
|
|
const filepath = path.join(uploadsDir, filename);
|
|
fs.writeFileSync(filepath, response.data);
|
|
return `/avatars/${filename}`;
|
|
}
|
|
catch (error) {
|
|
console.error('Error downloading avatar:', error);
|
|
throw error;
|
|
}
|
|
}
|
|
};
|
|
exports.AuthService = AuthService;
|
|
exports.AuthService = AuthService = __decorate([
|
|
(0, common_1.Injectable)(),
|
|
__param(2, (0, common_1.Inject)((0, common_1.forwardRef)(() => otp_service_1.OtpService))),
|
|
__metadata("design:paramtypes", [prisma_service_1.PrismaService,
|
|
jwt_1.JwtService,
|
|
otp_service_1.OtpService])
|
|
], AuthService);
|
|
//# sourceMappingURL=auth.service.js.map
|