Skip to content

Instantly share code, notes, and snippets.

@ScreamZ
Created September 17, 2021 12:23
Show Gist options
  • Save ScreamZ/81833c07b0871fa0f19ac0eb6b3bc374 to your computer and use it in GitHub Desktop.
Save ScreamZ/81833c07b0871fa0f19ac0eb6b3bc374 to your computer and use it in GitHub Desktop.
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