fix: make Google login and session recovery resilient
This commit is contained in:
@@ -16,46 +16,46 @@ export const LoginPage = ({ onLogin }) => {
|
||||
const [ready, setReady] = useState(false);
|
||||
const [noConfig, setNoConfig] = useState(false);
|
||||
|
||||
const [attempt,setAttempt]=useState(0),[signingIn,setSigningIn]=useState(false);
|
||||
const loginCallback=useRef(onLogin);loginCallback.current=onLogin;
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
(async () => {
|
||||
const { clientId } = await getGoogleConfig();
|
||||
if (cancelled) return;
|
||||
if (!clientId) { setNoConfig(true); return; }
|
||||
|
||||
const init = () => {
|
||||
if (!window.google?.accounts?.id || !btnRef.current) return;
|
||||
window.google.accounts.id.initialize({
|
||||
client_id: clientId,
|
||||
callback: async (resp) => {
|
||||
try {
|
||||
const user = await loginWithGoogle(resp.credential);
|
||||
onLogin(user);
|
||||
} catch (e) {
|
||||
setErr(e.message || 'Giriş başarısız');
|
||||
}
|
||||
},
|
||||
});
|
||||
window.google.accounts.id.renderButton(btnRef.current, {
|
||||
theme: 'outline', size: 'large', text: 'continue_with', locale: 'tr', width: 320,
|
||||
});
|
||||
setReady(true);
|
||||
};
|
||||
|
||||
if (window.google?.accounts?.id) { init(); return; }
|
||||
let s = document.getElementById('gsi-script');
|
||||
if (!s) {
|
||||
s = document.createElement('script');
|
||||
s.id = 'gsi-script';
|
||||
s.src = 'https://accounts.google.com/gsi/client';
|
||||
s.async = true;
|
||||
s.defer = true;
|
||||
document.head.appendChild(s);
|
||||
}
|
||||
s.addEventListener('load', init);
|
||||
let cancelled=false,script=null,scriptTimer=null,loginPending=false;
|
||||
const controller=new AbortController();
|
||||
setErr(null);setReady(false);setNoConfig(false);setSigningIn(false);
|
||||
const failed=()=>{clearTimeout(scriptTimer);if(!cancelled){setErr('Google giriş ekranı yüklenemedi. Bağlantınızı kontrol edip yeniden deneyin.');setReady(false);}script?.remove();};
|
||||
const init=()=>{
|
||||
if(cancelled)return;
|
||||
if(!window.google?.accounts?.id||!btnRef.current){failed();return;}
|
||||
clearTimeout(scriptTimer);
|
||||
try {
|
||||
window.google.accounts.id.initialize({client_id:clientId,callback:async response=>{
|
||||
if(cancelled||loginPending)return;
|
||||
loginPending=true;setSigningIn(true);setErr(null);
|
||||
try{const user=await loginWithGoogle(response.credential,{signal:controller.signal});if(!cancelled)loginCallback.current(user);}
|
||||
catch(error){if(!cancelled)setErr(error.message || 'Giriş başarısız');}
|
||||
finally{loginPending=false;if(!cancelled)setSigningIn(false);}
|
||||
}});
|
||||
btnRef.current.replaceChildren();
|
||||
window.google.accounts.id.renderButton(btnRef.current,{theme:'outline',size:'large',text:'continue_with',locale:'tr',width:Math.min(320,btnRef.current.parentElement.clientWidth)});
|
||||
setReady(true);
|
||||
} catch { failed(); }
|
||||
};
|
||||
let clientId;
|
||||
void (async()=>{
|
||||
try{
|
||||
const config=await getGoogleConfig({signal:controller.signal});
|
||||
if(cancelled)return;clientId=config.clientId;
|
||||
if(!clientId){setNoConfig(true);return;}
|
||||
if(window.google?.accounts?.id){init();return;}
|
||||
script=document.getElementById('gsi-script');
|
||||
if(!script){script=document.createElement('script');script.id='gsi-script';script.src='https://accounts.google.com/gsi/client';script.async=true;script.defer=true;}
|
||||
script.addEventListener('load',init);script.addEventListener('error',failed);
|
||||
scriptTimer=setTimeout(failed,15000);
|
||||
if(!script.isConnected)document.head.appendChild(script);
|
||||
}catch(error){if(!cancelled)setErr(error.message || 'Giriş hizmetine ulaşılamadı.');}
|
||||
})();
|
||||
return () => { cancelled = true; };
|
||||
}, [onLogin]);
|
||||
return()=>{cancelled=true;controller.abort();clearTimeout(scriptTimer);script?.removeEventListener('load',init);script?.removeEventListener('error',failed);};
|
||||
},[attempt]);
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-[#0f172a] text-white flex flex-col lg:flex-row">
|
||||
@@ -89,16 +89,18 @@ export const LoginPage = ({ onLogin }) => {
|
||||
|
||||
{noConfig ? (
|
||||
<div className="text-sm text-amber-700 bg-amber-50 border border-amber-200 rounded-xl p-4">
|
||||
Google girişi henüz yapılandırılmadı (sunucuda GOOGLE_CLIENT_ID eksik).
|
||||
Google girişi henüz etkinleştirilmedi. Lütfen yöneticinizle görüşün.
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex flex-col items-center gap-4">
|
||||
<div ref={btnRef} className="min-h-[44px]" />
|
||||
{!ready && <p className="text-xs text-slate-400">Google giriş yükleniyor…</p>}
|
||||
{!ready && !err && <p role="status" className="text-xs text-slate-400">Google giriş yükleniyor…</p>}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{err && <p className="mt-4 text-sm text-red-600">{err}</p>}
|
||||
{signingIn&&<p role="status" className="mt-4 text-sm">Giriş doğrulanıyor…</p>}
|
||||
{err && <p role="alert" className="mt-4 text-sm text-red-600">{err}</p>}
|
||||
{(err||noConfig)&&<button disabled={signingIn} onClick={()=>setAttempt(n=>n+1)} className="border rounded px-4 py-2 mt-3 text-sm">Girişi yeniden dene</button>}
|
||||
|
||||
<p className="mt-8 text-[11px] text-slate-400 flex items-center justify-center gap-1">
|
||||
<ShieldCheck className="w-3.5 h-3.5" /> Girişin Google tarafından güvenle doğrulanır.
|
||||
|
||||
+37
-27
@@ -1,3 +1,4 @@
|
||||
import {awaitWithAbort} from './abortable.js';
|
||||
/**
|
||||
* Google ile Giriş — frontend istemcisi (GIS ID-token akışı).
|
||||
* Token localStorage'da 'ihaleist_token', kullanıcı 'ihaleist_user' altında saklanır.
|
||||
@@ -25,43 +26,52 @@ export function clearSession() {
|
||||
} catch { /* yoksay */ }
|
||||
}
|
||||
|
||||
export async function getGoogleConfig() {
|
||||
try {
|
||||
const res = await fetch('/api/auth/google/config');
|
||||
if (!res.ok) return { clientId: null };
|
||||
return await res.json();
|
||||
} catch {
|
||||
return { clientId: null };
|
||||
}
|
||||
async function authRequest(url,options={}) {
|
||||
const {signal,...requestOptions}=options,controller=new AbortController();
|
||||
const cancel=()=>controller.abort(signal.reason);
|
||||
if(signal?.aborted)cancel();else signal?.addEventListener('abort',cancel,{once:true});
|
||||
let timeout=false;
|
||||
const timer=setTimeout(()=>{timeout=true;controller.abort();},30000);
|
||||
try{
|
||||
controller.signal.throwIfAborted();
|
||||
const res=await awaitWithAbort(fetch(url,{...requestOptions,signal:controller.signal}),controller.signal);
|
||||
const data=await awaitWithAbort(res.json().catch(error=>{if(res.ok)throw error;return null;}),controller.signal);
|
||||
controller.signal.throwIfAborted();
|
||||
if(!res.ok){const error=new Error(data?.error || 'Giriş hizmetine ulaşılamadı. Yeniden deneyin.');error.status=res.status;throw error;}
|
||||
return data;
|
||||
}catch(error){if(timeout)throw new Error('Giriş hizmeti zamanında yanıt vermedi. Yeniden deneyin.');throw error;}
|
||||
finally{clearTimeout(timer);signal?.removeEventListener('abort',cancel);}
|
||||
}
|
||||
|
||||
export async function loginWithGoogle(credential) {
|
||||
const res = await fetch('/api/auth/google', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ credential }),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok || !data.success) throw new Error(data.error || 'Giriş başarısız');
|
||||
setSession(data.token, data.user);
|
||||
export async function getGoogleConfig({signal}={}) {
|
||||
const data=await authRequest('/api/auth/google/config',{signal});
|
||||
if(!data || !Object.hasOwn(data,'clientId') || (data.clientId!==null&&typeof data.clientId!=='string'))throw new Error('Giriş yapılandırması doğrulanamadı. Yeniden deneyin.');
|
||||
return data;
|
||||
}
|
||||
export async function loginWithGoogle(credential,{signal}={}) {
|
||||
const data=await authRequest('/api/auth/google',{method:'POST',signal,headers:{'Content-Type':'application/json'},body:JSON.stringify({credential})});
|
||||
if(!data?.success)throw new Error(data?.error || 'Giriş başarısız');
|
||||
if(typeof data.token!=='string'||!data.token||typeof data.user?.email!=='string'||!data.user.email)throw new Error('Giriş yanıtı doğrulanamadı.');
|
||||
signal?.throwIfAborted();
|
||||
setSession(data.token,data.user);
|
||||
if(getToken()!==data.token||getStoredUser()?.email!==data.user.email){clearSession();throw new Error('Tarayıcı oturumu saklayamadı. Site depolama iznini kontrol edip tekrar deneyin.');}
|
||||
return data.user;
|
||||
}
|
||||
|
||||
// Sayfa açılışında saklı token'ı doğrula (opsiyonel; başarısızsa oturum düşer)
|
||||
// Geçici hizmet hatası oturumu silmez; yalnız açık yetki reddi sona erdirir.
|
||||
export async function restoreSession() {
|
||||
const token = getToken();
|
||||
if (!token) return null;
|
||||
try {
|
||||
const res = await fetch('/api/auth/me', { headers: { Authorization: `Bearer ${token}` } });
|
||||
const data = await authRequest('/api/auth/me', { headers: { Authorization: `Bearer ${token}` } });
|
||||
if (getToken() !== token) return getStoredUser();
|
||||
if (!res.ok) { clearSession(); return null; }
|
||||
const data = await res.json();
|
||||
if (data?.success && typeof data.user?.email === 'string' && data.user.email) {
|
||||
setSession(token, data.user);
|
||||
return data.user;
|
||||
}
|
||||
return getStoredUser();
|
||||
} catch (error) {
|
||||
if (getToken() !== token) return getStoredUser();
|
||||
if (data.success) { setSession(token, data.user); return data.user; }
|
||||
clearSession();
|
||||
return null;
|
||||
} catch {
|
||||
// Ağ hatası: saklı kullanıcıyı koru (offline)
|
||||
if (error.status === 401 || error.status === 403) { clearSession(); return null; }
|
||||
return getStoredUser();
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user