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:
- Import
LiveErroralongsidelive - Add a
loggedInSet to track authenticated names - Create a
login(name, password)RPC that checks if the password is'secret'- throwLiveError('UNAUTHORIZED', 'Wrong password')if it's not, otherwise add the name to the Set - Add a guard to
addNotethat throws if the author isn't in theloggedInSet - Add a
logout(name)RPC that removes the name from the Set - 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