Browse Source
feat: implement AuthBridge for managing HABIB_TOKEN and HABIB_COINS from window
master
feat: implement AuthBridge for managing HABIB_TOKEN and HABIB_COINS from window
master
5 changed files with 123 additions and 4 deletions
-
8src/app/api/proxy/route.ts
-
25src/app/layout.tsx
-
74src/lib/auth-bridge.ts
-
6src/lib/http.ts
-
12src/types/window.d.ts
@ -0,0 +1,74 @@ |
|||
class AuthBridge { |
|||
private token: string | null = null; |
|||
private coins: number = 0; |
|||
private isReady = false; |
|||
private readyCallbacks: Array<() => void> = []; |
|||
|
|||
constructor() { |
|||
this.init(); |
|||
} |
|||
|
|||
private init() { |
|||
if (typeof window !== 'undefined') { |
|||
const win = window as any; |
|||
|
|||
if (win.HABIB_TOKEN) { |
|||
this.token = win.HABIB_TOKEN; |
|||
this.coins = win.HABIB_COINS || 0; |
|||
this.isReady = true; |
|||
this.notifyReady(); |
|||
} else { |
|||
this.waitForInjection(); |
|||
} |
|||
} |
|||
} |
|||
|
|||
private waitForInjection() { |
|||
let attempts = 0; |
|||
const maxAttempts = 50; |
|||
|
|||
const checkInterval = setInterval(() => { |
|||
const win = window as any; |
|||
|
|||
if (win.HABIB_TOKEN) { |
|||
this.token = win.HABIB_TOKEN; |
|||
this.coins = win.HABIB_COINS || 0; |
|||
this.isReady = true; |
|||
clearInterval(checkInterval); |
|||
this.notifyReady(); |
|||
} else if (++attempts >= maxAttempts) { |
|||
clearInterval(checkInterval); |
|||
console.warn('⚠️ Token not received from Flutter'); |
|||
this.isReady = true; |
|||
this.notifyReady(); |
|||
} |
|||
}, 100); |
|||
} |
|||
|
|||
private notifyReady() { |
|||
this.readyCallbacks.forEach(cb => cb()); |
|||
this.readyCallbacks = []; |
|||
} |
|||
|
|||
public onReady(callback: () => void) { |
|||
if (this.isReady) { |
|||
callback(); |
|||
} else { |
|||
this.readyCallbacks.push(callback); |
|||
} |
|||
} |
|||
|
|||
public getToken(): string | null { |
|||
return this.token; |
|||
} |
|||
|
|||
public getCoins(): number { |
|||
return this.coins; |
|||
} |
|||
|
|||
public isAuthenticated(): boolean { |
|||
return !!this.token; |
|||
} |
|||
} |
|||
|
|||
export const authBridge = new AuthBridge(); |
|||
@ -0,0 +1,12 @@ |
|||
declare global { |
|||
interface Window { |
|||
HABIB_TOKEN?: string; |
|||
HABIB_COINS?: number; |
|||
onFlutterResponse?: (data: any) => void; |
|||
HabibApp?: { |
|||
postMessage: (message: string) => void; |
|||
}; |
|||
} |
|||
} |
|||
|
|||
export {}; |
|||
Write
Preview
Loading…
Cancel
Save
Reference in new issue