Secure function anti-pattern antics
JavaScript
const log = msg => document.getElementById('out').textContent += msg + '\n';
function fnA() {
secureFn();
}
function fnB() {
secureFn();
}
function secureFn() {
const allowedCallers = ['fnB'],
[_, callerStack] = (new Error()).stack.split('\n'),
callerFn = callerStack.replace(/@.*$/, '');
if (!allowedCallers.includes(callerFn)) {
throw new Error(`This function is a secure function, "${callerFn}" is not allowed to call it.`)
}
else {
log(`Success! ${callerFn} called this function securely.`)
}
}
function tryCalling(fn) {
try {
fn();
}
catch(e) {
log(e.message);
}
}
tryCalling(fnA);
tryCalling(fnB);