portal-auth-provider.tsx 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. "use client";
  2. import { BrivenAuthProvider } from "@briven/auth/react";
  3. import {
  4. createContext,
  5. useCallback,
  6. useContext,
  7. useEffect,
  8. useMemo,
  9. useState,
  10. type ReactNode,
  11. } from "react";
  12. import { getBrivenAuth } from "@/lib/auth";
  13. import type { DemoSession } from "@/lib/auth-config";
  14. import {
  15. clearDemoSession,
  16. readDemoSession,
  17. writeDemoSession,
  18. } from "@/lib/demo-session";
  19. type PortalAuthContextValue = {
  20. brivenConfigured: boolean;
  21. demoSession: DemoSession | null;
  22. setDemoSession: (s: DemoSession) => void;
  23. clearDemo: () => void;
  24. refreshDemo: () => void;
  25. };
  26. const PortalAuthContext = createContext<PortalAuthContextValue | null>(null);
  27. function readInitialDemo(): DemoSession | null {
  28. if (typeof window === "undefined") return null;
  29. return readDemoSession();
  30. }
  31. export function PortalAuthProvider({ children }: { children: ReactNode }) {
  32. const client = useMemo(() => getBrivenAuth(), []);
  33. const [demoSession, setDemo] = useState<DemoSession | null>(readInitialDemo);
  34. const refreshDemo = useCallback(() => {
  35. setDemo(readDemoSession());
  36. }, []);
  37. useEffect(() => {
  38. const onChange = () => setDemo(readDemoSession());
  39. window.addEventListener("krypco-auth-change", onChange);
  40. window.addEventListener("storage", onChange);
  41. return () => {
  42. window.removeEventListener("krypco-auth-change", onChange);
  43. window.removeEventListener("storage", onChange);
  44. };
  45. }, []);
  46. const value: PortalAuthContextValue = {
  47. brivenConfigured: Boolean(client),
  48. demoSession,
  49. setDemoSession: (s) => {
  50. writeDemoSession(s);
  51. setDemo(s);
  52. },
  53. clearDemo: () => {
  54. clearDemoSession();
  55. setDemo(null);
  56. },
  57. refreshDemo,
  58. };
  59. const tree = (
  60. <PortalAuthContext.Provider value={value}>
  61. {children}
  62. </PortalAuthContext.Provider>
  63. );
  64. if (client) {
  65. return <BrivenAuthProvider value={client}>{tree}</BrivenAuthProvider>;
  66. }
  67. return tree;
  68. }
  69. export function usePortalAuth(): PortalAuthContextValue {
  70. const ctx = useContext(PortalAuthContext);
  71. if (!ctx) {
  72. throw new Error("usePortalAuth must be used inside PortalAuthProvider");
  73. }
  74. return ctx;
  75. }