opengovsg / starter-kit

A technical kit to quickly build new products
https://start.open.gov.sg
MIT License
36 stars 6 forks source link

feat: add better client-side auth state handling #185

Closed karrui closed 1 year ago

karrui commented 1 year ago

Problem

The current auth handling in the application is not ideal, relying on implicit redirects to the sign in page when error boundary catches a specific TRPC error.

image

Closes TOOL-118

Solution

This PR simplifies the auth state handling, by using an insecure cookie (so that both client and server can read a preliminary login state) that acts as a proxy for the (secure, and thus hidden from browsers) session cookie.

The new cookie is-logged-in will only be set when the user logs in, and removed when any 401 errors are retrieved. A new LoginStateProvider checks the new cookie and provides current login state to the entire application. Two new route guard components PublicPageWrapperand EnforceLoginStatePageWrapper is included for use in the Layouts or directly on the page itself to guard the page.

See AdminLayout and /pages/sign-in/index.tsx for examples.

Error handling has been centralised into the trpc initiation stage, where any 401 errors will:

  1. Stop retrying
  2. redirect the user to the login page, whilst keeping track of the current page so the user can be redirected back after logging in.
vercel[bot] commented 1 year ago

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
starter-kit ✅ Ready (Inspect) Visit Preview 💬 Add feedback Aug 29, 2023 10:38am
karrui commented 1 year ago

Moved back to localStorage because of the ability to emit events that all login state hooks are listening to. This allows react to react (geddit?) and rerender its children if needed.