Spaces:
Sleeping
Sleeping
import { Body, forwardRef, Inject, Injectable, NotFoundException } from '@nestjs/common'; | |
import { UserEntity } from '../../entities/user.entity.js'; | |
import { SignUpDto } from '../authentication/dto/sign-up.dto.js'; | |
import { UpdateUserDto } from './dto/update-user-dto.js'; | |
import { ValidateService } from '../../validate/validate.service.js'; | |
import * as bcrypt from 'bcrypt'; | |
import { JwtService } from '@nestjs/jwt'; | |
export type User = any; | |
() | |
export class UserService { | |
constructor( | |
private validateService: ValidateService, | |
private jwtService: JwtService, | |
) {} | |
async findOne(username: string): Promise<UserEntity | undefined> { | |
return UserEntity.findOne({ where: { full_name: username } }); | |
} | |
async create(signUpDto: SignUpDto): Promise<UserEntity | undefined>{ | |
return UserEntity.create({ | |
full_name: signUpDto.full_name, | |
phone_number: signUpDto.phone_number, | |
email: signUpDto.email, | |
hash_password: signUpDto.password | |
}) | |
} | |
async save(userEntity: UserEntity): Promise<UserEntity | undefined>{ | |
return UserEntity.save(userEntity); | |
} | |
async findOneByField(field: string, value: any): Promise<UserEntity | undefined> { | |
return UserEntity.findOne({ | |
where: { [field]: value } | |
}); | |
} | |
async updateUserById(userId: string, updateUserDto: UpdateUserDto){ | |
await this.validateService.checkExistField('email', updateUserDto.email); | |
await this.validateService.checkExistField('phone_number', updateUserDto.phone_number); | |
const user = await UserEntity.findOne({ | |
where: { id: userId } | |
}); | |
if (!user) { | |
throw new NotFoundException(`User with ID ${userId} not found`); | |
} | |
Object.assign(user, updateUserDto); | |
if (updateUserDto.hash_password) { | |
const saltRounds = 10; | |
user.hash_password = await bcrypt.hash(updateUserDto.hash_password, saltRounds); // Mã hóa mật khẩu | |
} | |
await UserEntity.save(user); | |
const payload = { sub: user.id, username: user.full_name, roles: user.role }; | |
const token = await this.jwtService.signAsync(payload) | |
return { | |
access_token: token | |
}; | |
} | |
} | |