Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enhance basic-auth.middleware example with password hashing and env variables #782

Merged
merged 1 commit into from
Jun 30, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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);
}
}