How to use the @nestjs/common.UseGuards function in @nestjs/common

To help you get started, weโ€™ve selected a few @nestjs/common examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github alexitaylor / angular-graphql-nestjs-postgres-starter-kit / server / project / src / messages / messages.resolvers.ts View on Github external
Query,
  Resolver,
  Subscription,
  Context,
} from '@nestjs/graphql';
import { PubSub } from 'graphql-subscriptions';
import { MessagesService } from './messages.service';
import { MessagesDto, MessageConnection } from './dto/messages.dto';
import { AuthGuard } from '../auth/guards/auth.guard';
import { Roles } from '../decorators/roles.decorators';
import { RolesGuard } from '../auth/guards/roles.guard';

const pubSub = new PubSub();

@Resolver('Message')
@UseGuards(new AuthGuard(), RolesGuard)
export class MessagesResolvers {
  constructor(private readonly messagesService: MessagesService) {}

  // TODO pagination cursor instead of page???
  @Query('messages')
  @Roles('ADMIN', 'USER')
  async getMessages(
    @Args('page') page: number,
    @Args('limit') limit: number,
    @Args('newest') newest: boolean,
  ): Promise {
    return await this.messagesService.findAll(page, limit, newest);
  }

  @Query('message')
  @Roles('ADMIN', 'USER')
github kelvin-mai / nest-commerce / src / product / product.controller.ts View on Github external
}

  @Get('/mine')
  @UseGuards(AuthGuard('jwt'), SellerGuard)
  async listMine(@User() user: UserDocument): Promise {
    const { id } = user;
    return await this.productService.findByOwner(id);
  }

  @Get('/seller/:id')
  async listBySeller(@Param('id') id: string): Promise {
    return await this.productService.findByOwner(id);
  }

  @Post()
  @UseGuards(AuthGuard('jwt'), SellerGuard)
  async create(
    @Body() product: CreateProductDTO,
    @User() user: UserDocument,
  ): Promise {
    return await this.productService.create(product, user);
  }

  @Get(':id')
  async read(@Param('id') id: string): Promise {
    return await this.productService.findById(id);
  }

  @Put(':id')
  @UseGuards(AuthGuard('jwt'), SellerGuard)
  async update(
    @Param('id') id: string,
github vellengs / typerx / src / server / cats / cats.controller.ts View on Github external
UseGuards,
  UseInterceptors,
  Param,
} from '@nestjs/common';
import { CreateCatDto } from './dto/create-cat.dto';
import { CatsService } from './cats.service';
import { Cat } from './interfaces/cat.interface';
import { RolesGuard } from '../common/guards/roles.guard';
import { Roles } from '../common/decorators/roles.decorator';
import { LoggingInterceptor } from '../common/interceptors/logging.interceptor';
import { TransformInterceptor } from '../common/interceptors/transform.interceptor';
import { ParseIntPipe } from '../common/pipes/parse-int.pipe';
import { async } from '@angular/core/testing';

@Controller('api/cats')
@UseGuards(RolesGuard)
@UseInterceptors(LoggingInterceptor, TransformInterceptor)
export class CatsController {
  constructor(private readonly catsService: CatsService) { }


  /**
   * ๅˆ›ๅปบ็›ฎๅฝ•
   * @param createCatDto ๅฎžไฝ“ๅ‚ๆ•ฐ
   */
  @Post()
  @Roles('admin')
  async create( @Body() createCatDto: CreateCatDto) {
    this.catsService.create(createCatDto);
  }

  /**
github SolidZORO / leaa / packages / leaa-api / src / modules / article / article.resolver.ts View on Github external
@Query(() => Article)
  async articleBySlug(
    @Args({ name: 'slug', type: () => String }) slug: string,
    @Args() args?: ArticleArgs,
  ): Promise<article> {
    return this.articleService.articleBySlug(slug, args);
  }

  @UseGuards(PermissionsGuard)
  @Permissions('article.item-create')
  @Mutation(() =&gt; Article)
  async createArticle(@Args('article') args: CreateArticleInput): Promise<article> {
    return this.articleService.createArticle(args);
  }

  @UseGuards(PermissionsGuard)
  @Permissions('article.item-update')
  @Mutation(() =&gt; Article)
  async updateArticle(
    @Args({ name: 'id', type: () =&gt; Int }) id: number,
    @Args('article') args: UpdateArticleInput,
  ): Promise<article> {
    return this.articleService.updateArticle(id, args);
  }

  @UseGuards(PermissionsGuard)
  @Permissions('article.item-delete')
  @Mutation(() =&gt; Article)
  async deleteArticle(@Args({ name: 'id', type: () =&gt; Int }) id: number): Promise<article> {
    return this.articleService.deleteArticle(id);
  }
}</article></article></article></article>
github auth0-blog / nest-restaurant-api / src / items / items.controller.ts View on Github external
import { ItemsService } from './items.service';
import { Item } from './item.interface';
import { ValidationPipe } from '../common/validation.pipe';
import { AdminGuard } from '../common/admin.guard';

@Controller('items')
export class ItemsController {
  constructor(private readonly itemsService: ItemsService) {}

  @Get()
  async findAll(): Promise {
    return this.itemsService.findAll();
  }

  @Post()
  @UseGuards(new AdminGuard())
  @UsePipes(new ValidationPipe())
  async create(@Body() createItemDto: CreateItemDto) {
    this.itemsService.create(createItemDto);
  }
}
github penta-jelly / re-radio / server / src / radio / songs / songs.resolver.ts View on Github external
@Mutation('updateManySongs')
  @UseGuards(AuthenticationGuard, AuthorizationGuard)
  @Roles(['ADMIN', SongsResolver.songCreatorChecker])
  async updateManySongs(@Args() args, @Info() info): Promise {
    return await this.prisma.mutation.updateManySongs(args, info);
  }

  @Mutation('deleteSong')
  @UseGuards(AuthenticationGuard, AuthorizationGuard)
  @Roles(['ADMIN', SongsResolver.songCreatorChecker])
  async deleteSong(@Args() args, @Info() info): Promise {
    return await this.prisma.mutation.deleteSong(args, info);
  }

  @Mutation('deleteManySongs')
  @UseGuards(AuthenticationGuard, AuthorizationGuard)
  @Roles(['ADMIN', SongsResolver.songCreatorChecker])
  async deleteManySongs(@Args() args, @Info() info): Promise {
    return await this.prisma.mutation.deleteManySongs(args, info);
  }

  @Subscription('song')
  onSongMutation(@Args() args, @Info() info) {
    return this.prisma.subscription.song(args, info);
  }

  static async songCreatorChecker({
    user,
    args: { where },
    services: { prisma },
  }: RoleDecoratorParam&lt;{ where: SongWhereUniqueInput | SongWhereInput }&gt;) {
    const songs = await prisma.query.songs({ where }, `{ id creator { id } }`);
github neoteric-eu / nestjs-auth / src / app / home / home.resolver.ts View on Github external
return createdHome;
	}

	@Mutation('deleteHome')
	@UseGuards(GraphqlGuard)
	async delete(@CurrentUser() user: User, @Args('deleteHomeInput') args: DeleteHomeDto): Promise {
		const deletedHome = await this.homeService.softDelete(args);
		this.client.send({cmd: HOME_CMD_DELETE}, deletedHome).subscribe(() =&gt; {}, error =&gt; {
			this.logger.error(error, '');
		});
		await this.pubSub.publish('homeDeleted', {homeDeleted: deletedHome});
		return deletedHome;
	}

	@Mutation('updateHome')
	@UseGuards(GraphqlGuard)
	async update(@Args('updateHomeInput') args: UpdateHomeDto): Promise {
		const updatedHome = await this.homeService.update(args);
		await this.pubSub.publish('homeUpdated', {homeUpdated: updatedHome});
		return updatedHome;
	}

	@Subscription('homeCreated')
	homeCreated() {
		return {
			subscribe: () =&gt; this.pubSub.asyncIterator('homeCreated')
		};
	}

	@Subscription('homeDeleted')
	homeDeleted() {
		return {
github fischermatte / geolud / geolud-server-node / src / projects / projects.resolver.ts View on Github external
import { UseGuards } from '@nestjs/common';
import { Project } from './project.model';
import { MongoRepository, ObjectID as TypeOrmObjectID} from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { ProjectsGuard } from './projects.guard';
import { ObjectID as MongoObjectID} from 'mongodb';

@Resolver('Projects')
export class ProjectsResolvers {
  constructor(
    @InjectRepository(Project)
    private readonly projectRepository: MongoRepository,
  ) {}

  @Query('allProjects')
  @UseGuards(ProjectsGuard)
  async allProjects(): Promise {
    const projects = await this.projectRepository.find();
    projects.sort((a, b) =&gt; b.period.from.getTime() - a.period.from.getTime());
    return projects;
  }

  @Query('project')
  project(@Args('id') id: string): Promise {
    return this.projectRepository.findOne(new MongoObjectID(id) as TypeOrmObjectID);
  }
}
github rucken / todo-nestjs / src / libs / core / controllers / content-types.controller.ts View on Github external
} from '@nestjs/swagger';
import { plainToClass } from 'class-transformer';
import { Permissions } from '../decorators/permissions.decorator';
import { Roles } from '../decorators/roles.decorator';
import { InContentTypeDto } from '../dto/in-content-type.dto';
import { OutContentTypeDto } from '../dto/out-content-type.dto';
import { OutContentTypesDto } from '../dto/out-content-types.dto';
import { ContentType } from '../entities/content-type.entity';
import { AccessGuard } from '../guards/access.guard';
import { ParseIntWithDefaultPipe } from '../pipes/parse-int-with-default.pipe';
import { ContentTypesService } from '../services/content-types.service';

@ApiUseTags('content-types')
@ApiBearerAuth()
@Controller('/api/content_types')
@UseGuards(AccessGuard)
export class ContentTypesController {
  constructor(private readonly service: ContentTypesService) {}
  @Roles('isSuperuser')
  @Permissions('add_content-type')
  @HttpCode(HttpStatus.CREATED)
  @ApiResponse({
    status: HttpStatus.CREATED,
    type: OutContentTypeDto,
    description: 'The record has been successfully created.'
  })
  @ApiResponse({ status: HttpStatus.FORBIDDEN, description: 'Forbidden.' })
  @Post()
  async create(@Body() dto: InContentTypeDto) {
    try {
      return plainToClass(
        OutContentTypeDto,