Skip to content

Commit

Permalink
setup jwt strategy
Browse files Browse the repository at this point in the history
  • Loading branch information
ShaalanMarwan committed May 1, 2022
1 parent 93052bc commit 32d315d
Show file tree
Hide file tree
Showing 7 changed files with 251 additions and 29 deletions.
5 changes: 5 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,16 @@
"dependencies": {
"@nestjs/common": "^7.6.15",
"@nestjs/core": "^7.6.15",
"@nestjs/jwt": "^8.0.0",
"@nestjs/passport": "^8.2.1",
"@nestjs/platform-express": "^7.6.15",
"@nestjs/typeorm": "^8.0.3",
"@types/passport-jwt": "^3.0.6",
"bcrypt": "^5.0.1",
"class-transformer": "^0.5.1",
"class-validator": "^0.13.2",
"passport": "^0.5.2",
"passport-jwt": "^4.0.0",
"pg": "^8.7.3",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
Expand Down
19 changes: 10 additions & 9 deletions src/auth/auth.controller.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,18 @@
import { Body, Controller, Post } from '@nestjs/common';
import { AuthService } from 'src/auth/auth.service';
import { AuthCredentialDto } from 'src/auth/dto/auth-credentials.dto';
import { JwtPayload } from 'src/auth/jwt-payload.interface';

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

@Post('/signup')
signup(@Body() authCredentialDto: AuthCredentialDto): Promise<void> {
return this.authService.signUp(authCredentialDto);
}
@Post('/signin')
signIn(@Body() authCredentialDto: AuthCredentialDto): Promise<string> {
return this.authService.sigIn(authCredentialDto);
}
@Post('/signup')
signup(@Body() authCredentialDto: AuthCredentialDto): Promise<void> {
return this.authService.signUp(authCredentialDto);
}
@Post('/signin')
signIn(@Body() authCredentialDto: AuthCredentialDto): Promise<JwtPayload> {
return this.authService.sigIn(authCredentialDto);
}
}
19 changes: 16 additions & 3 deletions src/auth/auth.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,23 @@ import { TypeOrmModule } from '@nestjs/typeorm';
import { UsersRepository } from 'src/auth/users.repository';
import { AuthController } from './auth.controller';
import { AuthService } from './auth.service';
import { PassportModule } from '@nestjs/passport';
import { JwtModule } from '@nestjs/jwt';
import { JwtStrategy } from 'src/auth/jwt.strategy';

@Module({
imports: [TypeOrmModule.forFeature([UsersRepository])],
controllers: [AuthController],
providers: [AuthService],
imports: [
PassportModule.register({ defaultStrategy: 'jwt' }),
JwtModule.register({
secret: 'nothing',
signOptions: {
expiresIn: 3600,
},
}),
TypeOrmModule.forFeature([UsersRepository]),
],
controllers: [AuthController],
providers: [AuthService, JwtStrategy],
exports: [JwtStrategy, PassportModule],
})
export class AuthModule {}
38 changes: 23 additions & 15 deletions src/auth/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,25 +3,33 @@ import { InjectRepository } from '@nestjs/typeorm';
import { AuthCredentialDto } from 'src/auth/dto/auth-credentials.dto';
import { UsersRepository } from 'src/auth/users.repository';
import * as bcrypt from 'bcrypt';
import { JwtService } from '@nestjs/jwt';
import { JwtPayload } from 'src/auth/jwt-payload.interface';

@Injectable()
export class AuthService {
constructor(
@InjectRepository(UsersRepository)
private usersRepository: UsersRepository,
) {}
constructor(
@InjectRepository(UsersRepository)
private usersRepository: UsersRepository,
private jwtService: JwtService,
) {}

async signUp(authCredentialDto: AuthCredentialDto): Promise<void> {
return await this.usersRepository.createUser(authCredentialDto);
}
async signUp(authCredentialDto: AuthCredentialDto): Promise<void> {
return await this.usersRepository.createUser(authCredentialDto);
}

async sigIn(authCredentialDto: AuthCredentialDto): Promise<string> {
const { password, username } = authCredentialDto;
const user = await this.usersRepository.findOne({ username });
if (user && (await bcrypt.compare(password, user.password))) {
return 'success';
} else {
throw new UnauthorizedException('please check your credential ');
async sigIn(authCredentialDto: AuthCredentialDto): Promise<JwtPayload> {
const { password, username } = authCredentialDto;
const user = await this.usersRepository.findOne({ username });
if (user && (await bcrypt.compare(password, user.password))) {
const payload = { username };
const accessToken: string = await this.jwtService.sign(payload);
return {
username,
accessToken,
};
} else {
throw new UnauthorizedException('please check your credential ');
}
}
}
}
4 changes: 4 additions & 0 deletions src/auth/jwt-payload.interface.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export interface JwtPayload {
accessToken: string;
username: string;
}
29 changes: 29 additions & 0 deletions src/auth/jwt.strategy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { InjectRepository } from '@nestjs/typeorm';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { JwtPayload } from 'src/auth/jwt-payload.interface';
import { User } from 'src/auth/user.entity';
import { UsersRepository } from 'src/auth/users.repository';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(
@InjectRepository(UsersRepository)
private usersRepository: UsersRepository,
) {
super({
secretOrKey: 'nothing',
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
});
}

async validate(payload: JwtPayload): Promise<User> {
const { username } = payload;
const user: User = await this.usersRepository.findOne({ username });
if (!user) {
throw new UnauthorizedException();
}
return user;
}
}
Loading

0 comments on commit 32d315d

Please sign in to comment.