UNPKG

kaven-utils

Version:

Utils for Node.js.

63 lines (62 loc) 2.45 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: 2023-12-07 17:36:42.385 * @version: 5.4.0 * @times: 31 * @lines: 78 * @copyright: Copyright © 2019-2023 Kaven. All Rights Reserved. * @description: [description] * @license: [license] ********************************************************************/ import { InternalLogger } from "../../KavenUtility.Internal.js"; 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 = authStr.TrimStart(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) { InternalLogger()?.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; } }