Skip to content

fix: setAuth ran automatically for realtime; prioritize setAuth tasks #1475

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 20 additions & 12 deletions src/SupabaseClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ export default class SupabaseClient<
})

if (!settings.accessToken) {
this._listenForAuthEvents()
setTimeout(() => this._listenForAuthEvents(), 0)
}
}

Expand Down Expand Up @@ -268,7 +268,7 @@ export default class SupabaseClient<
return this.realtime.removeAllChannels()
}

private async _getAccessToken() {
protected async _getAccessToken() {
if (this.accessToken) {
return await this.accessToken()
}
Expand All @@ -278,7 +278,7 @@ export default class SupabaseClient<
return data.session?.access_token ?? null
}

private _initSupabaseAuthClient(
protected _initSupabaseAuthClient(
{
autoRefreshToken,
persistSession,
Expand Down Expand Up @@ -314,21 +314,23 @@ export default class SupabaseClient<
})
}

private _initRealtimeClient(options: RealtimeClientOptions) {
protected _initRealtimeClient(options: RealtimeClientOptions) {
return new RealtimeClient(this.realtimeUrl.href, {
...options,
params: { ...{ apikey: this.supabaseKey }, ...options?.params },
})
}

private _listenForAuthEvents() {
let data = this.auth.onAuthStateChange((event, session) => {
this._handleTokenChanged(event, 'CLIENT', session?.access_token)
protected async _listenForAuthEvents() {
return await this.auth.onAuthStateChange((event, session) => {
setTimeout(
async () => await this._handleTokenChanged(event, 'CLIENT', session?.access_token),
0
)
})
return data
}

private _handleTokenChanged(
protected async _handleTokenChanged(
event: AuthChangeEvent,
source: 'CLIENT' | 'STORAGE',
token?: string
Expand All @@ -338,10 +340,16 @@ export default class SupabaseClient<
this.changedAccessToken !== token
) {
this.changedAccessToken = token
this.realtime.setAuth(token)
} else if (event === 'SIGNED_OUT') {
this.realtime.setAuth()
if (source == 'STORAGE') this.auth.signOut()
this.changedAccessToken = undefined
try {
await this.realtime.setAuth()
if (source == 'STORAGE') this.auth.signOut()
} catch (error) {
console.log('Failed to set auth for realtime client:', error)
} finally {
this.changedAccessToken = undefined
}
}
}
}
Loading