Skip to content

Commit

Permalink
Merge pull request #29 from monstar-lab-oss/yash/auth
Browse files Browse the repository at this point in the history
Authentication Guards
  • Loading branch information
yashmurty authored Sep 1, 2020
2 parents 18239ab + 426c04c commit 623683b
Show file tree
Hide file tree
Showing 10 changed files with 45 additions and 19 deletions.
4 changes: 2 additions & 2 deletions src/auth/auth.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,13 @@ import {
ClassSerializerInterceptor,
} from '@nestjs/common';
import { Request } from 'express';
import { AuthGuard } from '@nestjs/passport';
import { ApiTags, ApiResponse, ApiOperation } from '@nestjs/swagger';

import { AuthService } from './auth.service';
import { User } from '../user/entities/user.entity';
import { LoginOutput, LoginInput } from './dto/login.dto';
import { RegisterInput, RegisterOutput } from './dto/register.dto';
import { LocalAuthGuard } from './guards/local-auth.guard';

@ApiTags('Auth')
@Controller('auth')
Expand All @@ -30,7 +30,7 @@ export class AuthController {
status: HttpStatus.OK,
type: LoginOutput,
})
@UseGuards(AuthGuard('local'))
@UseGuards(LocalAuthGuard)
@UseInterceptors(ClassSerializerInterceptor)
async login(
@Req() req: Request,
Expand Down
2 changes: 1 addition & 1 deletion src/auth/auth.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import { JwtStrategy } from './strategies/jwt.strategy';
@Module({
imports: [
SharedModule,
PassportModule.register({ defaultStrategy: 'jwt' }),
PassportModule.register({ defaultStrategy: 'jwtauth' }),
JwtModule.registerAsync({
imports: [SharedModule],
useFactory: async (configService: ConfigService) => ({
Expand Down
4 changes: 2 additions & 2 deletions src/auth/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ export class AuthService {
private jwtService: JwtService,
) {}

async validateUser(username: string, pass: string): Promise<any> {
const user = await this.userService.findByEmail(username);
async validateUser(email: string, pass: string): Promise<any> {
const user = await this.userService.findByEmail(email);
if (!user) return null;

const match = await compare(pass, user.password);
Expand Down
2 changes: 1 addition & 1 deletion src/auth/dto/login.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ export class LoginInput {
@IsNotEmpty()
@ApiProperty()
@MaxLength(200)
username: string;
email: string;

@IsNotEmpty()
@ApiProperty()
Expand Down
23 changes: 23 additions & 0 deletions src/auth/guards/jwt-auth.guard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import {
ExecutionContext,
Injectable,
UnauthorizedException,
} from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';

@Injectable()
export class JwtAuthGuard extends AuthGuard('jwtauth') {
canActivate(context: ExecutionContext) {
// Add your custom authentication logic here
// for example, call super.logIn(request) to establish a session.
return super.canActivate(context);
}

handleRequest(err, user, info) {
// You can throw an exception based on either "info" or "err" arguments
if (err || !user) {
throw err || new UnauthorizedException(`${info}`);
}
return user;
}
}
5 changes: 5 additions & 0 deletions src/auth/guards/local-auth.guard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { Injectable } from '@nestjs/common'
import { AuthGuard } from '@nestjs/passport'

@Injectable()
export class LocalAuthGuard extends AuthGuard('local') {}
2 changes: 1 addition & 1 deletion src/auth/strategies/jwt.strategy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
export class JwtStrategy extends PassportStrategy(Strategy, 'jwtauth') {
constructor(private readonly configService: ConfigService) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
Expand Down
11 changes: 7 additions & 4 deletions src/auth/strategies/local.strategy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,16 @@ import { Injectable, UnauthorizedException } from '@nestjs/common';
import { AuthService } from '../auth.service';

@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {
export class LocalStrategy extends PassportStrategy(Strategy, 'local') {
constructor(private authService: AuthService) {
super();
super({
usernameField: 'email',
passwordField: 'password',
});
}

async validate(username: string, password: string): Promise<any> {
const user = await this.authService.validateUser(username, password);
async validate(email: string, password: string): Promise<any> {
const user = await this.authService.validateUser(email, password);
if (!user) {
throw new UnauthorizedException();
}
Expand Down
4 changes: 2 additions & 2 deletions src/user/user.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,18 @@ import {
UseInterceptors,
ClassSerializerInterceptor,
} from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';

import { Request } from 'express';

import { UserService } from './user.service';
import { GetMeOutput } from './dto/me.dto';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';

@Controller('users')
export class UserController {
constructor(private readonly userService: UserService) {}

@UseGuards(AuthGuard())
@UseGuards(JwtAuthGuard)
@UseInterceptors(ClassSerializerInterceptor)
@Get('me')
getMyProfile(@Req() req: Request): Promise<GetMeOutput> {
Expand Down
7 changes: 1 addition & 6 deletions src/user/user.module.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { PassportModule } from '@nestjs/passport';

import { SharedModule } from '../shared/shared.module';

Expand All @@ -12,11 +11,7 @@ import { User } from '../user/entities/user.entity';
import { JwtStrategy } from '../auth/strategies/jwt.strategy';

@Module({
imports: [
SharedModule,
TypeOrmModule.forFeature([User]),
PassportModule.register({ defaultStrategy: 'jwt' }),
],
imports: [SharedModule, TypeOrmModule.forFeature([User])],
providers: [UserService, JwtStrategy],
controllers: [UserController],
exports: [UserService],
Expand Down

0 comments on commit 623683b

Please sign in to comment.