Created
September 17, 2021 12:23
-
-
Save ScreamZ/81833c07b0871fa0f19ac0eb6b3bc374 to your computer and use it in GitHub Desktop.
This file contains 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