@nestjs/swagger#ApiBearerAuth TypeScript Examples

The following examples show how to use @nestjs/swagger#ApiBearerAuth. 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: auth.controller.ts    From nest-js-boilerplate with MIT License 6 votes vote down vote up
@ApiNoContentResponse({
    description: 'No content. 204',
  })
  @ApiNotFoundResponse({
    schema: {
      type: 'object',
      example: {
        message: 'string',
        error: 'Not Found',
      },
    },
    description: 'User was not found',
  })
  @ApiInternalServerErrorResponse({
    schema: {
      type: 'object',
      example: {
        message: 'string',
        details: {},
      },
    },
    description: '500. InternalServerError',
  })
  @ApiBearerAuth()
  @HttpCode(HttpStatus.NO_CONTENT)
  @Auth(RolesEnum.admin)
  @Put('verify')
  async verifyUser(@Body() verifyUserDto: VerifyUserDto): Promise<User | null> {
    const foundUser = await this.usersService.getUnverifiedUserByEmail(
      verifyUserDto.email,
    ) as UserDocument;

    if (!foundUser) {
      throw new NotFoundException('The user does not exist');
    }

    return this.usersService.update(foundUser._id, { verified: true });
  }
Example #2
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 #3
Source File: collections.controller.ts    From aqualink-app with MIT License 6 votes vote down vote up
@ApiBearerAuth()
  @ApiOperation({ summary: "Fetch all user's private collections" })
  @Get()
  find(
    @Query() filterCollectionDto: FilterCollectionDto,
    @Req() request: AuthRequest,
  ) {
    return this.collectionsService.find(filterCollectionDto, request.user);
  }
Example #4
Source File: categories.controller.ts    From codeclannigeria-backend with MIT License 6 votes vote down vote up
@Post()
  @UseGuards(JwtAuthGuard, RolesGuard)
  @Roles(UserRole.ADMIN)
  @ApiResponse({ type: CategoryDto, status: HttpStatus.CREATED })
  @ApiResponse({ status: HttpStatus.FORBIDDEN, type: ApiException })
  @ApiResponse({ status: HttpStatus.BAD_REQUEST, type: ApiException })
  @ApiBearerAuth()
  async create(@Body() input: CreateCategoryDto): Promise<CategoryDto> {
    const exist = await this.categoryService.findOneAsync({
      title: input.name.toUpperCase()
    });

    if (exist)
      throw new ConflictException(
        `Category with the name "${exist.name}" already exists`
      );

    return super.create(input);
  }
Example #5
Source File: app.controller.ts    From edu-server with MIT License 6 votes vote down vote up
@ApiBearerAuth()
@Controller()
@UseGuards(RolesGuard)
export class AppController {
  constructor(private readonly appService: AppService) {}

  @Get('/hello')
  @Roles(Role.STUDENT)
  getHey(@Req() request): string {
    return 'Hello ' + request['user']?.email + request['user']?.role + '!';
  }
}
Example #6
Source File: article.controller.ts    From nestjs-starter-rest-api with MIT License 6 votes vote down vote up
@Post()
  @ApiOperation({
    summary: 'Create article API',
  })
  @ApiResponse({
    status: HttpStatus.CREATED,
    type: SwaggerBaseApiResponse(ArticleOutput),
  })
  @UseInterceptors(ClassSerializerInterceptor)
  @ApiBearerAuth()
  @UseGuards(JwtAuthGuard)
  async createArticle(
    @ReqContext() ctx: RequestContext,
    @Body() input: CreateArticleInput,
  ): Promise<BaseApiResponse<ArticleOutput>> {
    const article = await this.articleService.createArticle(ctx, input);
    return { data: article, meta: {} };
  }
Example #7
Source File: auth.controller.ts    From bank-server with MIT License 6 votes vote down vote up
@Patch('logout')
  @HttpCode(HttpStatus.NO_CONTENT)
  @ApiNoContentResponse({
    description: 'Successfully Logout',
  })
  @UseGuards(AuthGuard, RolesGuard)
  @UseInterceptors(AuthUserInterceptor)
  @ApiBearerAuth()
  @Roles(RoleType.USER, RoleType.ADMIN, RoleType.ROOT)
  async userLogout(@AuthUser() user: UserEntity): Promise<void> {
    await this._userAuthService.updateLastLogoutDate(user.userAuth);
  }
Example #8
Source File: auth.controller.ts    From MyAPI with MIT License 6 votes vote down vote up
@ApiOperation({ summary: 'Validate authentication token' })
  @ApiOkResponse({ description: 'Authentication token is valid' })
  @ApiUnauthorizedResponse({ description: 'The authentication token is invalid' })
  @UseGuards(AuthGuard())
  @ApiBearerAuth()
  @Get()
  @HttpCode(HttpStatus.OK)
  // eslint-disable-next-line @typescript-eslint/no-empty-function
  isAuthenticated(): void { }
Example #9
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 #10
Source File: app.controller.ts    From nestjs-starter with MIT License 6 votes vote down vote up
/**
   * Create User - User Registration
   * @param dto User Form
   */
  @ApiOperation({
    summary: 'Get my profile',
    description: 'You will get prompt with your user data, keep in mind that you need to provide the Bearer Token for Authentication',
  })
  @ApiOkResponse({ status: 200, description: 'Success response', type: User })
  @ApiUnauthorizedResponse({ status: 401, description: 'Unauthorized' })
  @ApiBadGatewayResponse({ status: 502, description: 'Login user authentication' })
  @ApiBadRequestResponse({ status: 400, description: 'You will prompt with the validation issues' })
  @ApiBearerAuth()
  @UseGuards(JwtAuthGuard)
  @Get('auth/profile')
  async profile(@Request() req) {
    return { output: req.user };
  }
Example #11
Source File: renderer.controller.ts    From Cromwell with MIT License 5 votes vote down vote up
@ApiBearerAuth()
@ApiTags('Renderer')
@Controller('v1/renderer')
export class RendererController {

    constructor(
        private readonly rendererService: RendererService,
    ) { }


    @Get('page')
    @UseGuards(JwtAuthGuard)
    @Roles('administrator')
    @ApiOperation({
        description: `Gather all data for Renderer service required to render a page`,
        parameters: [
            { name: 'pageName', in: 'query', required: true },
            { name: 'themeName', in: 'query', required: true },
            { name: 'slug', in: 'query', required: false },
        ],
    })
    @ApiResponse({
        status: 200,
    })
    async getRendererData(@Query('pageName') pageName: string, @Query('themeName') themeName: string,
        @Query('slug') slug: string) {
        logger.log('RendererController::getRendererData', pageName, themeName);
        if (!pageName) throw new HttpException('Page name is not valid: ' + pageName,
            HttpStatus.NOT_ACCEPTABLE);
        if (!themeName) throw new HttpException('Theme name is not valid: ' + themeName,
            HttpStatus.NOT_ACCEPTABLE);

        return await this.rendererService.getRendererData(pageName, themeName, slug);
    }


    @Get('purge-page-cache')
    @UseGuards(JwtAuthGuard)
    @Roles('administrator')
    @ApiOperation({
        description: `Purge Next.js cache for a page`,
        parameters: [{ name: 'pageRoute', in: 'query', required: true }]
    })
    @ApiResponse({
        status: 200,
    })
    async purgePageCache(@Query('pageRoute') pageRoute: string) {
        logger.log('RendererController::purgePageCache');
        if (!pageRoute)
            throw new HttpException('Page route is not valid: ' + pageRoute, HttpStatus.NOT_ACCEPTABLE);

        await this.rendererService.purgePageCache(pageRoute);
        return true;
    }


    @Get('purge-entire-cache')
    @UseGuards(JwtAuthGuard)
    @Roles('administrator')
    @ApiOperation({
        description: `Purge Next.js entire pages cache`,
    })
    @ApiResponse({
        status: 200,
    })
    async purgeEntireCache() {
        logger.log('RendererController::purgeEntireCache');

        await this.rendererService.purgeEntireCache();
        return true;
    }
}
Example #12
Source File: auth.controller.ts    From nest-js-boilerplate with MIT License 5 votes vote down vote up
@ApiBody({ type: SignInDto })
  @ApiOkResponse({
    schema: {
      type: 'object',
      properties: {
        data: {
          $ref: getSchemaPath(JwtTokensDto),
        },
      },
    },
    description: 'Returns jwt tokens',
  })
  @ApiBadRequestResponse({
    schema: {
      type: 'object',
      example: {
        message: [
          {
            target: {
              email: 'string',
              password: 'string',
            },
            value: 'string',
            property: 'string',
            children: [],
            constraints: {},
          },
        ],
        error: 'Bad Request',
      },
    },
    description: '400. ValidationException',
  })
  @ApiInternalServerErrorResponse({
    schema: {
      type: 'object',
      example: {
        message: 'string',
        details: {},
      },
    },
    description: '500. InternalServerError',
  })
  @ApiBearerAuth()
  @HttpCode(HttpStatus.OK)
  @UseGuards(LocalAuthGuard)
  @Post('sign-in')
  async signIn(@Request() req: ExpressRequest): Promise<JwtTokensDto> {
    const user = req.user as User;

    return this.authService.login(user);
  }