@nestjs/common#Req TypeScript Examples

The following examples show how to use @nestjs/common#Req. 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: game.controller.ts    From bad-cards-game with GNU Affero General Public License v3.0 6 votes vote down vote up
@UseGuards(AuthGuard)
  @Get('createRoom/:lang')
  async createRoom(@Req() request, @Param('lang') lang: string) {
    if (!['it', 'en'].includes(lang.substring(0, 2))) {
      return {
        error: 'Bad language',
      };
    }
    return {
      roomID: await this.appService.createRoom(request.user.uid, lang.substring(0, 2), 1),
    };
  }
Example #2
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 #3
Source File: auth.controller.ts    From ironfish-api with Mozilla Public License 2.0 6 votes vote down vote up
@ApiExcludeEndpoint()
  @Post('login')
  async login(@Req() req: Request, @Res() res: Response): Promise<void> {
    if (this.config.get<boolean>('DISABLE_LOGIN')) {
      throw new UnauthorizedException();
    }

    let email;

    const { authorization } = req.headers;
    if (!authorization) {
      throw new UnauthorizedException();
    }

    try {
      email = await this.magicLinkService.getEmailFromHeader(authorization);
    } catch {
      throw new UnauthorizedException();
    }

    if (email) {
      const user = await this.usersService.findByEmail(email);
      if (user) {
        await this.usersService.updateLastLoginAt(user);
      } else {
        throw new UnauthorizedException({ error: 'user_invalid' });
      }
    }

    res.sendStatus(HttpStatus.OK);
  }
Example #4
Source File: system.controller.ts    From life-helper-backend with MIT License 6 votes vote down vote up
/**
   * 请求调试(用于 `POST` 请求)
   *
   *
   * ### 功能说明
   *
   * ```markdown
   * 1. 同上
   * ```
   */
  @Post('debug')
  debugForPost(@Req() request: Request): Partial<Request> {
    return this.systemService.pickRequestProperties(request)
  }
Example #5
Source File: auth.controller.ts    From nestjs-rest-sample with GNU General Public License v3.0 6 votes vote down vote up
@UseGuards(LocalAuthGuard)
  @Post('login')
  login(@Req() req: AuthenticatedRequest, @Res() res: Response): Observable<Response> {
    return this.authService.login(req.user)
      .pipe(
        map(token => {
          return res
            .header('Authorization', 'Bearer ' + token.access_token)
            .json(token)
            .send()
        })
      );
  }
Example #6
Source File: api-gateway.controller.ts    From gear-js with GNU General Public License v3.0 6 votes vote down vote up
@Post()
  async rpc(@Req() { body, ip }: { body: IRpcRequest; ip: string }) {
    if (Array.isArray(body)) {
      const testBalance = body.find((value) => value.method === 'testBalance.get');
      if (testBalance && !(await verifyCaptcha(testBalance.params.token))) {
        logger.warn(ip);
        return getResponse(body, errors.Forbidden.name);
      }
    } else {
      if (body.method === 'testBalance.get' && !(await verifyCaptcha(body.params['token']))) {
        logger.warn(ip);
        return getResponse(body, errors.Forbidden.name);
      }
    }
    const response = await this.service.requestMessage(body);
    return response;
  }
Example #7
Source File: uc.controller.ts    From erda-ui with GNU Affero General Public License v3.0 6 votes vote down vote up
@Get('*')
  handleUC(@Req() req: Request, @Res() res: Response) {
    const extension = path.extname(req.path);
    if (!extension) {
      res.sendFile(path.join(staticDir, 'uc', 'index.html'));
    } else {
      res.sendFile(path.join(publicDir, req.path));
    }
  }
Example #8
Source File: auth.controller.ts    From Phantom with MIT License 6 votes vote down vote up
@Get('google/redirect')
  @UseGuards(AuthGuard('google'))
  async googleAuthRedirect(@Req() req, @Res() res) {
    const data = await this.authService.googleLogin(req);
    if (data) {
      res.redirect(
        process.env.FRONT_BASE_URL +
          '/aouth/google?token=' +
          data.token +
          '&type=' +
          data.type,
      );
    } else {
      throw new NotFoundException();
    }
  }
Example #9
Source File: card.controller.ts    From 42_checkIn with GNU General Public License v3.0 6 votes vote down vote up
@UseGuards(JwtAuthGuard)
  @Post('create/:type')
  async createCard(
    @Req() req: any,
    @Query('start') start: number,
    @Query('end') end: number,
    @Param('type') type: number,
  ) {
    return await this.cardServcie.createCard(req.user._id, start, end, type);
  }
Example #10
Source File: app.controller.ts    From nestjs-file-streaming with MIT License 6 votes vote down vote up
@ApiOperation({
    summary: 'Upload a file.',
    requestBody: {
      content: {
        'multipart/form-data': {
          schema: {
            type: 'object',
            properties: { file: { type: 'string', format: 'binary' } },
          },
        },
      },
    },
  })
  @ApiConsumes('multipart/form-data')
  @ApiCreatedResponse({
    schema: {
      properties: {
        id: {
          type: 'string',
          example: '5e2b4cb75876c93e38b6e6aa',
        },
      },
    },
  })
  @Post()
  uploadFile(@Req() request: Request): Promise<{ id: string }> {
    return this.appService.upload(request)
  }
Example #11
Source File: tracks.controller.ts    From codeclannigeria-backend with MIT License 6 votes vote down vote up
@Post(':trackId/enroll')
  @UseGuards(JwtAuthGuard)
  @HttpCode(HttpStatus.OK)
  @ApiBearerAuth()
  @ApiResponse({ status: HttpStatus.BAD_REQUEST, type: ApiException })
  async enroll(
    @Param('trackId') trackId: string,
    @Body() input: MentorInput,
    @Req() req: Request
  ): Promise<void> {
    const track = await this.trackService.findByIdAsync(trackId);
    if (!track) throw new NotFoundException(`Track with ${trackId} not found`);

    if (!track.isActive)
      throw new BadRequestException('Track is not unavailable at the moment');

    const mentor = await this.userService.findOneAsync({
      _id: input.mentorId,
      role: UserRole.MENTOR
    });
    if (!mentor)
      throw new NotFoundException(`Mentor with ${input.mentorId} not found`);

    await this.mentorService.assignMentor(
      req.user['userId'],
      mentor.id,
      trackId
    );
    await this.trackService.enroll(track.id);
  }
Example #12
Source File: AlgoController.ts    From tatum-blockchain-connector with MIT License 6 votes vote down vote up
@Get('/node/algod/:key/*')
  @HttpCode(HttpStatus.OK)
  public async nodeGetAlgod(@Req() req: Request, @Param() param: { key: string }) {
    try {
      return await this.service.nodeMethod(req, param.key, AlgoNodeType.ALGOD);
    } catch (e) {
      if (['Array', 'ValidationError'].includes(e.constructor.name)) {
        throw new BadRequestException(e);
      }
      if (e.constructor.name === 'TatumError' || e.constructor.name === AlgoError.name) {
        throw e;
      }
      throw new AlgoError(`Unexpected error occurred. Reason: ${e.message?.message || e.response?.data || e.message || e}`, 'Algo.error');
    }
  }
Example #13
Source File: app.controller.ts    From nestjs-file-streaming with MIT License 6 votes vote down vote up
@ApiOperation({ summary: 'Download a file.' })
  @Get(':id')
  downloadFile(
    @Param('id') id: string,
    @Req() request: Request,
    @Res({ passthrough: true }) response: Response,
  ): Promise<StreamableFile> {
    return this.appService.download(id, request, response)
  }
Example #14
Source File: AlgoController.ts    From tatum-blockchain-connector with MIT License 6 votes vote down vote up
@Post('/node/indexer/:key/*')
  @HttpCode(HttpStatus.OK)
  public async nodePostIndexer(@Req() req: Request, @Param() param: { key: string }) {
    try {
      return await this.service.nodeMethod(req, param.key, AlgoNodeType.INDEXER);
    } catch (e) {
      if (['Array', 'ValidationError'].includes(e.constructor.name)) {
        throw new BadRequestException(e);
      }
      if (e.constructor.name === 'TatumError' || e.constructor.name === AlgoError.name) {
        throw e;
      }
      throw new AlgoError(`Unexpected error occurred. Reason: ${e.message?.message || e.response?.data || e.message || e}`, 'Algo.error');
    }
  }
Example #15
Source File: request.controller.ts    From radiopanel with GNU General Public License v3.0 6 votes vote down vote up
@Post()
	@Permissions('requests/create')
	public async create(
		@Headers('authorization') authorization: string,
		@Body() request: RequestEntity,
		@Req() req: Request
	): Promise<any> {
		const remoteAddress = req.headers['x-real-ip'] as string || "internal";

		// first of all check for ban
		if (await this.banService.findOne({
			where: [
				{ identifier: remoteAddress, expiresAt: MoreThan(new Date()) },
				{ identifier: remoteAddress, expiresAt: IsNull()  }
			]
		})) {
			throw new NotAcceptableException('You have been banned from this radio');
		}

		if (await this.permissionService.hasPermission((req.user as any)?.uuid || req.headers.authorization, ['requests/ignore-timeout'])) {
			return this.requestService.create({
				requestOrigin: 'website',
				...request,
				requestContext: remoteAddress
			});
		}

		if (await this.requestService.findRecent(remoteAddress)) {
			throw new NotAcceptableException('Please wait before making another request');
		}

		return this.requestService.create({
			requestOrigin: 'website',
			...request,
			requestContext: remoteAddress
		});
	}
Example #16
Source File: MediaController.ts    From typescript-clean-architecture with MIT License 6 votes vote down vote up
@Post()
  @HttpAuth(UserRole.ADMIN, UserRole.AUTHOR)
  @HttpCode(HttpStatus.OK)
  @UseInterceptors(FileInterceptor('file'))
  @ApiBearerAuth()
  @ApiConsumes('multipart/form-data')
  @ApiBody({type: HttpRestApiModelCreateMediaBody})
  @ApiQuery({name: 'name', type: 'string', required: false})
  @ApiQuery({name: 'type', enum: MediaType})
  @ApiResponse({status: HttpStatus.OK, type: HttpRestApiResponseMedia})
  public async createMedia(
    @Req() request: HttpRequestWithUser,
    @UploadedFile() file: MulterFile,
    @Query() query: HttpRestApiModelCreateMediaQuery
    
  ): Promise<CoreApiResponse<MediaUseCaseDto>> {
  
    const adapter: CreateMediaAdapter = await CreateMediaAdapter.new({
      executorId: request.user.id,
      name      : query.name || parse(file.originalname).name,
      type      : query.type,
      file      : file.buffer,
    });
    
    const createdMedia: MediaUseCaseDto = await this.createMediaUseCase.execute(adapter);
    this.setFileStorageBasePath([createdMedia]);
    
    return CoreApiResponse.success(createdMedia);
  }
Example #17
Source File: auth.controller.ts    From bank-server with MIT License 6 votes vote down vote up
@Patch('password/reset')
  @ApiBearerAuth()
  @UseGuards(JwtResetPasswordGuard)
  @HttpCode(HttpStatus.NO_CONTENT)
  @ApiNoContentResponse({
    status: HttpStatus.NO_CONTENT,
    description: 'Successfully reseted password',
  })
  @Transactional()
  async resetPassword(
    @Body() { password }: UserResetPasswordDto,
    @Req() { user },
  ) {
    return this._authService.handleResetPassword(password, user);
  }
Example #18
Source File: todo.controller.ts    From postgres-nest-react-typescript-boilerplate with GNU General Public License v3.0 6 votes vote down vote up
@Patch('/update')
  updateTodo(
    @Query('id') id: string,
    @Req() req,
    @Body() data: Partial<TodoDTO>,
  ) {
    const userId = req.user.id;
    return this.todoService.updateTodo(userId, id, data);
  }
Example #19
Source File: auth.controller.ts    From nest-js-boilerplate with MIT License 6 votes vote down vote up
@ApiNoContentResponse({ description: 'No content. 204' })
  @UseGuards(IsLoggedGuard)
  @Delete('logout')
  @HttpCode(204)
  async logout(@Req() req: ExpressRequest): Promise<{}> {
    await req.logout();

    return {};
  }
Example #20
Source File: sites.controller.ts    From aqualink-app with MIT License 6 votes vote down vote up
@ApiBearerAuth()
  @ApiCreateSiteBody()
  @ApiOperation({ summary: 'Creates a new site and its site application' })
  @OverrideLevelAccess()
  @Post()
  create(
    @Req() request: AuthRequest,
    @Body('siteApplication') siteApplication: CreateSiteApplicationDto,
    @Body('site') site: CreateSiteDto,
  ): Promise<SiteApplication> {
    return this.sitesService.create(siteApplication, site, request.user);
  }
Example #21
Source File: RemixController.ts    From remix-hexagonal-architecture with MIT License 6 votes vote down vote up
@All("*")
  handler(
    @Req() request: Request,
    @Res() response: Response,
    @Next() next: NextFunction,
    @Body() body: any
  ) {
    if (this.isStaticAsset(request)) return next();
    this.purgeRequireCacheInDev();

    return createRequestHandler({
      // `remix build` and `remix dev` output files to a build directory, you need
      // to pass that build to the request handler
      build: require(this.remixHandlerPath),

      // return anything you want here to be available as `context` in your
      // loaders and actions. This is where you can bridge the gap between Remix
      // and your server
      getLoadContext: () => ({
        actions: this.actions,
        loaders: this.loaders,
      }),
    })(request, response, next);
  }
Example #22
Source File: auth.controller.ts    From amplication with Apache License 2.0 6 votes vote down vote up
@UseInterceptors(MorganInterceptor('combined'))
  @UseFilters(GithubAuthExceptionFilter)
  @Get('/github/callback')
  @UseGuards(AuthGuard('github'))
  async githubCallback(@Req() request: Request, @Res() response: Response) {
    const user: AuthUser = request.user as AuthUser;
    this.logger.log({
      level: 'info',
      message: `receive login callback from github account_id=${user.account.id}`
    });
    const token = await this.authService.prepareToken(user);
    response.redirect(301, `${this.host}?token=${token}`);
  }
Example #23
Source File: auth.controller.ts    From nest-js-boilerplate with MIT License 6 votes vote down vote up
@Get('verify/:token')
  @Redirect('/v1/home')
  async verifyUser(
    @Req() req: ExpressRequest,
    @Param('token') token: string,
  ): Promise<any> {
    const id = await this.authService.verifyEmailVerToken(token);
    if (!id) {
      return {
        message: req.flash('The user does not exist'),
      };
    }
    const foundUser = await this.usersService.verifyUser(id);
    if (!foundUser) {
      return {
        message: req.flash('The user does not exist'),
      };
    }
  }
Example #24
Source File: profile.controller.ts    From codeclannigeria-backend with MIT License 6 votes vote down vote up
@Get('mentors')
  @UseGuards(JwtAuthGuard)
  @UseGuards(JwtAuthGuard, RolesGuard)
  @Roles(UserRole.MENTEE)
  @ApiBearerAuth()
  @ApiResponse({ type: PagedUserOutputDto, status: HttpStatus.OK })
  async getMentors(
    @Query() query: FindDto,
    @Req() req: Request
  ): Promise<PagedUserOutputDto> {
    const { skip, limit, search, opts } = query;
    const conditions = JSON.parse(search || '{}');
    const options = JSON.parse(opts || '{}');
    const { totalCount, mentors } = await this.mentorService.getMentors({
      menteeId: req.user['userId'],
      conditions,
      options,
      limit,
      skip
    });
    const items = plainToClass(MentorDto, mentors, {
      enableImplicitConversion: true,
      excludeExtraneousValues: true
    }) as any;
    return { totalCount, items };
  }
Example #25
Source File: auth.controller.ts    From nest-js-boilerplate with MIT License 6 votes vote down vote up
@ApiOkResponse({
    description: 'User registered/authorized successfully',
  })
  @ApiInternalServerErrorResponse({
    schema: {
      type: 'object',
      example: {
        message: 'string',
        details: {},
      },
    },
    description: 'InternalServerError. User was not authorized/registered',
  })
  @UseGuards(GoogleAuthGuard)
  @Get('redirect')
  async googleAuthRedirect(@Req() req: ExpressRequest): Promise<any> {
    if (!req.user) {
      throw new ForbiddenException('No user from google');
    }

    const {
      accessToken,
      refreshToken,
      ...user
    } = req.user as UserGooglePayload;

    const foundUser = await this.usersService.getVerifiedUserByEmail(user.email as string);

    if (!foundUser) {
      await this.usersService.create(user as UserDto);
      return { message: 'Successfully registered' };
    }

    return { message: 'Successfully login' };
  }
Example #26
Source File: cms.controller.ts    From Cromwell with MIT License 6 votes vote down vote up
@Post('import-db')
    @UseGuards(JwtAuthGuard)
    @Roles('administrator')
    @ApiOperation({
        description: 'Import DB from Excel files',
        parameters: [{ name: 'removeSurplus', in: 'query' }]
    })
    @ApiResponse({
        status: 200,
    })
    async importDB(@Req() req: any, @Query('removeSurplus') removeSurplus?: string | null) {
        try {
            await this.migrationService.importDB(req, removeSurplus);
        } catch (error) {
            logger.error(error);
            throw new HttpException(String(error), HttpStatus.INTERNAL_SERVER_ERROR);
        }
        resetAllPagesCache();
    }
Example #27
Source File: waiting.controller.ts    From 42_checkIn with GNU General Public License v3.0 6 votes vote down vote up
@UseInterceptors(IpInterceptor)
  @UseGuards(JwtAuthGuard)
  @Post('create/:type')
  async createWaiting(
    @Req() req: any,
    @Param('type')
    type: number,
  ) {
    return this.waitingService.create(req.user._id, type);
  }
Example #28
Source File: mentor.controller.ts    From codeclannigeria-backend with MIT License 6 votes vote down vote up
@Get('submissions')
  @HttpCode(HttpStatus.OK)
  @ApiResponse({ status: HttpStatus.OK, type: PagedListSubmissionDto })
  @UseGuards(JwtAuthGuard, RolesGuard)
  @Roles(UserRole.MENTOR)
  @ApiBearerAuth()
  @ApiResponse({ status: HttpStatus.BAD_REQUEST, type: ApiException })
  async getSubmissions(
    @Query() query: FindDto,
    @Req() req: Request
  ): Promise<PagedListSubmissionDto> {
    const { skip, limit, search, opts } = query;
    const conditions = search && JSON.parse(search);
    const options = opts && JSON.parse(opts);
    const mentorId = req.user['userId'];
    const submissions = await this.SubmissionModel.find(
      { ...conditions, mentor: mentorId },
      null,
      { ...options, limit, skip }
    );

    const items = plainToClass(SubmissionDto, submissions, {
      enableImplicitConversion: true,
      excludeExtraneousValues: true
    }) as any;
    const totalCount = await this.mentorService.countSubmissions(mentorId);
    return { totalCount, items };
  }
Example #29
Source File: surveys.controller.ts    From aqualink-app with MIT License 6 votes vote down vote up
@ApiBearerAuth()
  @ApiNestNotFoundResponse('No site was found with the specified id')
  @ApiOperation({ summary: 'Creates a new survey' })
  @ApiParam({ name: 'siteId', example: 1 })
  @Post()
  create(
    @Body() createSurveyDto: CreateSurveyDto,
    @Param('siteId', ParseIntPipe) siteId: number,
    @Req() req: AuthRequest,
  ): Promise<Survey> {
    return this.surveyService.create(createSurveyDto, req.user, siteId);
  }