30 lines
849 B
TypeScript
30 lines
849 B
TypeScript
import { Request, Response, NextFunction } from "express";
|
|
import { Encryptor } from "./encryptor";
|
|
|
|
export interface CustomRequest extends Request {
|
|
_user?: { username: string; password: string };
|
|
}
|
|
|
|
export function basicAuth(req: CustomRequest, res: Response, next: NextFunction) {
|
|
const authHeader = req.headers['authorization'];
|
|
|
|
if (!authHeader) {
|
|
return res.sendStatus(401);
|
|
}
|
|
|
|
const base64Credentials = authHeader.split(' ')[1];
|
|
const credentials = Buffer.from(base64Credentials, 'base64').toString('utf-8');
|
|
const [username, password] = credentials.split(':');
|
|
const safeString = Encryptor.makeFileSafeString(username);
|
|
|
|
if (safeString.length < 6) {
|
|
return res.sendStatus(401);
|
|
}
|
|
|
|
req._user = {
|
|
username,
|
|
password,
|
|
}
|
|
next();
|
|
};
|