@nestjs/common#UseGuards TypeScript Examples

The following examples show how to use @nestjs/common#UseGuards. 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 7 votes vote down vote up
@Post('subscribe')
    /** Use ThrottlerGuard to limit number of requests from one IP address. Allow max 4 requests in 20 seconds: */
    @UseGuards(ThrottlerGuard)
    @Throttle(4, 20)
    @ApiOperation({ description: 'Post email to subscribe for newsletters' })
    @ApiResponse({
        status: 200,
        type: Boolean,
    })
    @ApiBody({ type: PluginNewsletterSubscription })
    @ApiForbiddenResponse({ description: 'Forbidden.' })
    async placeSubscription(@Body() input: PluginNewsletterSubscription): Promise<boolean | undefined> {
        const email = input?.email;
        if (!email || !/\S+@\S+\.\S+/.test(email)) {
            throw new HttpException(`Invalid email`, HttpStatus.BAD_REQUEST);
        }

        const hasSubscribed = await getManager().findOne(PluginNewsletter, {
            where: {
                email
            }
        });
        if (hasSubscribed) return true;

        const newsletter = new PluginNewsletter();
        newsletter.email = email;
        await getManager().save(newsletter);
        return true;
    }
Example #2
Source File: auth.controller.ts    From nest-js-boilerplate with MIT License 6 votes vote down vote up
@ApiNoContentResponse({
    description: 'no content',
  })
  @ApiInternalServerErrorResponse({
    schema: {
      type: 'object',
      example: {
        message: 'string',
        details: {},
      },
    },
    description: '500. InternalServerError',
  })
  @ApiInternalServerErrorResponse({ description: '500. InternalServerError' })
  @ApiBearerAuth()
  @Delete('logout-all')
  @UseGuards(RolesGuard)
  @Roles(RolesEnum.admin)
  @HttpCode(HttpStatus.NO_CONTENT)
  async logoutAll(): Promise<{}> {
    return this.authService.deleteAllTokens();
  }
Example #3
Source File: tracks.controller.ts    From codeclannigeria-backend with MIT License 6 votes vote down vote up
@Put(':trackId/reactivate')
  @UseGuards(JwtAuthGuard, RolesGuard)
  @Roles(UserRole.ADMIN)
  @ApiResponse({ status: HttpStatus.OK })
  @ApiBearerAuth()
  async enableTrack(@Param('trackId') trackId: string): Promise<void> {
    const track = await this.trackService.findByIdAsync(trackId);

    if (!track) throw new NotFoundException(`Track with ${trackId} not found`);

    await this.trackService.activateTrack(trackId);
  }
Example #4
Source File: time-series.controller.ts    From aqualink-app with MIT License 6 votes vote down vote up
@ApiOperation({ summary: 'Upload time series data' })
  @UseGuards(IsSiteAdminGuard)
  @Auth(AdminLevel.SiteManager, AdminLevel.SuperAdmin)
  @Post('sites/:siteId/site-survey-points/:surveyPointId/upload')
  @UseInterceptors(
    FilesInterceptor('files', MAX_FILE_COUNT, {
      dest: './upload',
      fileFilter,
      limits: {
        fileSize: MAX_FILE_SIZE_MB * 10 ** 6,
      },
    }),
  )
  uploadTimeSeriesData(
    @Param() surveyPointDataRangeDto: SurveyPointDataRangeDto,
    @UploadedFiles() files: Express.Multer.File[],
    @Body('sensor') sensor: SourceType,
    @Query('failOnWarning', ParseBoolPipe) failOnWarning?: boolean,
  ) {
    return this.timeSeriesService.uploadData(
      surveyPointDataRangeDto,
      sensor,
      files,
      failOnWarning,
    );
  }
Example #5
Source File: auth.resolver.ts    From amplication with Apache License 2.0 6 votes vote down vote up
@Mutation(() => Auth)
  @UseGuards(GqlAuthGuard)
  async completeInvitation(
    @UserEntity() user: User,
    @Args() args: CompleteInvitationArgs
  ): Promise<Auth> {
    if (!user.account) {
      throw new Error('User has no account');
    }
    const token = await this.authService.completeInvitation(user, args);
    return { token };
  }
Example #6
Source File: user.resolver.ts    From svvs with MIT License 6 votes vote down vote up
/**
   * Implement GraphQL Query 'user'
   *
   * @param user provides the user as a candidate for search in userRepository
   */
  @Query('user')
  @UseGuards(GqlAuthGuard)
  async whoAmI(@CurrentUser() user: UserEntity) {
    return await this.userService.findOneById(user.id)
  }
Example #7
Source File: dashboard.controller.ts    From uniauth-backend with MIT License 6 votes vote down vote up
@Get('/dev/details/:id')
  @UseGuards(JwtAuthGuard)
  async showUserList(@Request() req, @Res() res: Response, @Param('id') id: string) {
    try {
      const userDetails = await this.applicationService.findUsersGrantedAccess(id);
      res.render('dashboard/details.hbs', {
        userDetails: userDetails.participants,
      });
    } catch (e) {
      res.render('error.hbs');
    }
  }
Example #8
Source File: whisp.resolver.ts    From whispr with MIT License 6 votes vote down vote up
@UseGuards(GqlJwtAuthGuard)
  @Query(() => [Whisp], { nullable: true })
  async whispsAuthBeta(
    @Args('filter', { type: () => GraphQLJSONObject, nullable: true })
      filter?: Record<string, unknown>,
    @Args('sort', { type: () => GraphQLJSONObject, nullable: true })
      sort?: Record<string, unknown>,
    @Args('limit', { type: () => Int, nullable: true }) limit?: number,
  ): Promise<IWhisp[]> {
    return this.whispService.findAll(filter, sort, limit);
  }
Example #9
Source File: user.controller.ts    From barista with Apache License 2.0 6 votes vote down vote up
@UseGuards(AuthGuard('jwt'))
  @ApiBearerAuth()
  @Get('projects')
  @UseInterceptors(CrudRequestInterceptor)
  @ApiResponse({ status: 200, type: Project, isArray: true })
  async getManyProjects(
    @Query('page') page: number,
    @Query('pageSize') pageSize: number,
    @Query('filterText') filterText: string,
    @Request() request,
  ): Promise<GetManyDefaultResponse<Project> | Project[]> {
    const { groups: userId } = request.user;
    userId.push(request.user.id);

    let qb = this.projectService.getUsersProjectsQuery(userId);
    if (filterText) {
      qb = qb.andWhere('lower(project.name) like :filter or lower(project.gitUrl) like :filter', {
        filter: `%${filterText.toLowerCase()}%`,
      });
    }

    return await PaginateArrayResult(qb, page, pageSize);
  }
Example #10
Source File: app.gateway.ts    From nest-js-boilerplate with MIT License 6 votes vote down vote up
/**
   * Returns you Hello world!
   * @returns {string} Hello, World!
   */
  @UseGuards(JwtWSAccessGuard)
  @SubscribeMessage('event')
  handleEvent() {
    return 'Hello, World!';
  }
Example #11
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 #12
Source File: users.controller.ts    From nest-js-boilerplate with MIT License 6 votes vote down vote up
@ApiOkResponse({
    schema: {
      type: 'object',
      properties: {
        data: {
          $ref: getSchemaPath(UserEntity),
        },
      },
    },
    description: '200. Success. Returns all users',
  })
  @ApiUnauthorizedResponse({
    schema: {
      type: 'object',
      example: {
        message: 'string',
      },
    },
    description: '401. UnauthorizedException.',
  })
  @Get()
  @UseGuards(JwtAccessGuard)
  @Serialize(AllUsersResponseEntity)
  async getAllVerifiedUsers(): Promise<UserEntity[] | []> {
    const foundUsers = await this.usersService.getVerifiedUsers();

    return foundUsers;
  }
Example #13
Source File: cms.controller.ts    From Cromwell with MIT License 6 votes vote down vote up
@Post('place-order')
    @UseGuards(ThrottlerGuard)
    @Throttle(3, 20)
    @ApiOperation({
        description: 'Creates new Order in the shop',
    })
    @ApiBody({ type: CreateOrderDto })
    @ApiResponse({
        status: 200,
    })
    async placeOrder(@Body() input: CreateOrderDto): Promise<TOrder | undefined> {
        if (!input || !input.customerEmail
            || !input.customerPhone) throw new HttpException('Order form is incomplete', HttpStatus.NOT_ACCEPTABLE);

        const order = await this.storeService.placeOrder(input);
        serverFireAction('create_order', order);
        return order;
    }