se añadieron los controldores para autorizacion de login
This commit is contained in:
@@ -0,0 +1,25 @@
|
||||
import { Body, Controller, Post, Request, UseGuards } from '@nestjs/common';
|
||||
import { AuthGuard } from '@nestjs/passport';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { Usuario } from 'src/usuario/usuario.entity';
|
||||
import { Repository } from 'typeorm';
|
||||
import { AuthService } from './auth.service';
|
||||
import { LoginUsuarioDto } from './dto/loginUsuario.dto';
|
||||
import { RegistrarUsuarioDto } from './dto/registrarUsuario.dto';
|
||||
|
||||
@Controller('auth')
|
||||
export class AuthController {
|
||||
constructor(
|
||||
private authService: AuthService,
|
||||
) /* @InjectRepository(Usuario) private usuarioRepository: Repository<Usuario> */ {}
|
||||
|
||||
@Post('registro')
|
||||
registrarUsuario(@Body() registrarUsuario: RegistrarUsuarioDto) {
|
||||
return this.authService.registrar(registrarUsuario);
|
||||
}
|
||||
|
||||
@Post('login')
|
||||
login(@Body() LoginUsuario: LoginUsuarioDto) {
|
||||
return this.authService.login(LoginUsuario);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { PassportModule } from '@nestjs/passport';
|
||||
import { UsuarioModule } from 'src/usuario/usuario.module';
|
||||
import { AuthService } from './auth.service';
|
||||
import { jwtStrategy } from './jwt.strategy';
|
||||
import { AuthController } from './auth.controller';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { Usuario } from 'src/usuario/usuario.entity';
|
||||
import { UsuarioService } from 'src/usuario/usuario.service';
|
||||
import { JwtModule } from '@nestjs/jwt';
|
||||
import { jwtConstants } from './jwt.constants';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
UsuarioModule,
|
||||
PassportModule,
|
||||
TypeOrmModule.forFeature([Usuario]),
|
||||
JwtModule.register({
|
||||
secret: jwtConstants.secret,
|
||||
signOptions: { expiresIn: '5h' },
|
||||
}),
|
||||
],
|
||||
providers: [AuthService, jwtStrategy, UsuarioService, jwtStrategy],
|
||||
controllers: [AuthController],
|
||||
})
|
||||
export class AuthModule {}
|
||||
@@ -0,0 +1,61 @@
|
||||
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';
|
||||
|
||||
@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.name };
|
||||
const token = this.jwtService.sign(payload); //firma el token
|
||||
|
||||
const data = {
|
||||
usuario: usuario.name,
|
||||
id: usuario.id_usuario,
|
||||
email: usuario.email,
|
||||
token,
|
||||
};
|
||||
|
||||
return data;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import { IsEmail, MaxLength, MinLength } from "class-validator";
|
||||
|
||||
export class LoginUsuarioDto {
|
||||
@IsEmail()
|
||||
email: string
|
||||
|
||||
@MinLength(10)
|
||||
@MaxLength(15)
|
||||
password: string
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import { PartialType } from "@nestjs/swagger";
|
||||
import { IsNotEmpty } from "class-validator";
|
||||
import { LoginUsuarioDto } from "./loginUsuario.dto";
|
||||
|
||||
|
||||
export class RegistrarUsuarioDto extends PartialType(LoginUsuarioDto){
|
||||
@IsNotEmpty()
|
||||
name: string
|
||||
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { AuthGuard } from '@nestjs/passport';
|
||||
|
||||
@Injectable()
|
||||
export class JwtAuthGuard extends AuthGuard('jwt') {}
|
||||
@@ -0,0 +1,3 @@
|
||||
export const jwtConstants = {
|
||||
secret: "SemillaSecreta"
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { PassportStrategy } from '@nestjs/passport';
|
||||
import { Injectable, UnauthorizedException } from '@nestjs/common';
|
||||
import { ExtractJwt, Strategy } from 'passport-jwt';
|
||||
import { jwtConstants } from './jwt.constants';
|
||||
|
||||
@Injectable()
|
||||
export class jwtStrategy extends PassportStrategy(Strategy) {
|
||||
constructor() {
|
||||
super({
|
||||
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
|
||||
ignoreExpiration: false,
|
||||
secretOrKey: jwtConstants.secret,
|
||||
});
|
||||
}
|
||||
|
||||
async validate(payload: any) {
|
||||
return { userId: payload.sub , username: payload.username };
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user