Skip to content
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

feat: added async getSession/getUser method #285

Merged
merged 3 commits into from
Jun 4, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
57 changes: 55 additions & 2 deletions src/GoTrueClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
removeItemAsync,
getItemSynchronously,
getItemAsync,
Deferred,
} from './lib/helpers'
import {
GOTRUE_URL,
Expand Down Expand Up @@ -65,7 +66,11 @@ export default class GoTrueClient {
protected multiTab: boolean
protected stateChangeEmitters: Map<string, Subscription> = new Map()
protected refreshTokenTimer?: ReturnType<typeof setTimeout>
protected networkRetries: number = 0
protected networkRetries = 0
protected refreshingDeferred: Deferred<{
data: Session
error: null
}> | null = null

/**
* Create a new client for use in the browser.
Expand Down Expand Up @@ -330,6 +335,39 @@ export default class GoTrueClient {
return this.currentSession
}

async getSession(): Promise<
alaister marked this conversation as resolved.
Show resolved Hide resolved
| {
session: Session
error: null
}
| {
session: null
error: ApiError
}
| {
session: null
error: null
}
> {
if (!this.currentSession) {
return { session: null, error: null }
}

const hasExpired = this.currentSession.expires_at
? this.currentSession.expires_at <= Date.now() / 1000
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

have some threshold here? we already have a constate for this i think

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is it needed here? If this handler works for only refreshing the token if it's already somehow expired, and the regular refresh timer handles refreshing tokens early, users rarely have to wait for the refresh request before their normal request.

Not opposed to it, just wondering what the benefits are vs the drawbacks?

: false
if (!hasExpired) {
return { session: this.currentSession, error: null }
}

const { data: session, error } = await this.refreshSession()
if (error) {
return { session: null, error }
}

return { session, error: null }
}

/**
* Force refreshes the session including the user data in case it was updated in a different session.
*/
Expand Down Expand Up @@ -681,6 +719,16 @@ export default class GoTrueClient {

private async _callRefreshToken(refresh_token = this.currentSession?.refresh_token) {
try {
// refreshing is already in progress
if (this.refreshingDeferred) {
return await this.refreshingDeferred.promise
}

this.refreshingDeferred = new Deferred<{
data: Session
error: null
}>()

if (!refresh_token) {
throw new Error('No current session.')
}
Expand All @@ -692,7 +740,12 @@ export default class GoTrueClient {
this._notifyAllSubscribers('TOKEN_REFRESHED')
this._notifyAllSubscribers('SIGNED_IN')

return { data, error: null }
const result = { data, error: null }

this.refreshingDeferred.resolve(result)
this.refreshingDeferred = null

return result
} catch (e) {
return { data: null, error: e as ApiError }
}
Expand Down
22 changes: 22 additions & 0 deletions src/lib/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,3 +75,25 @@ export const getItemSynchronously = (storage: SupportedStorage, key: string): an
export const removeItemAsync = async (storage: SupportedStorage, key: string): Promise<void> => {
isBrowser() && (await storage?.removeItem(key))
}

/**
* A deferred represents some asynchronous work that is not yet finished, which
* may or may not culminate in a value.
* Taken from: https://github.com/mike-north/types/blob/master/src/async.ts
*/
export class Deferred<T = any> {
public static promiseConstructor: PromiseConstructor = Promise

public readonly promise!: PromiseLike<T>

public readonly resolve!: (value?: T | PromiseLike<T>) => void

public readonly reject!: (reason?: any) => any

public constructor() {
(this as any).promise = new Deferred.promiseConstructor((res, rej) => {
(this as any).resolve = res
;(this as any).reject = rej
})
}
}
84 changes: 84 additions & 0 deletions test/GoTrueClient.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,12 @@ import {
import { mockUserCredentials } from './lib/utils'

describe('GoTrueClient', () => {
const refreshAccessTokenSpy = jest.spyOn(authWithSession.api, 'refreshAccessToken')

afterEach(async () => {
await auth.signOut()
await authWithSession.signOut()
refreshAccessTokenSpy.mockClear()
})

describe('Sessions', () => {
Expand Down Expand Up @@ -51,6 +54,87 @@ describe('GoTrueClient', () => {
expect(userSession).toHaveProperty('user')
})

test('getSession() should return the currentUser session', async () => {
const { email, password } = mockUserCredentials()

const { error, session } = await authWithSession.signUp({
email,
password,
})

expect(error).toBeNull()
expect(session).not.toBeNull()

const { session: userSession, error: userError } = await authWithSession.getSession()

expect(userError).toBeNull()
expect(userSession).not.toBeNull()
expect(userSession).toHaveProperty('access_token')
})

test('getSession() should refresh the session', async () => {
const { email, password } = mockUserCredentials()

const { error, session } = await authWithSession.signUp({
email,
password,
})

expect(error).toBeNull()
expect(session).not.toBeNull()

const expired = new Date()
expired.setMinutes(expired.getMinutes() - 1)
const expiredSeconds = Math.floor(expired.getTime() / 1000)

// @ts-expect-error 'Allow access to protected currentSession'
authWithSession.currentSession = {
// @ts-expect-error 'Allow access to protected currentSession'
...authWithSession.currentSession,
expires_at: expiredSeconds,
}

const { session: userSession, error: userError } = await authWithSession.getSession()

expect(userError).toBeNull()
expect(userSession).not.toBeNull()
expect(userSession).toHaveProperty('access_token')
expect(refreshAccessTokenSpy).toBeCalledTimes(1)

// @kangmingtay Looks like this fails due to the 10 second reuse interval
// returning back the same session. It works with a long timeout before getSession().
// Do we want the reuse interval to apply for the initial login session?
// expect(session!.access_token).not.toEqual(userSession!.access_token)
})

test('refresh should only happen once', async () => {
const { email, password } = mockUserCredentials()

const { error, session } = await authWithSession.signUp({
email,
password,
})

expect(error).toBeNull()
expect(session).not.toBeNull()

const [{ data: data1, error: error1 }, { data: data2, error: error2 }] = await Promise.all([
authWithSession.refreshSession(),
authWithSession.refreshSession(),
])

expect(error1).toBeNull()
expect(error2).toBeNull()
expect(data1).toHaveProperty('access_token')
expect(data2).toHaveProperty('access_token')

// if both have the same access token, we can assume that they are
// the result of the same refresh
expect(data1!.access_token).toEqual(data2!.access_token)

expect(refreshAccessTokenSpy).toBeCalledTimes(1)
})

test('getSessionFromUrl() can only be called from a browser', async () => {
const { error, data } = await authWithSession.getSessionFromUrl()

Expand Down