call-test-web/pjsipauth.js
2024-12-08 21:11:23 -07:00

62 lines
1.9 KiB
JavaScript

/**
* Parses a config file into an array of objects.
* @param {string} configText - The text content of the config file.
* @returns {Array<Object>} - Parsed objects representing each section.
*/
function parseConfig(configText) {
const lines = configText.split(/\r?\n/); // Split text into lines
const sections = [];
let currentSection = null;
for (const line of lines) {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith(';')) {
// Skip empty lines or comments
continue;
}
if (trimmed.startsWith('[') && trimmed.endsWith(']')) {
// New section header
if (currentSection) {
sections.push(currentSection);
}
currentSection = {
name: trimmed.slice(1, -1),
properties: {}
};
} else if (currentSection) {
const [key, value] = trimmed.split('=', 2).map(part => part.trim());
if (key && value !== undefined) {
currentSection.properties[key] = value;
}
}
}
// Push the last section if it exists
if (currentSection) {
sections.push(currentSection);
}
// Transform sections into desired objects
return sections.map(section => ({
name: section.name,
...section.properties
}));
}
/**
* Validates a username and password against parsed config data.
* @param {Array<Object>} configData - Parsed config data.
* @param {string} username - The username to validate.
* @param {string} password - The password to validate.
* @returns {boolean} - True if the credentials are valid, false otherwise.
*/
function validateCredentials(configData, username, password) {
return configData.some(entry => entry.username === username && entry.password === password);
}
module.exports = {
validateCredentials,
parseConfig
}