@nestjs/common#Request TypeScript Examples

The following examples show how to use @nestjs/common#Request. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: plugin-newsletter.controller.ts    From Cromwell with MIT License 6 votes vote down vote up
/** 
     * The same method as pluginNewsletterStats in PluginNewsletterResolver. 
     * Added for documentation purposes of custom Controllers.
     * */
    @Get('stats')
    /** You can restrict route by assigning JwtAuthGuard and passing allowed roles as a decorator: */
    @UseGuards(JwtAuthGuard)
    @Roles('administrator', 'guest', 'author')
    @ApiOperation({ description: 'Get newsletters count' })
    @ApiResponse({
        status: 200,
        type: String,
    })
    @ApiForbiddenResponse({ description: 'Forbidden.' })
    async getStats(@Request() request: TRequestWithUser): Promise<string> {

        // Or you can retrieve user info and validate permissions in the method:
        const allowedRoles: TUserRole[] = ['administrator', 'guest', 'author'];
        if (!allowedRoles.includes(request.user?.role))
            throw new ForbiddenException('Forbidden');

        return (await getManager().find(PluginNewsletter) ?? []).length + '';
    }
Example #2
Source File: posts.controller.ts    From NestJs-youtube with MIT License 6 votes vote down vote up
@Override()
  @UseGuards(JwtAuthGuard)
  createOne(
    @Request() req: Express.Request,
    @ParsedRequest() pReq: CrudRequest,
    @ParsedBody() body: Partial<PostEntity>) {
    console.log({ user: (req as any).user, create: true });
    const obj = { ...body, user_id: (req as any).user.id };
    return this.base.createOneBase(pReq, obj);
  }
Example #3
Source File: bom-license-exception.controller.ts    From barista with Apache License 2.0 6 votes vote down vote up
@Post('/')
  @UseInterceptors(CrudRequestInterceptor)
  @ApiResponse({ status: 200, type: BomLicenseException })
  async createOneManualLicense(
    @Body() dto: BomLicenseException,
    @ParsedRequest() req: CrudRequest,
    @Request() request: any,
  ): Promise<BomLicenseException> {
    const { id: userId } = request.user;
    dto.userId = userId;
    const exception = await this.service.createOne(req, dto);

    const project = await this.projectService.findOne({ id: dto.project.id });
    await this.commandBus.execute(
      new LogProjectChangeCommand(
        project.id,
        LogProjectChangeCommand.Actions.licenseExceptionCreated,
        `A license exception has been created for project [${project.name}].`,
        userId,
      ),
    );

    return exception;
  }
Example #4
Source File: application.controller.ts    From uniauth-backend with MIT License 6 votes vote down vote up
@Get(':id')
  @UsePipes(ValidationPipe)
  async findOne(@Request() req, @Param('id') id: string) {
    const user: AuthorizedUser = req.user;
    const application = await this.applicationService.findOneById(id);
    if (String(application.admin) !== user.id) {
      throw new UnauthorizedException();
    }
    delete application.admin;
    return application;
  }
Example #5
Source File: app.controller.ts    From nestjs-keycloak-admin with MIT License 6 votes vote down vote up
@Get('/:slug')
  @DefineScope('read')
  @EnforceResource({
    def: ({params}) => params.slug,
    param: 'slug'
  })
  findBySlug(@Request() req: any): Resource {
    return req.resource as Resource
  }
Example #6
Source File: launcher.controller.ts    From emutypekov with GNU General Public License v3.0 6 votes vote down vote up
@UseInterceptors(ZLibDeflateJSONInterceptor)
  @Post('/launcher/profile/login')
  launcher_profile_login(@Req() request: Request): string {
    if (!request.body) {
      return 'FAILED';
    }
    return this.profile.getProfileByUsername(request.body['username'])[
      'account'
    ]['aid'];
  }
Example #7
Source File: admins.controller.ts    From mamori-i-japan-api with BSD 2-Clause "Simplified" License 6 votes vote down vote up
// TODO @yashmurty : Investigate pagination for this later.
  @UsePipes(new ValidationPipe(VALIDATION_PIPE_OPTIONS))
  @ApiOperation({ summary: 'Get all admin users' })
  @ApiOkResponse({ type: [Admin] })
  @Get('/users')
  async getAdminUsers(@Request() req, @Query() query: PaginationParamsDto): Promise<Admin[]> {
    const requestAdminUser: RequestAdminUser = req.user
    return this.adminsService.findAllAdminUsers(requestAdminUser, query.limit, query.offset)
  }
Example #8
Source File: auth.controller.ts    From Phantom with MIT License 6 votes vote down vote up
@UseGuards(AuthGuard('jwt'))
  @Post('/sign_up/confirm')
  async confirm(@Request() req) {
    const user = await this.userService.createUser(req.user);
    const payload: Payload = {
      _id: user._id,
    };
    const token = await this.authService.signPayload(payload);
    return { profileImage: user.profileImage, token };
  }