jwt
This commit is contained in:
+3
-1
@@ -4,6 +4,7 @@ import { AppService } from './app.service';
|
||||
import {ConfigModule} from '@nestjs/config'
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { UsuariosModule } from './usuarios/usuarios.module';
|
||||
import { AuthModule } from './auth/auth.module';
|
||||
|
||||
|
||||
|
||||
@@ -26,7 +27,8 @@ import { UsuariosModule } from './usuarios/usuarios.module';
|
||||
|
||||
|
||||
}),
|
||||
UsuariosModule
|
||||
UsuariosModule,
|
||||
AuthModule
|
||||
],
|
||||
controllers: [],
|
||||
providers: [AppService],
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { AuthController } from './auth.controller';
|
||||
|
||||
describe('AuthController', () => {
|
||||
let controller: AuthController;
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
controllers: [AuthController],
|
||||
}).compile();
|
||||
|
||||
controller = module.get<AuthController>(AuthController);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(controller).toBeDefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,24 @@
|
||||
import { Body, Controller, Get, Post, UseGuards } from '@nestjs/common';
|
||||
import { AuthService } from './auth.service';
|
||||
import { CreateUsuarioDto } from 'src/usuarios/dto/create-usuario.dto';
|
||||
import { LoginDto } from './dto/login.dto';
|
||||
|
||||
|
||||
@Controller('auth')
|
||||
export class AuthController {
|
||||
constructor( private readonly authService:AuthService){}
|
||||
@Post("registro")
|
||||
registro(@Body() registroDto:CreateUsuarioDto ){
|
||||
return this.authService.registro(registroDto);
|
||||
|
||||
}
|
||||
@Post("login")
|
||||
login(@Body() loginDto:LoginDto){
|
||||
return this.authService.login(loginDto);
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { AuthGuard } from '@nestjs/passport';
|
||||
|
||||
@Injectable()
|
||||
export class JwtAuthGuard extends AuthGuard('jwt'){}
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { AuthController } from './auth.controller';
|
||||
import { AuthService } from './auth.service';
|
||||
import { UsuariosModule } from 'src/usuarios/usuarios.module';
|
||||
import { JwtModule } from '@nestjs/jwt';
|
||||
import { PassportModule } from '@nestjs/passport';
|
||||
import { JwtStrategy } from './jwt.strategy';
|
||||
|
||||
@Module({
|
||||
imports:[UsuariosModule,
|
||||
JwtModule,
|
||||
PassportModule,
|
||||
JwtModule.register({
|
||||
global:true,
|
||||
secret: process.env.JWT,
|
||||
signOptions:{expiresIn:"1d"},
|
||||
|
||||
}),
|
||||
],
|
||||
controllers: [AuthController],
|
||||
providers: [AuthService,JwtStrategy]
|
||||
})
|
||||
export class AuthModule {}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { AuthService } from './auth.service';
|
||||
|
||||
describe('AuthService', () => {
|
||||
let service: AuthService;
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [AuthService],
|
||||
}).compile();
|
||||
|
||||
service = module.get<AuthService>(AuthService);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(service).toBeDefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,55 @@
|
||||
import { BadRequestException, Injectable, UnauthorizedException } from '@nestjs/common';
|
||||
import { UsuariosService } from 'src/usuarios/usuarios.service';
|
||||
import * as argon2 from 'argon2';
|
||||
import { LoginDto } from './dto/login.dto';
|
||||
import { CreateUsuarioDto } from 'src/usuarios/dto/create-usuario.dto';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
|
||||
@Injectable()
|
||||
export class AuthService {
|
||||
constructor(
|
||||
private readonly usuarioService:UsuariosService,
|
||||
private readonly jwtService:JwtService
|
||||
){}
|
||||
async registro({nombre, contraseña,tipoUsuario}: CreateUsuarioDto){
|
||||
const usuario= await this.usuarioService.findOneByName(nombre)
|
||||
if(usuario){
|
||||
throw new BadRequestException("Nombre de usuario ya existente");
|
||||
}
|
||||
const hashedContraseña= await argon2.hash(contraseña) ;
|
||||
await this.usuarioService.create({
|
||||
nombre,
|
||||
contraseña:hashedContraseña,
|
||||
tipoUsuario
|
||||
});
|
||||
return{
|
||||
message:"Usuario registrado exitosamente " };
|
||||
}
|
||||
async login({nombre, contraseña}:LoginDto){
|
||||
const usuario= await this.usuarioService.findOneByName(nombre)
|
||||
if(!usuario){
|
||||
throw new UnauthorizedException("Usuario no encontrado");
|
||||
|
||||
}
|
||||
const contraseñaValida= await argon2.verify(contraseña, usuario.contraseña);
|
||||
if(!contraseñaValida){
|
||||
throw new UnauthorizedException("Contraseña invalida");
|
||||
|
||||
}
|
||||
const dataUser={
|
||||
id:usuario.id_usuario,
|
||||
nombre:usuario.nombre,
|
||||
tipoUsuario:usuario.tipoUsuario.id_tipo_usuario}
|
||||
const token=await this.jwtService.sign(dataUser)
|
||||
return{
|
||||
token:token,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { Transform } from "class-transformer";
|
||||
import { IsString, MinLength } from "class-validator";
|
||||
export class LoginDto{
|
||||
@IsString()
|
||||
nombre:string;
|
||||
|
||||
@IsString()
|
||||
@MinLength(5)
|
||||
@Transform(({value})=>value.trim())
|
||||
contraseña:string
|
||||
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { PassportStrategy } from "@nestjs/passport";
|
||||
import{ExtractJwt,Strategy} from 'passport-jwt'
|
||||
|
||||
export class JwtStrategy extends PassportStrategy(Strategy){
|
||||
constructor(){
|
||||
super({
|
||||
jwtFromRequest:ExtractJwt.fromAuthHeaderAsBearerToken(),
|
||||
ignoreExpiration:false,
|
||||
secretOrKey:process.env.JWT
|
||||
});
|
||||
}
|
||||
async validate(dataUser:any){
|
||||
return {
|
||||
id: dataUser.id,
|
||||
nombre: dataUser.nombre,
|
||||
tipoUsuario: dataUser.tipoUsuario,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1 +1,17 @@
|
||||
export class CreateUsuarioDto {}
|
||||
import { Transform } from "class-transformer"
|
||||
import { IsInt, IsString, MinLength} from "class-validator"
|
||||
|
||||
export class CreateUsuarioDto {
|
||||
@IsString()
|
||||
nombre:string
|
||||
|
||||
@IsString()
|
||||
@MinLength(5)
|
||||
@Transform(({value})=>value.trim())
|
||||
contraseña:string
|
||||
|
||||
@IsInt()
|
||||
tipoUsuario:number
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ export class Usuario {
|
||||
@Column({length:100,nullable:true})
|
||||
contraseña:string
|
||||
|
||||
|
||||
@ManyToOne(()=>Tipo_Usuario,tipoUsuario=>tipoUsuario.usuarios )
|
||||
tipoUsuario:Tipo_Usuario;
|
||||
|
||||
@@ -22,7 +23,7 @@ export class Tipo_Usuario{
|
||||
@PrimaryGeneratedColumn()
|
||||
id_tipo_usuario:number
|
||||
|
||||
@Column({nullable:true})
|
||||
@Column({length:50, nullable:true})
|
||||
tipo_usuario:string
|
||||
|
||||
@OneToMany(()=>Usuario,usuarios=>usuarios.tipoUsuario)
|
||||
|
||||
@@ -11,7 +11,7 @@ export class UsuariosController {
|
||||
create(@Body() createUsuarioDto: CreateUsuarioDto) {
|
||||
return this.usuariosService.create(createUsuarioDto);
|
||||
}
|
||||
|
||||
|
||||
@Get()
|
||||
findAll() {
|
||||
return this.usuariosService.findAll();
|
||||
|
||||
@@ -1,26 +1,46 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { CreateUsuarioDto } from './dto/create-usuario.dto';
|
||||
import { UpdateUsuarioDto } from './dto/update-usuario.dto';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { Usuario } from './entities/usuario.entity';
|
||||
import { Repository } from 'typeorm';
|
||||
|
||||
@Injectable()
|
||||
export class UsuariosService {
|
||||
create(createUsuarioDto: CreateUsuarioDto) {
|
||||
return 'This action adds a new usuario';
|
||||
constructor(
|
||||
@InjectRepository(Usuario)
|
||||
private readonly usuarioRepository: Repository <Usuario>
|
||||
){}
|
||||
async create(createUsuarioDto: CreateUsuarioDto) {
|
||||
|
||||
let user= await this.usuarioRepository.create({
|
||||
nombre:createUsuarioDto.nombre,
|
||||
contraseña:createUsuarioDto.contraseña,
|
||||
tipoUsuario:{
|
||||
id_tipo_usuario:createUsuarioDto.tipoUsuario
|
||||
}
|
||||
})
|
||||
|
||||
return await this.usuarioRepository.save(user);
|
||||
}
|
||||
|
||||
async remove(id:number) {
|
||||
return await this.usuarioRepository.delete(id);
|
||||
}
|
||||
async findOneByName(nombre: string) {
|
||||
return await this.usuarioRepository.findOne({where:{nombre}});
|
||||
}
|
||||
|
||||
|
||||
findAll() {
|
||||
return `This action returns all usuarios`;
|
||||
}
|
||||
|
||||
findOne(id: number) {
|
||||
return `This action returns a #${id} usuario`;
|
||||
}
|
||||
|
||||
|
||||
update(id: number, updateUsuarioDto: UpdateUsuarioDto) {
|
||||
return `This action updates a #${id} usuario`;
|
||||
}
|
||||
|
||||
remove(id: number) {
|
||||
return `This action removes a #${id} usuario`;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user