A Session Lookup
Part of the Auth and Security section of Coddy's Node.js journey. Lesson 9 of 24.
A session id points to a stored session, and that session points to an account. The key itself is not a username. Resolve both links before deciding who made the request.
// tickets: {key: 'example-key', memberId: 7}
const ticket = tickets.find(t => t.key === receivedKey);
const member = ticket && members.find(m => m.id === ticket.memberId);Return no user when either lookup misses. Real session ids are long random values so other people cannot guess them; the short keys here make the relationship easy to inspect. The following project uses MongoDB collections and findOne for these two lookups instead of arrays.
Challenge
EasyIn exercise.js, use the supplied sessions and users arrays. Find the session for sid, then the user whose id matches its userId. Return the username in user, or null if either lookup fails.
Try GET /result?sid=key-a: {"user":"ada"}. A username such as ?sid=ada proves nothing and returns null. ?sid=orphan also returns null because its account is missing.
Try it yourself
const sessions = [
{ id: 'key-a', userId: 10 },
{ id: 'key-b', userId: 20 },
{ id: 'orphan', userId: 99 },
];
const users = [
{ id: 10, username: 'ada' },
{ id: 20, username: 'bo' },
];
export function exercise({ sid }) {
return { user: sid };
}
All lessons in Auth and Security
Practice on your own: Express playground