Broken access control often means a page shows any record whose id you type. The fix is to check that the record belongs to the person asking.
What to build
Answer requests for invoices, showing each only to its owner.
Requirements
- Line 1: N. Then N invoices
id owner amount. - Each remaining line is a request
user id. - If the invoice exists and belongs to the user, print
user sees id: amount taka. - Otherwise print
user asked for id: 404 not found(the same answer whether the invoice is missing or someone else's).
Input
As described.
Output
One line per request.
Constraints
Up to 50 invoices and 50 requests. Names have no spaces.
Example
Input:
2
101 rahim 1200
102 anika 560
rahim 101
rahim 102
Output:
rahim sees 101: 1200 taka
rahim asked for 102: 404 not found
Why it works
Answering not found in both cases checks ownership and also hides which invoice numbers exist, so changing the id in a request reveals nothing.
Examples
Example 1 · Input
2 101 rahim 1200 102 anika 560 rahim 101 rahim 102
Expected output
rahim sees 101: 1200 taka rahim asked for 102: 404 not found
Example 2 · Input
1 7 mina 50 mina 8
Expected output
mina asked for 8: 404 not found
Hints
Hint 1
Store invoices in an object keyed by id.
Hint 2
Check the owner before printing anything about the invoice.
Solution
Show one correct solution (try it yourself first)
const n = Number(prompt());
const invoices = {};
for (let k = 0; k < n; k++) {
const [id, owner, amount] = prompt().trim().split(/\s+/);
invoices[id] = { owner, amount };
}
let line = prompt();
while (line !== null) {
if (line.trim()) {
const [user, id] = line.trim().split(/\s+/);
const inv = Object.prototype.hasOwnProperty.call(invoices, id) ? invoices[id] : null;
console.log(inv && inv.owner === user ? `${user} sees ${id}: ${inv.amount} taka` : `${user} asked for ${id}: 404 not found`);
}
line = prompt();
}
▶ Open this solution in the compiler, then press Visualize to watch it run step by step