Check CSRF tokens

A server that uses CSRF tokens accepts a state-changing request only if it carries the token stored in that session.

What to build

Accept or reject requests by their session cookie and CSRF token.

Requirements

  • Line 1: N, then N sessions cookie user token.
  • Each remaining line is a request cookie token amount (the token may be - for none).
  • Print rejected: not logged in if the cookie is unknown, rejected: bad token if the token is missing or wrong, otherwise sent AMOUNT for USER.

Input

As described.

Output

One line per request.

Constraints

Up to 20 sessions and 50 requests.

Example

Input:

1
sess-abc rahim k9Fq2xT7
sess-abc k9Fq2xT7 500
sess-abc - 9000

Output:

sent 500 for rahim
rejected: bad token

Why it works

Another site can make the browser send the cookie but cannot read the token from the real form, so requiring the matching token tells real form posts from forged ones.

Examples

Example 1 · Input
1
sess-abc rahim k9Fq2xT7
sess-abc k9Fq2xT7 500
sess-abc - 9000
Expected output
sent 500 for rahim
rejected: bad token
Example 2 · Input
1
s1 anika t1
zzz t1 5
Expected output
rejected: not logged in

Hints

Hint 1

Look the session up by cookie first, then compare tokens.

Solution

Show one correct solution (try it yourself first)
const n = Number(prompt());
const sessions = new Map();
for (let k = 0; k < n; k++) {
  const [cookie, user, token] = prompt().trim().split(/\s+/);
  sessions.set(cookie, { user, token });
}
let line = prompt();
while (line !== null) {
  if (line.trim()) {
    const [cookie, token, amount] = line.trim().split(/\s+/);
    const s = sessions.get(cookie);
    if (!s) console.log("rejected: not logged in");
    else if (token !== s.token) console.log("rejected: bad token");
    else console.log(`sent ${amount} for ${s.user}`);
  }
  line = prompt();
}

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

Lesson: Cross-site request forgery (CSRF) →