Issue 1, untested
This commit is contained in:
80
code/lib/time.js
Normal file
80
code/lib/time.js
Normal file
@@ -0,0 +1,80 @@
|
||||
const rangeStringToArray = (str) => {
|
||||
// Split the string by hyphen
|
||||
const parts = str.split ("-");
|
||||
// Validate input format (two numbers separated by hyphen)
|
||||
if (parts.length !== 2 || isNaN (parts[0]) || isNaN (parts[1])) {
|
||||
return null; // Return null for invalid format
|
||||
}
|
||||
// Convert strings to numbers
|
||||
const start = parseInt (parts[0], 10);
|
||||
const end = parseInt (parts[1], 10);
|
||||
// Check if start is less than or equal to end (inclusive range)
|
||||
if (start > end) {
|
||||
return null; // Return null for invalid range
|
||||
}
|
||||
// Use Array.from() to create an array with sequence
|
||||
return Array.from ({ length: end - start + 1 }, (_, i) => start + i);
|
||||
};
|
||||
|
||||
const resolveRange = (str) => {
|
||||
const numberSets = str.split (","); // Split by commas
|
||||
const numbers = [];
|
||||
for (const set of numberSets) {
|
||||
// Check if it's a range
|
||||
if (set.includes ("-")) {
|
||||
const range = rangeStringToArray (set); // Use the previous function
|
||||
if (range) {
|
||||
numbers.push(...range); // Spread operator to add elements from range array
|
||||
}
|
||||
else {
|
||||
const num = parseInt(set, 10);
|
||||
// Check if conversion is successful (valid number)
|
||||
if (!isNaN(num)) {
|
||||
numbers.push(num);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return numbers;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
checkAuth: (rules = []) => {
|
||||
var authorised = false;
|
||||
if (rules.length > 0) {
|
||||
var now = new Date ();
|
||||
var minuteOfDay = (now.getHours () * 60) + now.getMinutes (); // 0 - 1439
|
||||
var day = now.getDay (); // 1 - 7
|
||||
var date = now.getDate (); // 1 - 31
|
||||
var month = now.getMonth () + 1; // 1 - 12
|
||||
var actions = [];
|
||||
rules.forEach ((rule) => {
|
||||
var valid = false;
|
||||
// Process rule
|
||||
var r = {
|
||||
startMinute: parseInt (rule.startTime.split (":")[0] * 60) + parseInt (rule.startTime.split (":")[1]),
|
||||
endMinute: parseInt (rule.endTime.split (":")[0] * 60) + parseInt (rule.endTime.split (":")[1]),
|
||||
days: resolveRange (rule.weekdays),
|
||||
dates: resolveRange (rule.dates),
|
||||
months: resolveRange (rule.months)
|
||||
}
|
||||
if (
|
||||
minuteOfDay >= r.startMinute &&
|
||||
minuteOfDay <= r.endMinute &&
|
||||
r.days.indexOf (day) !== -1 &&
|
||||
r.dates.indexOf (date) !== -1 &&
|
||||
r.months.indexOf (month) !== -1
|
||||
) {
|
||||
actions.push (rule.action.toLowerCase ());
|
||||
}
|
||||
});
|
||||
if (actions.indexOf ("allow")) {
|
||||
authorised = true;
|
||||
}
|
||||
if (actions.indexOf ("deny")) {
|
||||
authorised = false;
|
||||
}
|
||||
}
|
||||
return authorised;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user