2024-06-05 14:35:05 -06:00
|
|
|
|
2024-06-11 15:14:05 -06:00
|
|
|
import { HttpException, Inject, Injectable, UnauthorizedException } from '@nestjs/common';
|
2024-06-05 14:35:05 -06:00
|
|
|
import { UsersService } from '../users/users.service';
|
|
|
|
|
import { JwtService } from '@nestjs/jwt';
|
2024-06-11 15:14:05 -06:00
|
|
|
import { registerDto } from './Dto/registerDto.dto';
|
|
|
|
|
import { User } from 'src/users/entities/user.entity';
|
|
|
|
|
import { InjectRepository } from '@nestjs/typeorm';
|
|
|
|
|
import { Repository } from 'typeorm';
|
|
|
|
|
import *as bcrypt from 'bcrypt';
|
|
|
|
|
import { hash } from 'bcrypt';
|
|
|
|
|
import { compare } from 'bcryptjs';
|
|
|
|
|
|
2024-06-05 14:35:05 -06:00
|
|
|
|
|
|
|
|
@Injectable()
|
|
|
|
|
export class AuthService {
|
|
|
|
|
constructor(
|
|
|
|
|
private usersService: UsersService,
|
2024-06-11 15:14:05 -06:00
|
|
|
private jwtService: JwtService,
|
|
|
|
|
@InjectRepository(User) private userRepository: Repository<User>
|
2024-06-05 14:35:05 -06:00
|
|
|
) {}
|
|
|
|
|
|
2024-06-11 15:14:05 -06:00
|
|
|
async register(data: registerDto){
|
|
|
|
|
const{username, password,} = data;
|
|
|
|
|
if(await this.userRepository.findOne({where:{username:data.username}})){
|
|
|
|
|
throw new HttpException("User already exist",403);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const hashedpassword = await hash(password, 10);
|
|
|
|
|
|
|
|
|
|
data = {...data, password:hashedpassword}
|
|
|
|
|
|
|
|
|
|
return this.userRepository.save(
|
|
|
|
|
this.userRepository.create(data)
|
|
|
|
|
)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async signIn(data: registerDto) {
|
|
|
|
|
|
|
|
|
|
const{ password} = data;
|
|
|
|
|
const user = await this.usersService.findOne(data.username);
|
|
|
|
|
|
|
|
|
|
const checkPassword = await compare(password, (await user).password)
|
|
|
|
|
|
|
|
|
|
if (!checkPassword) {
|
2024-06-05 14:35:05 -06:00
|
|
|
throw new UnauthorizedException();
|
|
|
|
|
}
|
2024-06-11 15:14:05 -06:00
|
|
|
const payload = {
|
|
|
|
|
idUser: user.userId,
|
|
|
|
|
username: user.username
|
2024-06-05 14:35:05 -06:00
|
|
|
};
|
2024-06-11 15:14:05 -06:00
|
|
|
const token = this.jwtService.sign(payload);
|
|
|
|
|
|
|
|
|
|
data = {...data},token;
|
|
|
|
|
|
|
|
|
|
return data;
|
2024-06-05 14:35:05 -06:00
|
|
|
}
|
2024-06-07 13:46:18 -06:00
|
|
|
|
|
|
|
|
async create(
|
|
|
|
|
username: string,
|
|
|
|
|
pass: string,
|
|
|
|
|
){
|
|
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async update(
|
|
|
|
|
id,
|
|
|
|
|
updateUserDto
|
|
|
|
|
){
|
|
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async remove(
|
|
|
|
|
id
|
|
|
|
|
){
|
|
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
2024-06-05 14:35:05 -06:00
|
|
|
}
|