Skip to content

Commit 623683b

Browse files
authored
Merge pull request #29 from monstar-lab-oss/yash/auth
Authentication Guards
2 parents 18239ab + 426c04c commit 623683b

File tree

10 files changed

+45
-19
lines changed

10 files changed

+45
-19
lines changed

src/auth/auth.controller.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,13 +9,13 @@ import {
99
ClassSerializerInterceptor,
1010
} from '@nestjs/common';
1111
import { Request } from 'express';
12-
import { AuthGuard } from '@nestjs/passport';
1312
import { ApiTags, ApiResponse, ApiOperation } from '@nestjs/swagger';
1413

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

2020
@ApiTags('Auth')
2121
@Controller('auth')
@@ -30,7 +30,7 @@ export class AuthController {
3030
status: HttpStatus.OK,
3131
type: LoginOutput,
3232
})
33-
@UseGuards(AuthGuard('local'))
33+
@UseGuards(LocalAuthGuard)
3434
@UseInterceptors(ClassSerializerInterceptor)
3535
async login(
3636
@Req() req: Request,

src/auth/auth.module.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ import { JwtStrategy } from './strategies/jwt.strategy';
1515
@Module({
1616
imports: [
1717
SharedModule,
18-
PassportModule.register({ defaultStrategy: 'jwt' }),
18+
PassportModule.register({ defaultStrategy: 'jwtauth' }),
1919
JwtModule.registerAsync({
2020
imports: [SharedModule],
2121
useFactory: async (configService: ConfigService) => ({

src/auth/auth.service.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,8 @@ export class AuthService {
1414
private jwtService: JwtService,
1515
) {}
1616

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

2121
const match = await compare(pass, user.password);

src/auth/dto/login.dto.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ export class LoginInput {
55
@IsNotEmpty()
66
@ApiProperty()
77
@MaxLength(200)
8-
username: string;
8+
email: string;
99

1010
@IsNotEmpty()
1111
@ApiProperty()

src/auth/guards/jwt-auth.guard.ts

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
import {
2+
ExecutionContext,
3+
Injectable,
4+
UnauthorizedException,
5+
} from '@nestjs/common';
6+
import { AuthGuard } from '@nestjs/passport';
7+
8+
@Injectable()
9+
export class JwtAuthGuard extends AuthGuard('jwtauth') {
10+
canActivate(context: ExecutionContext) {
11+
// Add your custom authentication logic here
12+
// for example, call super.logIn(request) to establish a session.
13+
return super.canActivate(context);
14+
}
15+
16+
handleRequest(err, user, info) {
17+
// You can throw an exception based on either "info" or "err" arguments
18+
if (err || !user) {
19+
throw err || new UnauthorizedException(`${info}`);
20+
}
21+
return user;
22+
}
23+
}
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
import { Injectable } from '@nestjs/common'
2+
import { AuthGuard } from '@nestjs/passport'
3+
4+
@Injectable()
5+
export class LocalAuthGuard extends AuthGuard('local') {}

src/auth/strategies/jwt.strategy.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import { PassportStrategy } from '@nestjs/passport';
55
import { ExtractJwt, Strategy } from 'passport-jwt';
66

77
@Injectable()
8-
export class JwtStrategy extends PassportStrategy(Strategy) {
8+
export class JwtStrategy extends PassportStrategy(Strategy, 'jwtauth') {
99
constructor(private readonly configService: ConfigService) {
1010
super({
1111
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),

src/auth/strategies/local.strategy.ts

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,13 +5,16 @@ import { Injectable, UnauthorizedException } from '@nestjs/common';
55
import { AuthService } from '../auth.service';
66

77
@Injectable()
8-
export class LocalStrategy extends PassportStrategy(Strategy) {
8+
export class LocalStrategy extends PassportStrategy(Strategy, 'local') {
99
constructor(private authService: AuthService) {
10-
super();
10+
super({
11+
usernameField: 'email',
12+
passwordField: 'password',
13+
});
1114
}
1215

13-
async validate(username: string, password: string): Promise<any> {
14-
const user = await this.authService.validateUser(username, password);
16+
async validate(email: string, password: string): Promise<any> {
17+
const user = await this.authService.validateUser(email, password);
1518
if (!user) {
1619
throw new UnauthorizedException();
1720
}

src/user/user.controller.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,18 +6,18 @@ import {
66
UseInterceptors,
77
ClassSerializerInterceptor,
88
} from '@nestjs/common';
9-
import { AuthGuard } from '@nestjs/passport';
109

1110
import { Request } from 'express';
1211

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

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

20-
@UseGuards(AuthGuard())
20+
@UseGuards(JwtAuthGuard)
2121
@UseInterceptors(ClassSerializerInterceptor)
2222
@Get('me')
2323
getMyProfile(@Req() req: Request): Promise<GetMeOutput> {

src/user/user.module.ts

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
import { Module } from '@nestjs/common';
22
import { TypeOrmModule } from '@nestjs/typeorm';
3-
import { PassportModule } from '@nestjs/passport';
43

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

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

1413
@Module({
15-
imports: [
16-
SharedModule,
17-
TypeOrmModule.forFeature([User]),
18-
PassportModule.register({ defaultStrategy: 'jwt' }),
19-
],
14+
imports: [SharedModule, TypeOrmModule.forFeature([User])],
2015
providers: [UserService, JwtStrategy],
2116
controllers: [UserController],
2217
exports: [UserService],

0 commit comments

Comments
 (0)