summaryrefslogtreecommitdiff
path: root/makima/frontend/src/contexts/AuthContext.tsx
blob: ce2724bad3f17cc016825625bc931eab2590bb6a (plain) (blame)
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
import {
  createContext,
  useContext,
  useEffect,
  useState,
  useCallback,
  type ReactNode,
} from "react";
import { supabase, isAuthConfigured, type Session, type User } from "../lib/supabase";

interface AuthState {
  user: User | null;
  session: Session | null;
  isLoading: boolean;
  isAuthenticated: boolean;
  isAuthConfigured: boolean;
}

interface AuthContextValue extends AuthState {
  /** Get the current access token for API calls */
  getAccessToken: () => string | null;
  /** Sign in with email and password */
  signIn: (email: string, password: string) => Promise<{ error: Error | null }>;
  /** Sign up with email and password */
  signUp: (email: string, password: string) => Promise<{ error: Error | null }>;
  /** Sign out */
  signOut: () => Promise<void>;
  /** Sign in with OAuth provider */
  signInWithOAuth: (provider: "github" | "google") => Promise<{ error: Error | null }>;
}

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

export function AuthProvider({ children }: { children: ReactNode }) {
  const [state, setState] = useState<AuthState>({
    user: null,
    session: null,
    isLoading: true,
    isAuthenticated: false,
    isAuthConfigured: isAuthConfigured(),
  });

  // Initialize auth state
  useEffect(() => {
    if (!supabase) {
      // Auth not configured - allow unauthenticated access
      setState((prev) => ({
        ...prev,
        isLoading: false,
        isAuthenticated: true, // Allow access when auth is not configured
      }));
      return;
    }

    // Get initial session
    supabase.auth.getSession().then(({ data: { session } }) => {
      setState({
        user: session?.user ?? null,
        session,
        isLoading: false,
        isAuthenticated: !!session,
        isAuthConfigured: true,
      });
    });

    // Listen for auth changes
    const {
      data: { subscription },
    } = supabase.auth.onAuthStateChange((_event, session) => {
      setState((prev) => ({
        ...prev,
        user: session?.user ?? null,
        session,
        isAuthenticated: !!session,
      }));
    });

    return () => subscription.unsubscribe();
  }, []);

  const getAccessToken = useCallback((): string | null => {
    return state.session?.access_token ?? null;
  }, [state.session]);

  const signIn = useCallback(
    async (email: string, password: string): Promise<{ error: Error | null }> => {
      if (!supabase) {
        return { error: new Error("Auth not configured") };
      }
      const { error } = await supabase.auth.signInWithPassword({ email, password });
      return { error: error ? new Error(error.message) : null };
    },
    []
  );

  const signUp = useCallback(
    async (email: string, password: string): Promise<{ error: Error | null }> => {
      if (!supabase) {
        return { error: new Error("Auth not configured") };
      }
      const { error } = await supabase.auth.signUp({ email, password });
      return { error: error ? new Error(error.message) : null };
    },
    []
  );

  const signOut = useCallback(async () => {
    // Always clear local state first
    setState((prev) => ({
      ...prev,
      user: null,
      session: null,
      isAuthenticated: false,
    }));

    // Clear Supabase storage directly in case signOut API fails
    const storageKey = `sb-${import.meta.env.VITE_SUPABASE_URL?.split('//')[1]?.split('.')[0]}-auth-token`;
    localStorage.removeItem(storageKey);

    // Try to call signOut API (may fail if token is invalid, that's OK)
    if (supabase) {
      await supabase.auth.signOut({ scope: 'local' }).catch(() => {});
    }
  }, []);

  const signInWithOAuth = useCallback(
    async (provider: "github" | "google"): Promise<{ error: Error | null }> => {
      if (!supabase) {
        return { error: new Error("Auth not configured") };
      }
      const { error } = await supabase.auth.signInWithOAuth({
        provider,
        options: {
          redirectTo: window.location.origin,
        },
      });
      return { error: error ? new Error(error.message) : null };
    },
    []
  );

  const value: AuthContextValue = {
    ...state,
    getAccessToken,
    signIn,
    signUp,
    signOut,
    signInWithOAuth,
  };

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

export function useAuth(): AuthContextValue {
  const context = useContext(AuthContext);
  if (!context) {
    throw new Error("useAuth must be used within an AuthProvider");
  }
  return context;
}