kaven-utils
Version:
Utils for Node.js.
60 lines (59 loc) • 2.05 kB
JavaScript
/********************************************************************
* @author: Kaven
* @email: kaven@wuwenkai.com
* @website: http://blog.kaven.xyz
* @file: [Kaven-Utils] /src/net/authentication/KavenAuthorizationRecords.ts
* @create: 2022-09-20 10:55:20.367
* @modify: 2022-09-20 20:56:38.260
* @version: 4.3.6
* @times: 3
* @lines: 69
* @copyright: Copyright © 2022 Kaven. All Rights Reserved.
* @description: [description]
* @license: [license]
********************************************************************/
import { TimeUnit, ToSeconds } from "kaven-basic";
import { KavenAuthorizationRecord } from "./KavenAuthorizationRecord.js";
/**
* @since 4.3.6
* @version 2022-09-20
*/
export class KavenAuthorizationRecords {
records = new Map();
// <seconds, attempts>
AuthorizationLimits = new Map();
constructor() {
this.AuthorizationLimits.set(60, 10);
this.AuthorizationLimits.set(ToSeconds(10, TimeUnit.minutes), 20);
this.AuthorizationLimits.set(ToSeconds(1, TimeUnit.hours), 30);
this.AuthorizationLimits.set(ToSeconds(1, TimeUnit.days), 50);
}
AddRecord(key, success) {
const record = new KavenAuthorizationRecord(key, success);
const records = this.GetRecords(key);
if (records) {
records.push(record);
}
else {
this.records.set(key, [record]);
}
}
GetRecords(key) {
return this.records.get(key);
}
CanAuthenticate(key) {
const records = this.GetRecords(key);
if (!records) {
return true;
}
const now = new Date();
for (const [seconds, attempts] of this.AuthorizationLimits) {
const startDate = now.SubtractSeconds(seconds);
const failedAttempts = records.filter(p => !p.success && p.date >= startDate).length;
if (failedAttempts > attempts) {
return false;
}
}
return true;
}
}