Skip to content

Commit

Permalink
feat: remove session, emit SIGNED_OUT when JWT session_id is invalid
Browse files Browse the repository at this point in the history
  • Loading branch information
hf committed May 12, 2024
1 parent 4ecfdda commit 6bbcf92
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 0 deletions.
10 changes: 10 additions & 0 deletions src/GoTrueClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
isAuthApiError,
isAuthError,
isAuthRetryableFetchError,
isAuthSessionMissingError,
} from './lib/errors'
import {
Fetch,
Expand Down Expand Up @@ -1194,6 +1195,15 @@ export default class GoTrueClient {
})
} catch (error) {
if (isAuthError(error)) {
if (isAuthSessionMissingError(error)) {
// JWT contains a `session_id` which does not correspond to an active
// session in the database, indicating the user is signed out.

await this._removeSession()
await removeItemAsync(this.storage, `${this.storageKey}-code-verifier`)
await this._notifyAllSubscribers('SIGNED_OUT', null)
}

return { data: { user: null }, error }
}

Expand Down
4 changes: 4 additions & 0 deletions src/lib/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,10 @@ export class AuthSessionMissingError extends CustomAuthError {
}
}

export function isAuthSessionMissingError(error: any): error is AuthSessionMissingError {
return isAuthError(error) && error.name === 'AuthSessionMissingError'
}

export class AuthInvalidTokenResponseError extends CustomAuthError {
constructor() {
super('Auth session or user missing', 'AuthInvalidTokenResponseError', 500, undefined)
Expand Down
6 changes: 6 additions & 0 deletions src/lib/fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import {
AuthRetryableFetchError,
AuthWeakPasswordError,
AuthUnknownError,
AuthSessionMissingError,
} from './errors'

export type Fetch = typeof fetch
Expand Down Expand Up @@ -91,6 +92,11 @@ export async function handleError(error: unknown) {
error.status,
data.weak_password?.reasons || []
)
} else if (errorCode === 'session_not_found') {
// The `session_id` inside the JWT does not correspond to a row in the
// `sessions` table. This usually means the user has signed out, has been
// deleted, or their session has somehow been terminated.
throw new AuthSessionMissingError()
}

throw new AuthApiError(_getErrorMessage(data), error.status || 500, errorCode)
Expand Down

0 comments on commit 6bbcf92

Please sign in to comment.