Skip to content

Commit

Permalink
Update basic-auth.middleware.ts with bcrypt hashing (#782)
Browse files Browse the repository at this point in the history
  • Loading branch information
vincenzodomina authored Jun 30, 2024
1 parent 6172e9d commit 42ca519
Showing 1 changed file with 41 additions and 18 deletions.
59 changes: 41 additions & 18 deletions examples/with-nestjs/src/queues/basic-auth.middleware.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,47 @@
import { NestMiddleware } from '@nestjs/common';
import { Injectable, NestMiddleware } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { NextFunction, Request, Response } from 'express';
import * as bcrypt from 'bcrypt';

@Injectable()
export class BasicAuthMiddleware implements NestMiddleware {
private readonly username = 'user';
private readonly password = 'password';
private readonly encodedCreds = Buffer.from(
this.username + ':' + this.password,
).toString('base64');

use(req: Request, res: Response, next: NextFunction) {
const reqCreds = req.get('authorization')?.split('Basic ')?.[1] ?? null;

if (!reqCreds || reqCreds !== this.encodedCreds) {
res.setHeader(
'WWW-Authenticate',
'Basic realm="Your realm", charset="UTF-8"',
);
res.sendStatus(401);
} else {
next();
private readonly username: string;
private readonly passwordHash: string;

constructor(private readonly configService: ConfigService) {
this.username = this.configService.get<string>('BULL_BOARD_USERNAME') || '';
this.passwordHash = this.configService.get<string>('BULL_BOARD_PASSWORD_HASH') || '';
}

async use(req: Request, res: Response, next: NextFunction): Promise<void> {
const authHeader = req.get('authorization');

if (!authHeader || !authHeader.startsWith('Basic ')) {
this.sendUnauthorizedResponse(res);
return;
}

const encodedCreds = authHeader.split(' ')[1];
const decodedCreds = Buffer.from(encodedCreds, 'base64').toString('utf-8');
const [username, password] = decodedCreds.split(':');

if (!this.username || !this.passwordHash || username !== this.username) {
this.sendUnauthorizedResponse(res);
return;
}

const isPasswordValid = await await bcrypt.compare(password, this.passwordHash);

if (!isPasswordValid) {
this.sendUnauthorizedResponse(res);
return;
}

next();
}

private sendUnauthorizedResponse(res: Response): void {
res.setHeader('WWW-Authenticate', 'Basic realm="Restricted Area", charset="UTF-8"');
res.sendStatus(401);
}
}

0 comments on commit 42ca519

Please sign in to comment.