• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

supabase / supabase-js / 10130650437

28 Jul 2024 09:31AM UTC coverage: 66.038% (+1.1%) from 64.948%
10130650437

Pull #1004

github

web-flow
Merge 7b4c23f85 into 51cd9863a
Pull Request #1004: feat: add third-party auth support

41 of 83 branches covered (49.4%)

Branch coverage included in aggregate %.

12 of 15 new or added lines in 2 files covered. (80.0%)

1 existing line in 1 file now uncovered.

99 of 129 relevant lines covered (76.74%)

4.59 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

64.35
/src/SupabaseClient.ts
1
import { FunctionsClient } from '@supabase/functions-js'
2✔
2
import { AuthChangeEvent } from '@supabase/auth-js'
3
import {
2✔
4
  PostgrestClient,
5
  PostgrestFilterBuilder,
6
  PostgrestQueryBuilder,
7
} from '@supabase/postgrest-js'
8
import {
2✔
9
  RealtimeChannel,
10
  RealtimeChannelOptions,
11
  RealtimeClient,
12
  RealtimeClientOptions,
13
} from '@supabase/realtime-js'
14
import { StorageClient as SupabaseStorageClient } from '@supabase/storage-js'
2✔
15
import {
2✔
16
  DEFAULT_GLOBAL_OPTIONS,
17
  DEFAULT_DB_OPTIONS,
18
  DEFAULT_AUTH_OPTIONS,
19
  DEFAULT_REALTIME_OPTIONS,
20
} from './lib/constants'
21
import { fetchWithAuth } from './lib/fetch'
2✔
22
import { stripTrailingSlash, applySettingDefaults } from './lib/helpers'
2✔
23
import { SupabaseAuthClient } from './lib/SupabaseAuthClient'
2✔
24
import { Fetch, GenericSchema, SupabaseClientOptions, SupabaseAuthClientOptions } from './lib/types'
25

26
/**
27
 * Supabase Client.
28
 *
29
 * An isomorphic Javascript client for interacting with Postgres.
30
 */
31
export default class SupabaseClient<
2✔
32
  Database = any,
33
  SchemaName extends string & keyof Database = 'public' extends keyof Database
34
    ? 'public'
35
    : string & keyof Database,
36
  Schema extends GenericSchema = Database[SchemaName] extends GenericSchema
37
    ? Database[SchemaName]
38
    : any
39
> {
40
  /**
41
   * Supabase Auth allows you to create and manage user sessions for access to data that is secured by access policies.
42
   */
43
  auth: SupabaseAuthClient
44
  realtime: RealtimeClient
45

46
  protected realtimeUrl: string
47
  protected authUrl: string
48
  protected storageUrl: string
49
  protected functionsUrl: string
50
  protected rest: PostgrestClient<Database, SchemaName>
51
  protected storageKey: string
52
  protected fetch?: Fetch
53
  protected changedAccessToken?: string
54
  protected accessToken?: () => Promise<string>
55

56
  protected headers: Record<string, string>
57

58
  /**
59
   * Create a new client for use in the browser.
60
   * @param supabaseUrl The unique Supabase URL which is supplied when you create a new project in your project dashboard.
61
   * @param supabaseKey The unique Supabase Key which is supplied when you create a new project in your project dashboard.
62
   * @param options.db.schema You can switch in between schemas. The schema needs to be on the list of exposed schemas inside Supabase.
63
   * @param options.auth.autoRefreshToken Set to "true" if you want to automatically refresh the token before expiring.
64
   * @param options.auth.persistSession Set to "true" if you want to automatically save the user session into local storage.
65
   * @param options.auth.detectSessionInUrl Set to "true" if you want to automatically detects OAuth grants in the URL and signs in the user.
66
   * @param options.realtime Options passed along to realtime-js constructor.
67
   * @param options.global.fetch A custom fetch implementation.
68
   * @param options.global.headers Any additional headers to send with each network request.
69
   */
70
  constructor(
71
    protected supabaseUrl: string,
10✔
72
    protected supabaseKey: string,
10✔
73
    options?: SupabaseClientOptions<SchemaName>
74
  ) {
75
    if (!supabaseUrl) throw new Error('supabaseUrl is required.')
10✔
76
    if (!supabaseKey) throw new Error('supabaseKey is required.')
9✔
77

78
    const _supabaseUrl = stripTrailingSlash(supabaseUrl)
8✔
79

80
    this.realtimeUrl = `${_supabaseUrl}/realtime/v1`.replace(/^http/i, 'ws')
8✔
81
    this.authUrl = `${_supabaseUrl}/auth/v1`
8✔
82
    this.storageUrl = `${_supabaseUrl}/storage/v1`
8✔
83
    this.functionsUrl = `${_supabaseUrl}/functions/v1`
8✔
84

85
    // default storage key uses the supabase project ref as a namespace
86
    const defaultStorageKey = `sb-${new URL(this.authUrl).hostname.split('.')[0]}-auth-token`
8✔
87
    const DEFAULTS = {
8✔
88
      db: DEFAULT_DB_OPTIONS,
89
      realtime: DEFAULT_REALTIME_OPTIONS,
90
      auth: { ...DEFAULT_AUTH_OPTIONS, storageKey: defaultStorageKey },
91
      global: DEFAULT_GLOBAL_OPTIONS,
92
    }
93

94
    const settings = applySettingDefaults(options ?? {}, DEFAULTS)
8✔
95

96
    this.storageKey = settings.auth.storageKey ?? ''
8!
97
    this.headers = settings.global.headers ?? {}
8!
98

99
    if (!settings.accessToken) {
8✔
100
      this.auth = this._initSupabaseAuthClient(
7✔
101
        settings.auth ?? {},
21!
102
        this.headers,
103
        settings.global.fetch
104
      )
105
    } else {
106
      this.accessToken = settings.accessToken
1✔
107

108
      this.auth = new Proxy<SupabaseAuthClient>({} as any, {
1✔
109
        get: (_, prop) => {
110
          throw new Error(
1✔
111
            `@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(
112
              prop
113
            )} is not possible`
114
          )
115
        },
116
      })
117
    }
118

119
    this.fetch = fetchWithAuth(supabaseKey, this._getAccessToken.bind(this), settings.global.fetch)
8✔
120

121
    this.realtime = this._initRealtimeClient({ headers: this.headers, ...settings.realtime })
8✔
122
    this.rest = new PostgrestClient(`${_supabaseUrl}/rest/v1`, {
8✔
123
      headers: this.headers,
124
      schema: settings.db.schema,
125
      fetch: this.fetch,
126
    })
127

128
    if (!settings.accessToken) {
8✔
129
      this._listenForAuthEvents()
7✔
130
    }
131
  }
132

133
  /**
134
   * Supabase Functions allows you to deploy and invoke edge functions.
135
   */
136
  get functions(): FunctionsClient {
137
    return new FunctionsClient(this.functionsUrl, {
×
138
      headers: this.headers,
139
      customFetch: this.fetch,
140
    })
141
  }
142

143
  /**
144
   * Supabase Storage allows you to manage user-generated content, such as photos or videos.
145
   */
146
  get storage(): SupabaseStorageClient {
147
    return new SupabaseStorageClient(this.storageUrl, this.headers, this.fetch)
×
148
  }
149

150
  // NOTE: signatures must be kept in sync with PostgrestClient.from
151
  from<
152
    TableName extends string & keyof Schema['Tables'],
153
    Table extends Schema['Tables'][TableName]
154
  >(relation: TableName): PostgrestQueryBuilder<Schema, Table, TableName>
155
  from<ViewName extends string & keyof Schema['Views'], View extends Schema['Views'][ViewName]>(
156
    relation: ViewName
157
  ): PostgrestQueryBuilder<Schema, View, ViewName>
158
  /**
159
   * Perform a query on a table or a view.
160
   *
161
   * @param relation - The table or view name to query
162
   */
163
  from(relation: string): PostgrestQueryBuilder<Schema, any, any> {
164
    return this.rest.from(relation)
×
165
  }
166

167
  // NOTE: signatures must be kept in sync with PostgrestClient.schema
168
  /**
169
   * Select a schema to query or perform an function (rpc) call.
170
   *
171
   * The schema needs to be on the list of exposed schemas inside Supabase.
172
   *
173
   * @param schema - The schema to query
174
   */
175
  schema<DynamicSchema extends string & keyof Database>(
176
    schema: DynamicSchema
177
  ): PostgrestClient<
178
    Database,
179
    DynamicSchema,
180
    Database[DynamicSchema] extends GenericSchema ? Database[DynamicSchema] : any
181
  > {
182
    return this.rest.schema<DynamicSchema>(schema)
2✔
183
  }
184

185
  // NOTE: signatures must be kept in sync with PostgrestClient.rpc
186
  /**
187
   * Perform a function call.
188
   *
189
   * @param fn - The function name to call
190
   * @param args - The arguments to pass to the function call
191
   * @param options - Named parameters
192
   * @param options.head - When set to `true`, `data` will not be returned.
193
   * Useful if you only need the count.
194
   * @param options.get - When set to `true`, the function will be called with
195
   * read-only access mode.
196
   * @param options.count - Count algorithm to use to count rows returned by the
197
   * function. Only applicable for [set-returning
198
   * functions](https://www.postgresql.org/docs/current/functions-srf.html).
199
   *
200
   * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the
201
   * hood.
202
   *
203
   * `"planned"`: Approximated but fast count algorithm. Uses the Postgres
204
   * statistics under the hood.
205
   *
206
   * `"estimated"`: Uses exact count for low numbers and planned count for high
207
   * numbers.
208
   */
209
  rpc<FnName extends string & keyof Schema['Functions'], Fn extends Schema['Functions'][FnName]>(
210
    fn: FnName,
211
    args: Fn['Args'] = {},
1✔
212
    options: {
1✔
213
      head?: boolean
214
      get?: boolean
215
      count?: 'exact' | 'planned' | 'estimated'
216
    } = {}
217
  ): PostgrestFilterBuilder<
218
    Schema,
219
    Fn['Returns'] extends any[]
220
      ? Fn['Returns'][number] extends Record<string, unknown>
221
        ? Fn['Returns'][number]
222
        : never
223
      : never,
224
    Fn['Returns']
225
  > {
226
    return this.rest.rpc(fn, args, options)
1✔
227
  }
228

229
  /**
230
   * Creates a Realtime channel with Broadcast, Presence, and Postgres Changes.
231
   *
232
   * @param {string} name - The name of the Realtime channel.
233
   * @param {Object} opts - The options to pass to the Realtime channel.
234
   *
235
   */
236
  channel(name: string, opts: RealtimeChannelOptions = { config: {} }): RealtimeChannel {
×
237
    return this.realtime.channel(name, opts)
×
238
  }
239

240
  /**
241
   * Returns all Realtime channels.
242
   */
243
  getChannels(): RealtimeChannel[] {
244
    return this.realtime.getChannels()
×
245
  }
246

247
  /**
248
   * Unsubscribes and removes Realtime channel from Realtime client.
249
   *
250
   * @param {RealtimeChannel} channel - The name of the Realtime channel.
251
   *
252
   */
253
  removeChannel(channel: RealtimeChannel): Promise<'ok' | 'timed out' | 'error'> {
254
    return this.realtime.removeChannel(channel)
×
255
  }
256

257
  /**
258
   * Unsubscribes and removes all Realtime channels from Realtime client.
259
   */
260
  removeAllChannels(): Promise<('ok' | 'timed out' | 'error')[]> {
261
    return this.realtime.removeAllChannels()
×
262
  }
263

264
  private async _getAccessToken() {
NEW
265
    if (this.accessToken) {
×
NEW
266
      return await this.accessToken()
×
267
    }
268

UNCOV
269
    const { data } = await this.auth.getSession()
×
270

271
    return data.session?.access_token ?? null
×
272
  }
273

274
  private _initSupabaseAuthClient(
275
    {
276
      autoRefreshToken,
277
      persistSession,
278
      detectSessionInUrl,
279
      storage,
280
      storageKey,
281
      flowType,
282
      debug,
283
    }: SupabaseAuthClientOptions,
284
    headers?: Record<string, string>,
285
    fetch?: Fetch
286
  ) {
287
    const authHeaders = {
8✔
288
      Authorization: `Bearer ${this.supabaseKey}`,
289
      apikey: `${this.supabaseKey}`,
290
    }
291
    return new SupabaseAuthClient({
8✔
292
      url: this.authUrl,
293
      headers: { ...authHeaders, ...headers },
294
      storageKey: storageKey,
295
      autoRefreshToken,
296
      persistSession,
297
      detectSessionInUrl,
298
      storage,
299
      flowType,
300
      debug,
301
      fetch,
302
      // auth checks if there is a custom authorizaiton header using this flag
303
      // so it knows whether to return an error when getUser is called with no session
304
      hasCustomAuthorizationHeader: 'Authorization' in this.headers ?? false,
24!
305
    })
306
  }
307

308
  private _initRealtimeClient(options: RealtimeClientOptions) {
309
    return new RealtimeClient(this.realtimeUrl, {
8✔
310
      ...options,
311
      params: { ...{ apikey: this.supabaseKey }, ...options?.params },
24!
312
    })
313
  }
314

315
  private _listenForAuthEvents() {
316
    let data = this.auth.onAuthStateChange((event, session) => {
7✔
317
      this._handleTokenChanged(event, 'CLIENT', session?.access_token)
7!
318
    })
319
    return data
7✔
320
  }
321

322
  private _handleTokenChanged(
323
    event: AuthChangeEvent,
324
    source: 'CLIENT' | 'STORAGE',
325
    token?: string
326
  ) {
327
    if (
7!
328
      (event === 'TOKEN_REFRESHED' || event === 'SIGNED_IN') &&
14!
329
      this.changedAccessToken !== token
330
    ) {
331
      // Token has changed
332
      this.realtime.setAuth(token ?? null)
×
333

334
      this.changedAccessToken = token
×
335
    } else if (event === 'SIGNED_OUT') {
7!
336
      // Token is removed
337
      this.realtime.setAuth(this.supabaseKey)
×
338
      if (source == 'STORAGE') this.auth.signOut()
×
339
      this.changedAccessToken = undefined
×
340
    }
341
  }
342
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc