File size: 5,825 Bytes
09801ca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
/**
 * Auth Context - PRODUCTION READY
 * Provides auth state throughout the app
 */

import { createContext, useContext, useEffect, useState, ReactNode, useMemo } from 'react';
import { auth } from '../lib/auth-client';

export interface User {
    id: string;
    email?: string;
    user_metadata?: any;
    app_metadata?: any;
    [key: string]: any;
}

export interface Session {
    access_token: string;
    refresh_token?: string;
    expires_in?: number;
    expires_at?: number;
    token_type?: string;
    user: User;
}

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

interface AuthContextType extends AuthState {
    signUp: (email: string, password: string, metadata?: Record<string, any>) => Promise<any>;
    signIn: (email: string, password: string) => Promise<any>;
    signInWithMagicLink: (email: string) => Promise<any>;
    signInWithGoogle: () => Promise<any>;
    signInWithGithub: () => Promise<any>;
    signOut: () => Promise<void>;
}

const AuthContext = createContext<AuthContextType | undefined>(undefined);

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

    useEffect(() => {
        let isMounted = true;

        // Get initial session
        auth.getSession().then(({ data: { session } }) => {
            if (!isMounted) return;

            if (session) {
                setState({
                    user: session.user,
                    session,
                    loading: false,
                    isAuthenticated: true
                });
                localStorage.setItem('userId', session.user.id);
            } else {
                setState(s => ({ ...s, loading: false }));
            }
        });

        // Listen for auth changes
        const { data: { subscription } } = auth.onAuthStateChange((_event, session) => {
            if (!isMounted) return;

            if (session) {
                setState({
                    user: session.user,
                    session,
                    loading: false,
                    isAuthenticated: true
                });
                localStorage.setItem('userId', session.user.id);
            } else {
                setState({
                    user: null,
                    session: null,
                    loading: false,
                    isAuthenticated: false
                });
                localStorage.removeItem('userId');
            }
        });

        // Timeout
        setTimeout(() => {
            if (isMounted) {
                setState(s => s.loading ? { ...s, loading: false } : s);
            }
        }, 2000);

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

    const updateAuthState = async () => {
        const { data: { session } } = await auth.getSession();
        if (session) {
            setState({
                user: session.user,
                session,
                loading: false,
                isAuthenticated: true
            });
            localStorage.setItem('userId', session.user.id);
        }
    };

    const signUp = async (email: string, password: string, metadata?: Record<string, any>) => {
        const result = await auth.signUp(email, password, metadata);
        if (!result.error) await updateAuthState();
        return { error: result.error };
    };

    const signIn = async (email: string, password: string) => {
        const result = await auth.signIn(email, password);
        if (!result.error) await updateAuthState();
        return { error: result.error };
    };

    const signInWithMagicLink = async (email: string) => {
        const result = await auth.signInWithMagicLink(email);
        return { error: result.error };
    };

    const signInWithGoogle = async () => {
        const result = await auth.signInWithOAuth('google');
        return { error: result.error };
    };

    const signInWithGithub = async () => {
        const result = await auth.signInWithOAuth('github');
        return { error: result.error };
    };

    const signOut = async () => {
        try {
            // Sign out from auth service
            await auth.signOut();
        } catch (error) {
            console.error('Sign out error:', error);
        }

        // Clear all user-related localStorage
        localStorage.removeItem('userId');
        localStorage.removeItem('ai-analyst-storage-v2'); // Zustand store

        // Clear any user profile data
        const keys = Object.keys(localStorage);
        keys.forEach(key => {
            if (key.startsWith('userProfile_') || key.startsWith('userPreferences_')) {
                localStorage.removeItem(key);
            }
        });

        // Clear session - force clear any auth storage
        const authKeys = keys.filter(key =>
            key.startsWith('sb-') ||
            key.includes('auth')
        );
        authKeys.forEach(key => localStorage.removeItem(key));

        // Redirect to landing page
        window.location.href = '/';
    };

    const value = useMemo(() => ({
        ...state,
        signUp,
        signIn,
        signInWithMagicLink,
        signInWithGoogle,
        signInWithGithub,
        signOut
    }), [state]);

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

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

export default AuthContext;