UNPKG

kaven-utils

Version:

Utils for Node.js.

63 lines (62 loc) 2.42 kB
/******************************************************************** * @author: Kaven * @email: kaven@wuwenkai.com * @website: http://blog.kaven.xyz * @file: [Kaven-Utils] /src/net/authentication/KavenBasicAuthentication.ts * @create: 2019-03-26 13:54:54.865 * @modify: 2025-10-14 22:58:04.870 * @version: 6.1.0 * @times: 35 * @lines: 78 * @copyright: Copyright © 2019-2025 Kaven. All Rights Reserved. * @description: [description] * @license: [license] ********************************************************************/ import { TrimStart } from "kaven-basic"; import { KavenAuthentication } from "./KavenAuthentication.js"; export class KavenBasicAuthentication extends KavenAuthentication { Name = "Basic"; async Authenticate(req) { try { const authStr = req.authorization; if (!authStr || !authStr.startsWith(this.Name)) { return false; } let authentication = TrimStart(authStr, this.Name, 1).trimStart(); authentication = (Buffer.from(authentication, "base64")).toString("utf8"); const loginInfo = authentication.split(":"); const [username, password] = loginInfo; const key = `${username}${req.ip ?? ""}`; if (!this.CanAuthenticate(key)) { return false; } if (username !== this.UserName) { this.AddRecord(key, false); return false; } if (password !== this.Password) { this.AddRecord(key, false); return false; } this.AddRecord(key, true); return true; } catch (ex) { this.Logger?.Warn(ex); return false; } } Update(response) { response.AddHeader(this.ResponseHeaderName, `${this.Name} realm="${this.Realm}"`); return response; } static CreateHeader(username, password) { // Combine username and password with a colon const credentials = `${username}:${password}`; // Encode credentials in Base64 const base64Credentials = Buffer.from(credentials, "utf-8").toString("base64"); // Construct the Basic Authentication header const basicAuthHeader = `Basic ${base64Credentials}`; return basicAuthHeader; } }