se añadieron los controldores para autorizacion de login
This commit is contained in:
Generated
+951
-34
File diff suppressed because it is too large
Load Diff
@@ -23,14 +23,22 @@
|
||||
"@nestjs/common": "^9.0.0",
|
||||
"@nestjs/config": "^2.3.1",
|
||||
"@nestjs/core": "^9.0.0",
|
||||
"@nestjs/jwt": "^10.0.2",
|
||||
"@nestjs/passport": "^9.0.3",
|
||||
"@nestjs/platform-express": "^9.0.0",
|
||||
"@nestjs/swagger": "^6.2.1",
|
||||
"@nestjs/typeorm": "^9.0.1",
|
||||
"bcrypt": "^5.1.0",
|
||||
"class-transformer": "^0.5.1",
|
||||
"class-validator": "^0.14.0",
|
||||
"moment": "^2.29.4",
|
||||
"passport": "^0.6.0",
|
||||
"passport-jwt": "^4.0.1",
|
||||
"passport-local": "^1.0.0",
|
||||
"pg": "^8.9.0",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rxjs": "^7.2.0",
|
||||
"swagger-ui-express": "^4.6.1",
|
||||
"typeorm": "^0.3.12"
|
||||
},
|
||||
"devDependencies": {
|
||||
@@ -40,6 +48,7 @@
|
||||
"@types/express": "^4.17.13",
|
||||
"@types/jest": "29.2.4",
|
||||
"@types/node": "18.11.18",
|
||||
"@types/passport-local": "^1.0.35",
|
||||
"@types/supertest": "^2.0.11",
|
||||
"@typescript-eslint/eslint-plugin": "^5.0.0",
|
||||
"@typescript-eslint/parser": "^5.0.0",
|
||||
|
||||
+7
-1
@@ -7,6 +7,10 @@ import { EventosModule } from './eventos/eventos.module';
|
||||
import { ParticipanteController } from './participante/participante.controller';
|
||||
import { ParticipanteModule } from './participante/participante.module';
|
||||
import { EventoParticipanteModule } from './evento-participante/evento-participante/evento-participante.module';
|
||||
import { UsuarioModule } from './usuario/usuario.module';
|
||||
import { AuthModule } from './auth/auth.module';
|
||||
import { PassportModule } from '@nestjs/passport';
|
||||
import { JwtModule } from '@nestjs/jwt';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
@@ -23,7 +27,9 @@ import { EventoParticipanteModule } from './evento-participante/evento-participa
|
||||
}),
|
||||
EventosModule,
|
||||
ParticipanteModule,
|
||||
EventoParticipanteModule],
|
||||
EventoParticipanteModule,
|
||||
UsuarioModule,
|
||||
AuthModule, PassportModule, JwtModule.register({})],
|
||||
controllers: [AppController, ParticipanteController],
|
||||
providers: [AppService],
|
||||
})
|
||||
|
||||
@@ -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 };
|
||||
}
|
||||
}
|
||||
+12
-1
@@ -1,9 +1,20 @@
|
||||
import { NestFactory } from '@nestjs/core';
|
||||
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
|
||||
import { AppModule } from './app.module';
|
||||
|
||||
async function bootstrap() {
|
||||
const app = await NestFactory.create(AppModule);
|
||||
app.enableCors()
|
||||
|
||||
const config = new DocumentBuilder()
|
||||
.addBearerAuth()
|
||||
.setTitle('Documentacion')
|
||||
.setDescription('des')
|
||||
.setVersion('1.0')
|
||||
.build();
|
||||
const document = SwaggerModule.createDocument(app, config);
|
||||
SwaggerModule.setup('api', app, document);
|
||||
|
||||
app.enableCors();
|
||||
await app.listen(AppModule.port);
|
||||
}
|
||||
bootstrap();
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
import { Column, Entity, PrimaryGeneratedColumn } from 'typeorm';
|
||||
|
||||
@Entity()
|
||||
export class Usuario {
|
||||
@PrimaryGeneratedColumn()
|
||||
id_usuario: number;
|
||||
|
||||
@Column({ nullable: false })
|
||||
name: string;
|
||||
|
||||
@Column({ nullable: false })
|
||||
password: string;
|
||||
|
||||
@Column({nullable:false})
|
||||
email:string
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { UsuarioService } from './usuario.service';
|
||||
import { UsuarioController } from './usuarios.controller';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { Usuario } from './usuario.entity';
|
||||
|
||||
@Module({
|
||||
imports:[TypeOrmModule.forFeature([Usuario])],
|
||||
providers: [UsuarioService],
|
||||
controllers: [UsuarioController]
|
||||
})
|
||||
export class UsuarioModule {}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { Repository } from 'typeorm';
|
||||
import { Usuario } from './usuario.entity';
|
||||
|
||||
@Injectable()
|
||||
export class UsuarioService {
|
||||
constructor(
|
||||
@InjectRepository(Usuario) private usuarioRepository: Repository<Usuario>,
|
||||
) {}
|
||||
|
||||
getUsuarios(){
|
||||
return this.usuarioRepository.find()
|
||||
}
|
||||
|
||||
getUsuario(email: string) {
|
||||
return this.usuarioRepository.findOne({
|
||||
where: {
|
||||
email,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { Controller, Get, UseGuards } from '@nestjs/common';
|
||||
import { ApiBearerAuth } from '@nestjs/swagger';
|
||||
import { JwtAuthGuard } from 'src/auth/jwt-auth.guard';
|
||||
import { Usuario } from './usuario.entity';
|
||||
import { UsuarioService } from './usuario.service';
|
||||
|
||||
@ApiBearerAuth()
|
||||
@Controller('usuarios')
|
||||
export class UsuarioController {
|
||||
|
||||
constructor(private readonly usuarioService: UsuarioService){}
|
||||
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Get()
|
||||
getUsuarios(): Promise<Usuario[]>{
|
||||
return this.usuarioService.getUsuarios()
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user