Spaces:
Sleeping
Sleeping
File size: 2,148 Bytes
c0f9d1c 13dd365 17cd84b c0f9d1c 13dd365 9a12f24 c114c72 c0f9d1c c114c72 9a12f24 17cd84b c114c72 3cd799a 85b81c4 184b88f 85b81c4 3cd799a c0f9d1c 184b88f c0f9d1c 184b88f c0f9d1c c114c72 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
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;
@Injectable()
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
};
}
}
|