Spaces:
Running
Running
Update src/firebase.js
Browse files- src/firebase.js +35 -1
src/firebase.js
CHANGED
|
@@ -9,7 +9,41 @@ let profilesCache={};
|
|
| 9 |
|
| 10 |
async function fetchIP(){try{const r=await fetch('https://api.ipify.org?format=json');if(!r.ok)throw 0;const j=await r.json();return j.ip||'';}catch{return''}}
|
| 11 |
|
| 12 |
-
export async function initFirebase(){
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
|
| 14 |
export function getDB(){return db;}
|
| 15 |
export function getAuthState(){return{userId,username,ready}};
|
|
|
|
| 9 |
|
| 10 |
async function fetchIP(){try{const r=await fetch('https://api.ipify.org?format=json');if(!r.ok)throw 0;const j=await r.json();return j.ip||'';}catch{return''}}
|
| 11 |
|
| 12 |
+
export async function initFirebase(){
|
| 13 |
+
try{
|
| 14 |
+
app=initializeApp(firebaseConfig); db=getFirestore(app); auth=getAuth(app);
|
| 15 |
+
}catch{
|
| 16 |
+
db=undefined; auth=undefined;
|
| 17 |
+
}
|
| 18 |
+
const ip=await fetchIP(); const last=localStorage.getItem('last_ip')||'';
|
| 19 |
+
if(ip&&ip!==last){ localStorage.removeItem('local_username'); localStorage.setItem('last_ip',ip); }
|
| 20 |
+
|
| 21 |
+
let resolved=false;
|
| 22 |
+
function resolveReady(){ if(!resolved){ resolved=true; ready=true; }}
|
| 23 |
+
|
| 24 |
+
if (auth){
|
| 25 |
+
onAuthStateChanged(auth,async u=>{
|
| 26 |
+
if(u){ userId=u.uid; const p=await ensureProfile(userId); username=p.username; renderAuthUI(true); resolveReady(); }
|
| 27 |
+
else{
|
| 28 |
+
try{ await signInAnonymously(auth); }
|
| 29 |
+
catch{
|
| 30 |
+
userId=localStorage.getItem('local_uid')||crypto.randomUUID(); localStorage.setItem('local_uid',userId);
|
| 31 |
+
let uname=localStorage.getItem('local_username'); if(!uname){ uname=autoUsername(); localStorage.setItem('local_username',uname); }
|
| 32 |
+
username=uname; renderAuthUI(false); resolveReady();
|
| 33 |
+
}
|
| 34 |
+
}
|
| 35 |
+
});
|
| 36 |
+
} else {
|
| 37 |
+
userId=localStorage.getItem('local_uid')||crypto.randomUUID(); localStorage.setItem('local_uid',userId);
|
| 38 |
+
let uname=localStorage.getItem('local_username'); if(!uname){ uname=autoUsername(); localStorage.setItem('local_username',uname); }
|
| 39 |
+
username=uname; renderAuthUI(false); resolveReady();
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
return new Promise(res=>{
|
| 43 |
+
const start=Date.now();
|
| 44 |
+
const t=setInterval(()=>{ if(ready){ clearInterval(t); res(); } else if(Date.now()-start>2500){ resolveReady(); clearInterval(t); res(); } }, 50);
|
| 45 |
+
});
|
| 46 |
+
}
|
| 47 |
|
| 48 |
export function getDB(){return db;}
|
| 49 |
export function getAuthState(){return{userId,username,ready}};
|