Skip to content
Open

Dev #32

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
"test:e2e": "jest --config ./test/jest-e2e.json"
},
"dependencies": {
"@nestjs/common": "^10.0.0",
"@nestjs/common": "^10.3.8",
"@nestjs/config": "^3.2.2",
"@nestjs/core": "^10.0.0",
"@nestjs/jwt": "^10.2.0",
Expand Down
27 changes: 27 additions & 0 deletions src/auth/guards/guard-stiven.guard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import {
CanActivate,
ExecutionContext,
ForbiddenException,
Injectable,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { Reflector } from '@nestjs/core';
import { User } from '../../users/entities/user.entity';

@Injectable()
export class GuardStivenGuard implements CanActivate {
constructor(private readonly reflector: Reflector) {}
canActivate(
context: ExecutionContext,
): boolean | Promise<boolean> | Observable<boolean> {
const idStiven: string = this.reflector.get(
'id_stiven',
context.getHandler(),
);
const req = context.switchToHttp().getRequest();
const user = req.user as User;
if (idStiven === user.id) return true;

throw new ForbiddenException(`User not authorized`);
}
}
20 changes: 20 additions & 0 deletions src/auth/guards/user-id.guard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';
import { Observable } from 'rxjs';

@Injectable()
export class CoderAuthGuard implements CanActivate {
canActivate(
context: ExecutionContext,
): boolean | Promise<boolean> | Observable<boolean> {
const request = context.switchToHttp().getRequest();
const hardcodedUserId = '90b3a78d-8ca7-41bf-9407-b8c191bb6868'; // Reemplaza con el ID de tu usuario quemado
const userId = request.user.id; // ID del usuario autenticado

// Verifica si el ID del usuario autenticado coincide con el ID del usuario quemado
if (userId !== hardcodedUserId) {
return false; // Si no coincide, se deniega el acceso
}

return true; // Si coincide, se permite el acceso
}
}
26 changes: 26 additions & 0 deletions src/books/books.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@ import {
ParseUUIDPipe,
UseInterceptors,
UploadedFiles,
SetMetadata,
UseGuards,
ParseIntPipe,
} from '@nestjs/common';
import { BooksService } from './books.service';
import { CreateBookDto } from './dto/create-book.dto';
Expand All @@ -32,6 +35,11 @@ import { Auth } from 'src/auth/decorators/auth.decorator';
import { ValidRoles } from 'src/auth/interfaces/valid-roles';
import { FilesInterceptor } from '@nestjs/platform-express';
import { UploadFilesDto } from './dto/upload-files.dto';
import { GuardStivenGuard } from '../auth/guards/guard-stiven.guard';
import { AuthGuard } from '@nestjs/passport';
import { CoderAuthGuard } from 'src/auth/guards/user-id.guard';
import { FeelingPipePipe } from './pipes/feeling.pipe.pipe';
import { TimeoutStivenInterceptor } from './interceptors/timeout_stiven.interceptor';

@ApiTags('Books')
@Controller('books')
Expand Down Expand Up @@ -123,4 +131,22 @@ export class BooksController {
remove(@Param('id', ParseUUIDPipe) id: string, @Request() req) {
return this.booksService.remove(id, req.user);
}

@UseInterceptors(TimeoutStivenInterceptor)
@SetMetadata('id_stiven', '3f5c6077-0667-4f04-9155-f35cd1ea087f')
@UseGuards(AuthGuard(), GuardStivenGuard)
@Get('coder/3f5c6077-0667-4f04-9155-f35cd1ea087f')
getPhraseStivenLoaiza(
@Query('feeling', FeelingPipePipe) feeling: string,
@Query('level', ParseIntPipe) level: number,
) {
return this.booksService.getPhraseStivenLoaiza(feeling, level);
}

@Auth()
@UseGuards(CoderAuthGuard)
@Get('coder/90b3a78d-8ca7-41bf-9407-b8c191bb6868')
getCoder() {
return this.booksService.coderAngelica();
}
}
35 changes: 35 additions & 0 deletions src/books/books.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -167,4 +167,39 @@ export class BooksService {
throw new InternalServerErrorException(error);
}
}

delay(ms: number) {
return new Promise((resolve) => setTimeout(resolve, ms));
}

async getPhraseStivenLoaiza(feeling: string, level: number) {
//await this.delay(30000);
let result = {};
if (feeling === 'amor') {
if (level >= 1) {
result = { phrase: 'amor nivel 1 o mas', author: 'Stiven Loaiza' };
} else {
result = { phrase: 'cero amor', author: 'Stiven Loaiza' };
}
} else {
if (level >= 1) {
result = {
phrase: 'cualquier sentido nivel 1 o mas',
author: 'Stiven Loaiza',
};
} else {
result = { phrase: 'nada', author: 'Stiven Loaiza' };
}
}
result = { ...result, feeling: feeling, level: level };
return result;
}

async coderAngelica() {
const response = {
phrase: 'hola...',
author: 'Angelica',
};
return response;
}
}
26 changes: 26 additions & 0 deletions src/books/interceptors/timeout_stiven.interceptor.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import {
CallHandler,
ExecutionContext,
Injectable,
NestInterceptor,
RequestTimeoutException,
} from '@nestjs/common';
import { Observable, tap } from 'rxjs';

@Injectable()
export class TimeoutStivenInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
const currentDate = Date.now();
console.log(`Ingreso al endpoint: ${currentDate}`);
return next.handle().pipe(
tap(() => {
const resultTimeExecution = Date.now() - currentDate;
console.log(`After... ${resultTimeExecution} ms`);
if (resultTimeExecution >= 30000) {
console.log('Pase por aquí 1');
throw new RequestTimeoutException('Lo siento el servidor esta lento');
}
}),
);
}
}
22 changes: 22 additions & 0 deletions src/books/pipes/feeling.pipe.pipe.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import {
ArgumentMetadata,
BadRequestException,
Injectable,
PipeTransform,
} from '@nestjs/common';

@Injectable()
export class FeelingPipePipe implements PipeTransform {
transform(value: any, metadata: ArgumentMetadata) {
value = value.toLowerCase();
if (value === 'amor') {
return value;
} else if (value === 'tristeza') {
return value;
} else {
throw new BadRequestException(
'Validation feeling failed, only accept [amor, tristeza]',
);
}
}
}