import { Injectable, ConflictException } from '@nestjs/common'; import { JwtService } from '@nestjs/jwt'; import { PrismaService } from '../prisma/prisma.service'; import * as bcrypt from 'bcrypt'; import { CreateUserDto } from '../dto/create-user.dto'; import { ConfigService } from '@nestjs/config'; @Injectable() export class AuthService { constructor( private prisma: PrismaService, private jwtService: JwtService, private configService: ConfigService, ) {} async validateUser(username: string, password: string): Promise { const user = await this.prisma.user.findUnique({ where: { email: username }, }); if (user && (await bcrypt.compare(password, user.password))) { // eslint-disable-next-line @typescript-eslint/no-unused-vars const { password, ...result } = user; return result; } return null; } async login(user: any) { // const payload = { username: user.email, sub: user.id }; // return { // access_token: this.jwtService.sign(payload), // }; const payload = { username: user.username, sub: user.id }; console.log(payload); return { access_token: this.jwtService.sign(payload, { secret: this.configService.get('JWT_SECRET'), }), }; } async createUser( createUserDto: CreateUserDto, isAdmin: boolean = false, ): Promise { const existingUser = await this.prisma.user.findUnique({ where: { email: createUserDto.email }, }); if (existingUser) { throw new ConflictException('Email already exists'); } const hashedPassword = await bcrypt.hash(createUserDto.password, 10); const newUser = await this.prisma.user.create({ data: { email: createUserDto.email, password: hashedPassword, name: createUserDto.name, isAdmin: isAdmin, }, }); // eslint-disable-next-line @typescript-eslint/no-unused-vars const { password, ...result } = newUser; console.log(result); return result; } // async getUserInfo(userId: number) { // return this.prisma.user.findUnique({ // where: { id: userId }, // select: { // id: true, // name: true, // email: true, // isAdmin: true, // }, // }); // } async getUserInfo(userId: number) { if (!userId) { throw new Error('User ID is required'); } return this.prisma.user.findUnique({ where: { id: userId, // Make sure userId is properly passed and converted to number if needed }, select: { id: true, name: true, email: true, isAdmin: true } }); } }