Spaces:
Running

File size: 2,768 Bytes
03608f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
"use client";

import {
  createContext,
  useCallback,
  useContext,
  useEffect,
  useMemo,
  useState,
  type ReactNode,
} from "react";

import { api } from "@/lib/api";
import * as session from "@/lib/session";
import type { Me, Role } from "@/lib/types";

type Status = "loading" | "anonymous" | "authenticated";

interface AuthValue {
  status: Status;
  me: Me | null;
  login: (email: string, password: string) => Promise<void>;
  signup: (business: string, email: string, password: string) => Promise<void>;
  logout: () => Promise<void>;
  switchTenant: (tenantId: string) => Promise<void>;
  reload: () => Promise<void>;
  hasRole: (min: Role) => boolean;
}

export const ROLE_RANK: Record<Role, number> = {
  viewer: 0,
  agent_operator: 1,
  manager: 2,
  owner: 3,
};

const AuthContext = createContext<AuthValue | null>(null);

export function AuthProvider({ children }: { children: ReactNode }) {
  const [status, setStatus] = useState<Status>("loading");
  const [me, setMe] = useState<Me | null>(null);

  const loadMe = useCallback(async () => {
    try {
      const m = await api<Me>("/me");
      setMe(m);
      setStatus("authenticated");
    } catch {
      setMe(null);
      setStatus("anonymous");
    }
  }, []);

  useEffect(() => {
    let alive = true;
    // A reload has no access token in memory: trade the httpOnly refresh cookie for one.
    session.refreshAccessToken().then((token) => {
      if (!alive) return;
      if (token) void loadMe();
      else setStatus("anonymous");
    });
    const off = session.onSessionExpired(() => {
      setMe(null);
      setStatus("anonymous");
    });
    return () => {
      alive = false;
      off();
    };
  }, [loadMe]);

  const value = useMemo<AuthValue>(
    () => ({
      status,
      me,
      login: async (email, password) => {
        await session.login(email, password);
        await loadMe();
      },
      signup: async (business, email, password) => {
        await session.signup(business, email, password);
        await loadMe();
      },
      logout: async () => {
        await session.logout();
        setMe(null);
        setStatus("anonymous");
      },
      switchTenant: async (tenantId) => {
        await session.switchTenant(tenantId);
        await loadMe();
      },
      reload: loadMe,
      hasRole: (min) => (me ? ROLE_RANK[me.role] >= ROLE_RANK[min] : false),
    }),
    [status, me, loadMe],
  );

  return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
}

export function useAuth(): AuthValue {
  const v = useContext(AuthContext);
  if (!v) throw new Error("useAuth outside AuthProvider");
  return v;
}