0/12
9. Authentication

Lesson 9: Authentication

Right now, anyone can add notes without identifying themselves. Let's add a login system with guards that reject unauthorized users.

The guard pattern

A guard is just an if check at the top of an RPC that throws LiveError when the caller shouldn't have access:

export const doSomething = live((ctx, name) => {
  if (!loggedIn.has(name)) {
    throw new LiveError('UNAUTHORIZED', 'Log in first');
  }
  // ... proceed
});

Try it

The starter code lets anyone add notes. Your task:

  1. Import LiveError alongside live
  2. Add a loggedIn Set to track authenticated names
  3. Create a login(name, password) RPC that checks if the password is 'secret' - throw LiveError('UNAUTHORIZED', 'Wrong password') if it's not, otherwise add the name to the Set
  4. Add a guard to addNote that throws if the author isn't in the loggedIn Set
  5. Add a logout(name) RPC that removes the name from the Set
  6. Update the component: show a login form first, then the note form and a logout button after login. Wrap RPC calls in try/catch to display errors.

Try it with both users - log in as different names and watch the notes stream sync between them. Try a wrong password to see the error. Log out and verify you can't add notes anymore.

WebSocket
0
No messages yet
User A
User B