import { Injectable, Logger } from '@nestjs/common'; import * as bcrypt from 'bcrypt'; import { LoginPayload, RegisteredUser, User } from 'src/interface/interface'; @Injectable() export class UsersService { private logger: Logger = new Logger(`UsersService`) private users: RegisteredUser[] = []; private idCounter = 1; public async createUser(user: User): Promise { return new Promise(async (resolve, reject) => { const existing = this.users.find(u => u.email === user.email); if (existing) { reject('User already exists'); } else { const hashedPassword = await bcrypt.hash(user.password, 10); const newUser: RegisteredUser = { id: (this.idCounter++).toString(), name: user.name, email: user.email, password: hashedPassword, }; this.users.push(newUser); this.logger.log(`Current users count: ${this.users.length}`) resolve(newUser) } }) } public async findByEmail(email: string): Promise { return this.users.find(user => user.email === email); } public async validateUser(login: LoginPayload): Promise> { return new Promise((resolve, reject) => { this.findByEmail(login.email) .then(user => { if (!user) return reject('No such user'); // console.log('Comparing passwords...'); // console.log('Login.password:', login.password, typeof login.password); // console.log('User.password:', user.password, typeof user.password); if (typeof login.password !== 'string' || typeof user.password !== 'string') { return reject('Password and hash must be strings'); } bcrypt.compare(login.password, user.password, (err, isMatch) => { if (err) return reject(err); if (!isMatch) return reject(`Password doesn't match`); const { password, ...safeUser } = user; resolve(safeUser); }); }) .catch(err => reject(err)); }); } public async findById(id: string): Promise { return this.users.find(user => user.id === id); } public getAllUsers(): Omit[] { return this.users.map(({ password, ...rest }) => rest); } public async updateUser(updatedUser: RegisteredUser): Promise { const index = this.users.findIndex(user => user.id === updatedUser.id); if (index === -1) { throw new Error(`User with ID ${updatedUser.id} not found`); } this.users[index] = updatedUser; this.logger.log(`User ${updatedUser.id} updated successfully`); } }