Created
November 17, 2021 20:31
-
-
Save markodayan/f5912199662f7b48f7c1f56f11048722 to your computer and use it in GitHub Desktop.
Timing Attack protection in Nestjs project
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { BasicStrategy as Strategy } from 'passport-http'; | |
import { Injectable, InternalServerErrorException, UnauthorizedException } from '@nestjs/common'; | |
import { PassportStrategy } from '@nestjs/passport'; | |
import { ConfigService } from '@nestjs/config'; | |
import { timingSafeEqual } from 'crypto'; | |
@Injectable() | |
export class AdminBasicStrategy extends PassportStrategy(Strategy) { | |
constructor(private readonly configService: ConfigService) { | |
super(); | |
} | |
public validate = async (username: string, password: string): Promise<boolean> => { | |
const adminUsername = this.configService.get<string>('ADMIN_USER'); | |
const adminPassword = this.configService.get<string>('ADMIN_PASSWORD'); | |
if (!adminUsername || !adminPassword) { | |
throw new InternalServerErrorException('Missing configuration on AdminBasicStrategy'); | |
} | |
if ( | |
adminUsername.length === username.length && | |
adminPassword.length === password.length && | |
timingSafeEqual(Buffer.from(adminUsername), Buffer.from(username)) && | |
timingSafeEqual(Buffer.from(adminPassword), Buffer.from(password)) | |
) { | |
return true; | |
} | |
throw new UnauthorizedException(); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment