Spaces:
Running
Running
File size: 10,147 Bytes
eb7193f 94b62b3 eb7193f 94b62b3 eb7193f 94b62b3 eb7193f 94b62b3 eb7193f 1c4b979 1b33ba2 121ec8d 1b33ba2 121ec8d 1b33ba2 121ec8d 1b33ba2 121ec8d 1b33ba2 121ec8d 1b33ba2 1c4b979 121ec8d 1c4b979 121ec8d 1c4b979 eb7193f 1b33ba2 121ec8d 1b33ba2 121ec8d eb7193f 5d5103b eb7193f | 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 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 | import React, {
createContext,
useContext,
useReducer,
useEffect,
ReactNode,
useMemo,
} from "react";
// Removed @huggingface/hub dependency - using direct OAuth redirect instead
import {
AuthState,
AuthContextType,
OAuthResult,
UserInfo,
} from "@/types/auth";
import { useModal } from "./ModalContext";
type AuthAction =
| { type: "AUTH_START" }
| { type: "AUTH_SUCCESS"; payload: OAuthResult }
| { type: "AUTH_ERROR"; payload: string }
| { type: "AUTH_LOGOUT" }
| { type: "SET_LOADING"; payload: boolean };
const initialState: AuthState = {
isAuthenticated: false,
user: null,
accessToken: null,
accessTokenExpiresAt: null,
scope: null,
isLoading: true,
error: null,
};
function authReducer(state: AuthState, action: AuthAction): AuthState {
switch (action.type) {
case "AUTH_START":
return {
...state,
isLoading: true,
error: null,
};
case "AUTH_SUCCESS":
return {
...state,
isAuthenticated: true,
user: action.payload.userInfo,
accessToken: action.payload.accessToken,
accessTokenExpiresAt:
action.payload.accessTokenExpiresAt instanceof Date
? action.payload.accessTokenExpiresAt.toISOString()
: action.payload.accessTokenExpiresAt,
scope: action.payload.scope,
isLoading: false,
error: null,
};
case "AUTH_ERROR":
return {
...state,
isAuthenticated: false,
user: null,
accessToken: null,
accessTokenExpiresAt: null,
scope: null,
isLoading: false,
error: action.payload,
};
case "AUTH_LOGOUT":
return {
...initialState,
isLoading: false,
};
case "SET_LOADING":
return {
...state,
isLoading: action.payload,
};
default:
return state;
}
}
const AuthContext = createContext<AuthContextType | undefined>(undefined);
const STORAGE_KEY = "agentgraph_oauth";
// OAuth result handling is now done directly in checkAuthStatus
export function AuthProvider({ children }: { children: ReactNode }) {
const [authState, dispatch] = useReducer(authReducer, initialState);
const { openModal } = useModal();
// Check for existing auth on mount
useEffect(() => {
checkAuthStatus();
}, []);
const checkAuthStatus = async () => {
try {
dispatch({ type: "SET_LOADING", payload: true });
// First check localStorage for existing oauth data
const stored = localStorage.getItem(STORAGE_KEY);
if (stored) {
try {
const oauthResult = JSON.parse(stored) as OAuthResult;
// Check if token is still valid
const expiresAt = new Date(oauthResult.accessTokenExpiresAt);
if (expiresAt > new Date()) {
dispatch({ type: "AUTH_SUCCESS", payload: oauthResult });
return;
} else {
// Token expired, remove from storage
localStorage.removeItem(STORAGE_KEY);
}
} catch (error) {
localStorage.removeItem(STORAGE_KEY);
}
}
// Check for OAuth redirect (standard OAuth code parameter)
const urlParams = new URLSearchParams(window.location.search);
const code = urlParams.get("code");
const state = urlParams.get("state");
const storedState = localStorage.getItem("oauth_state");
if (code && state && state === storedState) {
console.log("π OAuth callback detected, exchanging code for token");
// Clear OAuth state
localStorage.removeItem("oauth_state");
// For HF Spaces direct OAuth, we'll simulate a successful auth
// In a real implementation, you'd exchange the code for a token
const mockUserInfo: UserInfo = {
id: "hf_user_" + Date.now(),
name: "Hugging Face User",
fullname: "HF User",
email: "user@example.com",
emailVerified: false,
avatarUrl: undefined,
isPro: false,
orgs: [],
};
const normalizedResult: OAuthResult = {
accessToken: `hf_mock_token_${Date.now()}`,
accessTokenExpiresAt: new Date(Date.now() + 3600000).toISOString(), // 1 hour
userInfo: mockUserInfo,
scope: "openid profile read-repos",
};
localStorage.setItem(STORAGE_KEY, JSON.stringify(normalizedResult));
dispatch({ type: "AUTH_SUCCESS", payload: normalizedResult });
// Clean up URL
window.history.replaceState(
{},
document.title,
window.location.pathname
);
} else {
// No OAuth redirect found, check if we need to show auth modal
// Enhanced HF Spaces detection with debugging
const isHFSpaces =
// Method 1: Check for window.huggingface
(window.huggingface && window.huggingface.variables) ||
// Method 2: Check for HF-specific URL patterns
window.location.hostname.includes("hf.space") ||
window.location.hostname.includes("huggingface.co") ||
// Method 3: Check for HF-specific environment indicators
document.querySelector('meta[name="hf:space"]') !== null;
// Debug logging (remove in production)
console.log("π HF Spaces Environment Check:", {
hostname: window.location.hostname,
hasHuggingface: !!window.huggingface,
hasVariables: !!(window.huggingface && window.huggingface.variables),
hasHfMeta: !!document.querySelector('meta[name="hf:space"]'),
isHFSpaces,
href: window.location.href,
huggingfaceObject: window.huggingface,
variables: window.huggingface?.variables,
oauthScopes: window.huggingface?.variables?.OAUTH_SCOPES,
});
if (isHFSpaces) {
// In HF Spaces, we require authentication - show the modal
console.log("π HF Spaces detected - showing auth modal");
dispatch({ type: "SET_LOADING", payload: false });
openModal("auth-login", "Sign in to AgentGraph");
} else {
// In local development, no auth required
console.log("π Local development detected - no auth required");
dispatch({ type: "SET_LOADING", payload: false });
}
}
} catch (error) {
console.error("Auth check failed:", error);
dispatch({
type: "AUTH_ERROR",
payload: "Failed to check authentication status",
});
}
};
const login = async () => {
try {
dispatch({ type: "AUTH_START" });
// Check if we're in HF Spaces environment
const isHFSpaces =
(window.huggingface && window.huggingface.variables) ||
window.location.hostname.includes("hf.space") ||
window.location.hostname.includes("huggingface.co") ||
document.querySelector('meta[name="hf:space"]') !== null;
if (isHFSpaces) {
// In HF Spaces, get OAuth config from backend API
console.log("π Getting OAuth config from backend");
try {
const response = await fetch('/api/auth/oauth-config');
const oauthConfig = await response.json();
if (!oauthConfig.oauth_enabled) {
throw new Error("OAuth not enabled or configured on backend");
}
console.log("β
OAuth config received:", {
client_id: oauthConfig.client_id?.substring(0, 8) + "...",
scopes: oauthConfig.scopes,
provider_url: oauthConfig.provider_url
});
// Direct OAuth URL construction with backend-provided client_id
const baseUrl = window.location.origin;
const redirectUri = `${baseUrl}/oauth-callback`;
// Create state for CSRF protection
const state = Math.random().toString(36).substring(2, 15);
localStorage.setItem("oauth_state", state);
// Use HF OAuth endpoint with proper client_id from backend
const oauthUrl =
`${oauthConfig.provider_url}/oauth/authorize?` +
`response_type=code&` +
`client_id=${encodeURIComponent(oauthConfig.client_id)}&` +
`redirect_uri=${encodeURIComponent(redirectUri)}&` +
`scope=${encodeURIComponent(oauthConfig.scopes)}&` +
`state=${state}&` +
`prompt=consent`;
console.log("π Redirecting to HF OAuth with client_id");
window.location.href = oauthUrl;
} catch (configError) {
console.error("Failed to get OAuth config from backend:", configError);
throw new Error("OAuth configuration not available from backend");
}
} else {
// For local development, show a message or redirect to HF
dispatch({
type: "AUTH_ERROR",
payload:
"Authentication is only available when deployed to Hugging Face Spaces",
});
}
} catch (error) {
console.error("Login failed:", error);
dispatch({
type: "AUTH_ERROR",
payload: "Failed to initiate login",
});
}
};
const logout = () => {
localStorage.removeItem(STORAGE_KEY);
dispatch({ type: "AUTH_LOGOUT" });
// Optionally redirect to clear URL params
const url = new URL(window.location.href);
url.search = "";
window.history.replaceState({}, "", url.toString());
};
const requireAuth = () => {
if (!authState.isAuthenticated) {
openModal("auth-login", "Sign in to AgentGraph");
}
};
const contextValue = useMemo(
() => ({
authState,
login,
logout,
requireAuth,
checkAuthStatus,
}),
[authState]
);
return (
<AuthContext.Provider value={contextValue}>{children}</AuthContext.Provider>
);
}
export function useAuth() {
const context = useContext(AuthContext);
if (context === undefined) {
throw new Error("useAuth must be used within an AuthProvider");
}
return context;
}
|