Role-based access

Many apps decide access by role: a student may read courses, a teacher may also edit them, an admin may do everything. Anything not granted is denied.

What to build

Decide each request from a table of role permissions, with deny by default.

Requirements

  • Line 1: N. Then N lines role action granting one action to one role; the action * grants everything.
  • Line N + 2: M. Then M lines user role.
  • Each remaining line is a request user action.
  • Print allow if the user has a role that grants the action (or *), otherwise deny. A user may have several roles; an unknown user is denied.

Input

As described.

Output

One word per request.

Constraints

Up to 50 grants, 50 user-role lines and 50 requests.

Example

Input:

3
student read
teacher read
teacher edit
2
rahim student
mina teacher
rahim read
rahim edit
mina edit

Output:

allow
deny
allow

Why it works

Collecting every action each user's roles grant and refusing everything else is deny by default: a forgotten grant blocks an action instead of exposing it.

Examples

Example 1 · Input
3
student read
teacher read
teacher edit
2
rahim student
mina teacher
rahim read
rahim edit
mina edit
Expected output
allow
deny
allow
Example 2 · Input
1
admin *
1
root admin
root delete
guest read
Expected output
allow
deny

Hints

Hint 1

Keep a Map from role to a Set of actions, and a Map from user to a list of roles.

Solution

Show one correct solution (try it yourself first)
const n = Number(prompt());
const grants = new Map();
for (let k = 0; k < n; k++) {
  const [role, action] = prompt().trim().split(/\s+/);
  if (!grants.has(role)) grants.set(role, new Set());
  grants.get(role).add(action);
}
const m = Number(prompt());
const roles = new Map();
for (let k = 0; k < m; k++) {
  const [user, role] = prompt().trim().split(/\s+/);
  if (!roles.has(user)) roles.set(user, []);
  roles.get(user).push(role);
}
let line = prompt();
while (line !== null) {
  if (line.trim()) {
    const [user, action] = line.trim().split(/\s+/);
    const ok = (roles.get(user) ?? []).some((r) => grants.has(r) && (grants.get(r).has(action) || grants.get(r).has("*")));
    console.log(ok ? "allow" : "deny");
  }
  line = prompt();
}

▶ Open this solution in the compiler, then press Visualize to watch it run step by step

Lesson: The OWASP Top 10 and broken access control →