Spaces:
Running
on
CPU Upgrade
Running
on
CPU Upgrade
File size: 7,403 Bytes
f555806 f48f76d f555806 f48f76d f555806 f48f76d f555806 f48f76d f555806 f48f76d f555806 f48f76d f555806 |
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 |
'use client';
import { createContext, useCallback, useContext, useEffect, useMemo, useState } from 'react';
import { loadSettings, persistSettings } from '@/utils/storage/settingsStorage';
import { oauthClientId } from '@/utils/env';
type AuthMethod = 'oauth' | 'manual';
interface StoredAuthState {
token: string;
namespace: string;
method: AuthMethod;
}
export type AuthStatus = 'checking' | 'authenticated' | 'unauthenticated' | 'error';
interface AuthContextValue {
status: AuthStatus;
token: string | null;
namespace: string | null;
method: AuthMethod | null;
error: string | null;
oauthAvailable: boolean;
loginWithOAuth: () => void;
exchangeCodeForToken: (code: string, state: string) => Promise<boolean>;
setManualToken: (token: string) => Promise<void>;
logout: () => void;
}
const STORAGE_KEY = 'HF_AUTH_STATE';
const defaultValue: AuthContextValue = {
status: 'checking',
token: null,
namespace: null,
method: null,
error: null,
oauthAvailable: Boolean(oauthClientId),
loginWithOAuth: () => {},
exchangeCodeForToken: async () => false,
setManualToken: async () => {},
logout: () => {},
};
const AuthContext = createContext<AuthContextValue>(defaultValue);
async function validateToken(token: string) {
const res = await fetch('/api/auth/hf/validate', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ token }),
});
if (!res.ok) {
const data = await res.json().catch(() => ({}));
throw new Error(data?.error || 'Failed to validate token');
}
return res.json();
}
async function syncTokenWithSettings(token: string) {
try {
const current = await loadSettings();
if (current.HF_TOKEN === token) {
return;
}
current.HF_TOKEN = token;
await persistSettings(current);
} catch (error) {
console.warn('Failed to persist HF token to settings:', error);
}
}
async function clearTokenFromSettings() {
try {
const current = await loadSettings();
if (current.HF_TOKEN !== '') {
current.HF_TOKEN = '';
await persistSettings(current);
}
} catch (error) {
console.warn('Failed to clear HF token from settings:', error);
}
}
export function AuthProvider({ children }: { children: React.ReactNode }) {
const [status, setStatus] = useState<AuthStatus>('checking');
const [token, setToken] = useState<string | null>(null);
const [namespace, setNamespace] = useState<string | null>(null);
const [method, setMethod] = useState<AuthMethod | null>(null);
const [error, setError] = useState<string | null>(null);
const oauthAvailable = Boolean(oauthClientId);
const applyAuthState = useCallback(async ({ token: nextToken, namespace: nextNamespace, method: nextMethod }: StoredAuthState) => {
setToken(nextToken);
setNamespace(nextNamespace);
setMethod(nextMethod);
setStatus('authenticated');
setError(null);
if (typeof window !== 'undefined') {
window.localStorage.setItem(
STORAGE_KEY,
JSON.stringify({
token: nextToken,
namespace: nextNamespace,
method: nextMethod,
}),
);
}
syncTokenWithSettings(nextToken).catch(err => {
console.warn('Failed to sync HF token with settings:', err);
});
}, []);
const clearAuthState = useCallback(async () => {
setToken(null);
setNamespace(null);
setMethod(null);
setStatus('unauthenticated');
setError(null);
if (typeof window !== 'undefined') {
window.localStorage.removeItem(STORAGE_KEY);
}
clearTokenFromSettings().catch(err => {
console.warn('Failed to clear HF token from settings:', err);
});
}, []);
// Restore stored token on mount
useEffect(() => {
if (typeof window === 'undefined') {
return;
}
const restore = async () => {
const raw = window.localStorage.getItem(STORAGE_KEY);
if (!raw) {
setStatus('unauthenticated');
return;
}
try {
const stored: StoredAuthState = JSON.parse(raw);
if (!stored?.token) {
setStatus('unauthenticated');
return;
}
setStatus('checking');
const data = await validateToken(stored.token);
await applyAuthState({
token: stored.token,
namespace: data?.name || data?.preferred_username || stored.namespace || 'user',
method: stored.method || 'manual',
});
} catch (err) {
console.warn('Stored HF token invalid:', err);
await clearAuthState();
}
};
restore();
}, [applyAuthState, clearAuthState]);
const setManualToken = useCallback(
async (manualToken: string) => {
if (!manualToken) {
setError('Please provide a token');
setStatus('error');
return;
}
setStatus('checking');
setError(null);
try {
const data = await validateToken(manualToken);
await applyAuthState({
token: manualToken,
namespace: data?.name || data?.preferred_username || 'user',
method: 'manual',
});
} catch (err: any) {
setError(err?.message || 'Failed to validate token');
setStatus('error');
}
},
[applyAuthState],
);
const exchangeCodeForToken = useCallback(
async (code: string, state: string) => {
if (!code || !state) {
setError('Invalid authorization response.');
setStatus('error');
return false;
}
setStatus('checking');
setError(null);
try {
const res = await fetch('/api/auth/hf/exchange', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
credentials: 'same-origin',
body: JSON.stringify({ code, state }),
});
if (!res.ok) {
const data = await res.json().catch(() => ({}));
throw new Error(data?.error || 'Failed to exchange authorization code');
}
const data = await res.json();
await applyAuthState({
token: data.token,
namespace: data.namespace || 'user',
method: 'oauth',
});
return true;
} catch (err: any) {
setError(err?.message || 'Failed to authenticate with Hugging Face');
setStatus('error');
return false;
}
},
[applyAuthState],
);
const loginWithOAuth = useCallback(() => {
if (typeof window === 'undefined') {
return;
}
if (!oauthAvailable) {
setError('OAuth is not available on this deployment.');
setStatus('error');
return;
}
setStatus('checking');
setError(null);
window.location.href = '/api/auth/hf/login';
}, []);
const logout = useCallback(() => {
clearAuthState();
}, [clearAuthState]);
const value = useMemo<AuthContextValue>(
() => ({
status,
token,
namespace,
method,
error,
oauthAvailable,
loginWithOAuth,
exchangeCodeForToken,
setManualToken,
logout,
}),
[status, token, namespace, method, error, oauthAvailable, loginWithOAuth, exchangeCodeForToken, setManualToken, logout],
);
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
}
export function useAuth() {
return useContext(AuthContext);
}
|