viewer-access.ts 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import { getCachedMembership } from './cached-session'
  2. import { getAuthContext } from './get-auth-context'
  3. import { hasPermission, PermissionAction, type PermissionSubject } from './permissions'
  4. import type { ActionResult } from './with-auth'
  5. /**
  6. * What the person looking at a page may read, asked once, before the page
  7. * asks for anything.
  8. *
  9. * A page that shows several things at once (the dashboard shows sixteen) used
  10. * to ask for all of them and let `withAuth` refuse the ones this role may not
  11. * have. That is correct on screen, because a refused card is simply not
  12. * drawn, and wrong everywhere else: each refusal is a query that was never
  13. * going to be answered and a "permission denied" row in the audit log. A
  14. * Member opening the dashboard wrote twelve of them per visit, which buries
  15. * the one refusal an owner would actually want to see.
  16. *
  17. * So the page asks here first and does not make the call. The rules are the
  18. * ones `withAuth` applies, in the same order: a super admin, an owner, an
  19. * admin and an admin role read everything; anybody else reads what their role
  20. * was given, and somebody with no role reads nothing.
  21. *
  22. * This decides what to ask for, never what is allowed. `withAuth` still
  23. * guards every action, so a page that gets this wrong is refused as before.
  24. */
  25. export interface ViewerAccess {
  26. reads(subject: PermissionSubject): boolean
  27. }
  28. export async function getViewerAccess(): Promise<ViewerAccess> {
  29. const auth = await getAuthContext()
  30. if (!auth) return { reads: () => false }
  31. if (auth.isAdmin) return { reads: () => true }
  32. const membership = await getCachedMembership(auth.userId)
  33. const granted = membership?.customRole?.permissions ?? []
  34. return {
  35. reads: (subject) => hasPermission(granted, { action: PermissionAction.READ, subject }),
  36. }
  37. }
  38. /**
  39. * Makes the call when the viewer may read `subject`, and otherwise answers as
  40. * `withAuth` would have, without the query and without the audit row. The
  41. * page handles both the same way, which is the point.
  42. */
  43. export function readIfAllowed<T extends ActionResult<unknown>>(
  44. access: ViewerAccess,
  45. subject: PermissionSubject,
  46. call: () => Promise<T>
  47. ): Promise<T> {
  48. if (access.reads(subject)) return call()
  49. return Promise.resolve({
  50. success: false,
  51. error: 'Insufficient permissions',
  52. forbidden: true,
  53. } as T)
  54. }