How to use the @nestjs/passport.AuthGuard function in @nestjs/passport

To help you get started, we’ve selected a few @nestjs/passport 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 vip-git / react-ssr-advanced-seed / src / server / app / modules / cats / graphql / cats.resolvers.ts View on Github external
Query,
  Mutation,
  Resolver,
  DelegateProperty,
  Subscription,
} from '@nestjs/graphql';
import { PubSub } from 'graphql-subscriptions';

// Internal
import { ICat } from '../shared/cat.model';
import { CatsService } from '../shared/cats.service';
import { CatsGuard } from './cats.guard';

const pubSub = new PubSub();

@UseGuards(AuthGuard('jwt'))
@Resolver('Cat')
export class CatsResolvers {
  constructor(private readonly catsService: CatsService) {}

  @Query()
  @UseGuards(CatsGuard)
  async getCats() {
    return await this.catsService.findAll();
  }

  @Query('cat')
  async findOneById(obj, args, context, info): Promise {
    const { id } = args;
    return await this.catsService.findOneById(+id);
  }
github joe307bad / points / API.Points / src / auth / auth.controller.ts View on Github external
import { Controller, Get, UseGuards } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';

import { Roles } from './gaurds/roles';
import { RolesGuard } from './gaurds/roles';

@Controller('auth')
@UseGuards(RolesGuard)
export class AuthController {
  constructor() { }

  @Get('data')
  @UseGuards(AuthGuard('jwt'))
  @Roles('admin')
  findAll() {
    // this route is restricted
  }
}
github nestjs / nest / sample / 19-auth / src / auth / auth.controller.ts View on Github external
import { Controller, Get, UseGuards } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { AuthService } from './auth.service';

@Controller('auth')
export class AuthController {
  constructor(private readonly authService: AuthService) {}

  @Get('token')
  async createToken(): Promise {
    return await this.authService.createToken();
  }

  @Get('data')
  @UseGuards(AuthGuard())
  findAll() {
    // this route is restricted by AuthGuard
    // JWT strategy
  }
}
github jmcdo29 / zeldaPlay / apps / api / src / app / guards / local.guard.spec.ts View on Github external
it('should return true for `canActivate`', async () => {
    AuthGuard('local').prototype.canActivate = jest.fn(() =>
      Promise.resolve(true),
    );
    AuthGuard('local').prototype.logIn = jest.fn(() => Promise.resolve());
    expect(await guard.canActivate(createMock())).toBe(true);
  });
});
github jiayisheji / jianshu / apps / client / src / app / auth / auth.controller.ts View on Github external
@Body() registerDto: RegisterDto,
  ) {
    return await this.authService.register(registerDto);
  }

  /**
   * 登录账号
   * @param {LoginDto} loginDto
   * @returns
   * @memberof AuthController
   */
  @Post('/login')
  @ApiOperation({ title: '登录' })
  @ApiOkResponse({ description: '登录成功', type: LoginDao })
  @ApiForbiddenResponse({ description: '手机号或邮箱没注册,密码不正确' })
  @UseGuards(AuthGuard('local'))
  @HttpCode(HttpStatus.OK)
  public async login(
    @Body() loginDto: LoginDto,
    @CurrentUser() user: User,
    @Ip() ip: string
  ) {
    this.logger.log(ip);
    return this.authService.login(user);
  }

  /**
   * 登出账号
   * @returns
   * @memberof AuthController
   */
  @Get('/logout')
github neoteric-eu / nestjs-auth / src / app / auth / auth.controller.ts View on Github external
this.logger.error(error, '');
		});
	}

	@Post('refresh')
	@HttpCode(200)
	@ApiResponse({ status: 200, description: 'OK', type: JwtDto })
	public async refreshToken(@Body() body: RefreshTokenDto): Promise {
		this.logger.debug(`[refresh] Token ${body.refreshToken}`);
		const token = await verifyToken(body.refreshToken, config.session.refresh.secret);
		return await createAuthToken({id: token.id});
	}

	@Post('facebook')
	@HttpCode(200)
	@UseGuards(AuthGuard('facebook-token'))
	@ApiResponse({ status: 200, description: 'OK', type: JwtDto })
	public async fbSignIn(@Body() fbToken: FacebookTokenDto, @Profile() profile: FacebookProfile): Promise {
		this.logger.debug(`[fbSignIn] Facebook socialId ${profile.id}`);
		let user = await this.userService.findOne({where: {socialId: profile.id}});
		if (!user) {
			this.logger.debug(`[fbSignIn] User with this id doesn't exists before, social register`);
			user = await this.userService.socialRegister({
				email: profile._json.email,
				first_name: profile._json.first_name,
				last_name: profile._json.last_name,
				socialId: profile._json.id,
				provider: profile.provider,
				is_verified: true
			});
			this.client.send({cmd: USER_CMD_REGISTER_VERIFY}, user).subscribe(() => {}, error => {
				this.logger.error(error, '');
github nestjs / nest / sample / 19-auth-jwt / src / app.controller.ts View on Github external
import { Controller, Get, Request, Post, UseGuards } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { AuthService } from './auth/auth.service';

@Controller()
export class AppController {
  constructor(private readonly authService: AuthService) {}

  @UseGuards(AuthGuard('local'))
  @Post('auth/login')
  async login(@Request() req) {
    return this.authService.login(req.user);
  }

  @UseGuards(AuthGuard('jwt'))
  @Get('profile')
  getProfile(@Request() req) {
    return req.user;
  }
}
github anton-g / quizify / server / src / playlist / playlist.controller.ts View on Github external
import { Controller, UseFilters, Get, HttpCode, UseGuards, Req, Query } from "@nestjs/common";
import { UserExceptionFilter } from "../common/user-exception.filter";
import { PlaylistService } from "./services/playlist.service";
import { PlaylistDto } from "./dtos/playlist.dto";
import { AuthGuard } from "@nestjs/passport";
import { SpotifyService } from "../spotify/spotify.service";

@Controller('playlist')
@UseFilters(new UserExceptionFilter())
export class PlaylistController {
  constructor(
    private readonly playlistService: PlaylistService,
    private readonly spotifyService: SpotifyService) {}

  @UseGuards(AuthGuard('jwt'))
  @HttpCode(200)
  @Get('')
  async get (@Req() { user }, @Query('offset') offset: any): Promise {
    const userPlaylists = await this.spotifyService.getUserPlaylists(user, offset)

    return userPlaylists.map(p => PlaylistDto.fromSpotifyPlaylist(p))
  }

  @HttpCode(200)
  @Get('featured')
  async getFeatured (): Promise {
    const playlists = await this.playlistService.getFeatured()
    return playlists.map(p => new PlaylistDto(p))
  }
}
github joe307bad / points / API.Points / src / achievement / achievement.controller.ts View on Github external
import { Controller, UseGuards, Post, Body, Get, Put, Param, UseInterceptors, UploadedFile } from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { AchievementDto, IAchievementService } from '@points/shared';
import { AuthGuard } from '@nestjs/passport';

import { HasPermission, ApiAction, ApiPermission, PermissionGaurd } from '../core/acl';
import { AchievementService } from './achievement.service';
import { UploadFileSettings } from '../app.settings';
import {OnlyApprovedUsers} from '../auth/guards/approved.guard';

const resource = 'achievement';
export const to = (action: ApiAction) => new ApiPermission(action, resource);

@Controller(resource)
@UseGuards(AuthGuard('jwt'), PermissionGaurd, OnlyApprovedUsers)
export class AchievementController implements IAchievementService {
    constructor(private readonly achievement: AchievementService) { }

    @Post()
    @HasPermission(to('create'))
    @UseInterceptors(FileInterceptor('photo', UploadFileSettings))
    async create(@Body() achievement: AchievementDto, @UploadedFile() photo?): Promise {
        return await this.achievement.create(achievement, photo).catch(err => err);
    }

    @Get()
    @HasPermission(to('read'))
    async getAll(): Promise {
        return await this.achievement.getAll().catch(err => err);
    }

@nestjs/passport

Nest - modern, fast, powerful node.js web framework (@passport)

MIT
Latest version published 8 months ago

Package Health Score

88 / 100
Full package analysis

Similar packages