forked from CIDWA/cedetec_api_nest
63 lines
1.9 KiB
TypeScript
63 lines
1.9 KiB
TypeScript
import { HttpException, Injectable } from '@nestjs/common';
|
|
import { UsuarioService } from 'src/usuario/usuario.service';
|
|
import { JwtService } from '@nestjs/jwt';
|
|
import * as bcrypt from 'bcrypt';
|
|
import { RegistrarUsuarioDto } from './dto/registrarUsuario.dto';
|
|
import { hash } from 'bcrypt';
|
|
import { InjectRepository } from '@nestjs/typeorm';
|
|
import { Usuario } from 'src/usuario/usuario.entity';
|
|
import { Repository } from 'typeorm';
|
|
import { LoginUsuarioDto } from './dto/loginUsuario.dto';
|
|
import { compare } from 'bcrypt';
|
|
import { jwtConstants } from './jwt.constants';
|
|
|
|
@Injectable()
|
|
export class AuthService {
|
|
constructor(
|
|
private jwtService: JwtService,
|
|
private readonly usuarioService: UsuarioService,
|
|
@InjectRepository(Usuario) private usuarioRepository: Repository<Usuario>,
|
|
) {}
|
|
|
|
async registrar(registrarUsuario: RegistrarUsuarioDto) {
|
|
|
|
const { email, password } = registrarUsuario;
|
|
|
|
const plainToHash = await hash(password, 10);
|
|
|
|
if (await this.usuarioRepository.findOne({ where: { email } }))
|
|
throw new HttpException('usuario existe', 403);
|
|
|
|
registrarUsuario = { ...registrarUsuario, password: plainToHash };
|
|
|
|
return this.usuarioRepository.save(
|
|
this.usuarioRepository.create(registrarUsuario),
|
|
);
|
|
}
|
|
|
|
|
|
async login(loginUsuario: LoginUsuarioDto) {
|
|
const { email, password } = loginUsuario;
|
|
|
|
const usuario = await this.usuarioRepository.findOne({ where: { email } });
|
|
|
|
if (!usuario) throw new HttpException('Usuario no encontrado', 404);
|
|
|
|
const checkPassword = await compare(password, (await usuario).password);
|
|
|
|
if (!checkPassword) throw new HttpException('Contraseña incorrecta', 403);
|
|
|
|
const payload = { id_usuario: usuario.id_usuario, name: usuario.nombre };
|
|
const token = this.jwtService.sign(payload); //firma el token
|
|
|
|
const data = {
|
|
usuario: usuario.nombre,
|
|
id: usuario.id_usuario,
|
|
email: usuario.email,
|
|
token,
|
|
};
|
|
|
|
return data;
|
|
}
|
|
}
|