You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

99 lines
3.0 KiB

import { HttpException, HttpStatus, Injectable, UnauthorizedException, BadRequestException, NotFoundException } from "@nestjs/common";
import { InjectModel } from "@nestjs/sequelize";
import { User } from "./entities/user.entity";
import * as bcrypt from "bcrypt";
import { JwtService } from "@nestjs/jwt";
import { ConfigService } from "@nestjs/config";
import { CreateUserDto } from "./dto/create-user.dto";
import { LoginUserDto } from "./dto/login-user.dto";
import { UpdateUserDto } from "./dto/update-user.dto";
@Injectable()
export class UsersService {
constructor(
@InjectModel(User) private readonly userModel: typeof User,
private readonly jwtService: JwtService,
private readonly configService: ConfigService,
) {}
// Register method
async register(createUserDto: CreateUserDto): Promise<User> {
try {
createUserDto.password = await bcrypt.hash(createUserDto.password, parseInt(process.env.BCRYPT_SALT_ROUNDS || "10", 10));
const userExists = await this.userModel.findOne({
where: { email: createUserDto.email },
});
if (userExists) {
throw new BadRequestException("Email already exists");
}
const user = await this.userModel.create(createUserDto);
return user;
} catch (error) {
throw new HttpException(`An error occurred: ${error.message}`, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
// Login method
async login(loginUserDto: LoginUserDto): Promise<{ token: string }> {
const user = await this.userModel.findOne({
where: { email: loginUserDto.email },
});
if (!user) {
throw new UnauthorizedException("Invalid email or password");
}
const passwordMatch = await bcrypt.compare(loginUserDto.password, user.password);
if (!passwordMatch) {
throw new UnauthorizedException("Invalid email or password");
}
const token = this.jwtService.sign(
{ id: user.id,role:user.role },
{
secret: this.configService.get<string>("JWT_SECRET"),
expiresIn: this.configService.get<string | number>("JWT_EXPIRES") || "1h",
},
);
return { token };
}
//get information user method
async getProfile(userId: number): Promise<User> {
const user = await this.userModel.findOne({
where: { id: userId },
attributes: { exclude: ["password"] },
});
if (!user) {
throw new Error("User not found");
}
return user;
}
//edit profile user method
async editProfile(userId: number, updateUserDto: UpdateUserDto) {
const user = await this.userModel.findOne({ where: { id: userId } });
if (!user) {
throw new NotFoundException("User not found");
}
if (updateUserDto.password) {
updateUserDto.password = await bcrypt.hash(updateUserDto.password, 10);
}
await user.update(updateUserDto);
return user;
}
//get users list
async findAll(): Promise<User[]> {
try {
return await this.userModel.findAll();
} catch (error) {
throw new Error("An error occurred while fetching users");
}
}
}