File size: 4,939 Bytes
d15f07c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import React, { createContext, useContext, useState, useEffect, ReactNode } from 'react';
import { tracedFetch } from '../lib/api';

interface User {
  id: number;
  email: string;
  username?: string;
  full_name?: string;
  avatar_url?: string;
  oauth_provider?: string;
  state?: string;
  county?: string;
  city?: string;
  school_board?: string;
  profile_completed?: boolean;
  is_admin?: boolean;
}

interface AuthContextType {
  user: User | null;
  token: string | null;
  /** Start sign-in; `returnTo` (a URL on this site) is where it lands afterwards, the home page by default. */
  login: (provider: string, returnTo?: string) => void;
  logout: () => void;
  refreshUser: () => Promise<void>;
  isAuthenticated: boolean;
  isLoading: boolean;
  authError: string | null;
  clearAuthError: () => void;
}

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

export const AuthProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
  const [user, setUser] = useState<User | null>(null);
  const [token, setToken] = useState<string | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [authError, setAuthError] = useState<string | null>(null);

  // Use /api for both dev and prod - Vite proxy handles dev routing
  const API_URL = '/api';

  // Load user from localStorage on mount
  useEffect(() => {
    // Check for token in URL FIRST (OAuth callback)
    const urlParams = new URLSearchParams(window.location.search);
    const urlToken = urlParams.get('token');
    const urlError = urlParams.get('error');
    
    if (urlError) {
      // Show OAuth error to user
      setAuthError(urlError);
      // Clean URL (remove error from address bar)
      window.history.replaceState({}, document.title, window.location.pathname);
      setIsLoading(false);
      return;
    }
    
    if (urlToken) {
      localStorage.setItem('auth_token', urlToken);
      setToken(urlToken);
      fetchUser(urlToken);
      
      // Clean URL (remove token from address bar)
      window.history.replaceState({}, document.title, window.location.pathname);
      return; // Exit early, fetchUser will handle loading state
    }
    
    // Check for stored token
    const storedToken = localStorage.getItem('auth_token');
    
    if (storedToken) {
      setToken(storedToken);
      fetchUser(storedToken);
    } else {
      setIsLoading(false);
    }
  }, []);

  const fetchUser = async (authToken: string) => {
    try {
      const response = await tracedFetch(`${API_URL}/auth/me`, {
        headers: {
          'Authorization': `Bearer ${authToken}`,
        },
      });

      if (response.ok) {
        const userData = await response.json();
        console.log('✅ User data received:', {
          email: userData.email,
          full_name: userData.full_name,
          oauth_provider: userData.oauth_provider,
          avatar_url: userData.avatar_url ? `${userData.avatar_url.substring(0, 50)}...` : 'null',
        });
        setUser(userData);
      } else {
        // Token is invalid
        console.error('❌ Auth token invalid, status:', response.status);
        localStorage.removeItem('auth_token');
        setToken(null);
      }
    } catch (error) {
      console.error('Error fetching user:', error);
      localStorage.removeItem('auth_token');
      setToken(null);
    } finally {
      setIsLoading(false);
    }
  };

  const login = (provider: string, returnTo?: string) => {
    // Redirect to OAuth endpoint. The API only accepts a redirect on this site's origin, so returnTo can't leave it.
    const back = returnTo && returnTo.startsWith(window.location.origin) ? returnTo : window.location.origin;
    const redirectUri = encodeURIComponent(back);
    const authUrl = `${API_URL}/auth/login/${provider}?redirect_uri=${redirectUri}`;
    window.location.href = authUrl;
  };

  // Re-fetch the current user from /auth/me using the stored token. Lets pages
  // that mutate the profile (e.g. FeedSetup) refresh `profile_completed` and the
  // synced city/state without a full page reload.
  const refreshUser = async () => {
    const authToken = token || localStorage.getItem('auth_token');
    if (!authToken) return;
    await fetchUser(authToken);
  };

  const logout = () => {
    localStorage.removeItem('auth_token');
    setToken(null);
    setUser(null);
  };

  const clearAuthError = () => {
    setAuthError(null);
  };

  return (
    <AuthContext.Provider
      value={{
        user,
        token,
        login,
        logout,
        refreshUser,
        isAuthenticated: !!user,
        isLoading,
        authError,
        clearAuthError,
      }}
    >
      {children}
    </AuthContext.Provider>
  );
};

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