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

Elef/sign out snapshot #5205

Closed
wants to merge 17 commits into from
Closed
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
5 changes: 5 additions & 0 deletions .changeset/dry-tigers-mate.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@clerk/clerk-js': patch
---

Fixes an issue where calling `signOut()` would not always redirect.
5 changes: 5 additions & 0 deletions .changeset/thick-beds-beam.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@clerk/clerk-js': patch
---

Avoid client updates on sign out.
34 changes: 10 additions & 24 deletions packages/clerk-js/src/core/__tests__/clerk.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -587,16 +587,13 @@ describe('Clerk singleton', () => {
);

const sut = new Clerk(productionPublishableKey);
sut.setActive = jest.fn();
sut.navigate = jest.fn();
await sut.load();
await sut.signOut();
await waitFor(() => {
expect(mockClientDestroy).not.toHaveBeenCalled();
expect(mockClientRemoveSessions).toHaveBeenCalled();
expect(sut.setActive).toHaveBeenCalledWith({
session: null,
redirectUrl: '/',
});
expect(sut.navigate).toHaveBeenCalledWith('/');
});
});

Expand All @@ -613,17 +610,14 @@ describe('Clerk singleton', () => {
);

const sut = new Clerk(productionPublishableKey);
sut.setActive = jest.fn();
sut.navigate = jest.fn();
await sut.load();
await sut.signOut();
await waitFor(() => {
expect(mockClientDestroy).not.toHaveBeenCalled();
expect(mockClientRemoveSessions).toHaveBeenCalled();
expect(mockSession1.remove).not.toHaveBeenCalled();
expect(sut.setActive).toHaveBeenCalledWith({
session: null,
redirectUrl: '/',
});
expect(sut.navigate).toHaveBeenCalledWith('/');
});
},
);
Expand All @@ -638,15 +632,13 @@ describe('Clerk singleton', () => {
);

const sut = new Clerk(productionPublishableKey);
sut.setActive = jest.fn();
sut.navigate = jest.fn();
await sut.load();
await sut.signOut({ sessionId: '2' });
await waitFor(() => {
expect(mockSession2.remove).toHaveBeenCalled();
expect(mockClientDestroy).not.toHaveBeenCalled();
expect(sut.setActive).not.toHaveBeenCalledWith({
session: null,
});
expect(sut.navigate).not.toHaveBeenCalled();
});
});

Expand All @@ -660,16 +652,13 @@ describe('Clerk singleton', () => {
);

const sut = new Clerk(productionPublishableKey);
sut.setActive = jest.fn();
sut.navigate = jest.fn();
await sut.load();
await sut.signOut({ sessionId: '1' });
await waitFor(() => {
expect(mockSession1.remove).toHaveBeenCalled();
expect(mockClientDestroy).not.toHaveBeenCalled();
expect(sut.setActive).toHaveBeenCalledWith({
session: null,
redirectUrl: '/',
});
expect(sut.navigate).toHaveBeenCalledWith('/');
});
});

Expand All @@ -683,16 +672,13 @@ describe('Clerk singleton', () => {
);

const sut = new Clerk(productionPublishableKey);
sut.setActive = jest.fn();
sut.navigate = jest.fn();
await sut.load();
await sut.signOut({ sessionId: '1', redirectUrl: '/after-sign-out' });
await waitFor(() => {
expect(mockSession1.remove).toHaveBeenCalled();
expect(mockClientDestroy).not.toHaveBeenCalled();
expect(sut.setActive).toHaveBeenCalledWith({
session: null,
redirectUrl: '/after-sign-out',
});
expect(sut.navigate).toHaveBeenCalledWith('/after-sign-out');
});
});
});
Expand Down
106 changes: 66 additions & 40 deletions packages/clerk-js/src/core/clerk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,6 @@ import {
getClerkQueryParam,
getWeb3Identifier,
hasExternalAccountSignUpError,
ignoreEventValue,
inActiveBrowserTab,
inBrowser,
isDevAccountPortalOrigin,
Expand Down Expand Up @@ -128,6 +127,8 @@ import {
} from './resources/internal';
import { warnings } from './warnings';

type SetActiveHook = () => void | Promise<void>;

export type ClerkCoreBroadcastChannelEvent = { type: 'signout' };

declare global {
Expand Down Expand Up @@ -372,43 +373,72 @@ export class Clerk implements ClerkInterface {
if (!this.client || this.client.sessions.length === 0) {
return;
}

const onBeforeSetActive: SetActiveHook =
typeof window !== 'undefined' && typeof window.__unstable__onBeforeSetActive === 'function'
? window.__unstable__onBeforeSetActive
: noop;

const onAfterSetActive: SetActiveHook =
typeof window !== 'undefined' && typeof window.__unstable__onAfterSetActive === 'function'
? window.__unstable__onAfterSetActive
: noop;

const opts = callbackOrOptions && typeof callbackOrOptions === 'object' ? callbackOrOptions : options || {};

const redirectUrl = opts?.redirectUrl || this.buildAfterSignOutUrl();
const signOutCallback = typeof callbackOrOptions === 'function' ? callbackOrOptions : undefined;

const handleSetActive = () => {
const signOutCallback = typeof callbackOrOptions === 'function' ? callbackOrOptions : undefined;
const executeSignOut = async () => {
const tracker = createBeforeUnloadTracker(this.#options.standardBrowser);

// Notify other tabs that user is signing out.
eventBus.dispatch(events.UserSignOut, null);
if (signOutCallback) {
return this.setActive({
session: null,
beforeEmit: ignoreEventValue(signOutCallback),
});
}
// Clearn up cookies
eventBus.dispatch(events.TokenUpdate, { token: null });

return this.setActive({
session: null,
redirectUrl,
this.#setTransitiveState();

await tracker.track(async () => {
if (signOutCallback) {
await signOutCallback();
} else {
await this.navigate(redirectUrl);
}
});

if (tracker.isUnloading()) {
return;
}

this.#setAccessors();
this.#emit();

await onAfterSetActive();
};

await onBeforeSetActive();

if (!opts.sessionId || this.client.signedInSessions.length === 1) {
if (this.#options.experimental?.persistClient ?? true) {
await this.client.removeSessions();
} else {
await this.client.destroy();
}

return handleSetActive();
await executeSignOut();

return;
}

// Multi-session handling
const session = this.client.signedInSessions.find(s => s.id === opts.sessionId);
const shouldSignOutCurrent = session?.id && this.session?.id === session.id;

await session?.remove();

if (shouldSignOutCurrent) {
return handleSetActive();
await executeSignOut();
}
};

Expand Down Expand Up @@ -872,7 +902,6 @@ export class Clerk implements ClerkInterface {
);
}

type SetActiveHook = () => void | Promise<void>;
const onBeforeSetActive: SetActiveHook =
typeof window !== 'undefined' && typeof window.__unstable__onBeforeSetActive === 'function'
? window.__unstable__onBeforeSetActive
Expand Down Expand Up @@ -934,40 +963,41 @@ export class Clerk implements ClerkInterface {
// undefined, then wait for beforeEmit to complete before emitting the new session.
// When undefined, neither SignedIn nor SignedOut renders, which avoids flickers or
// automatic reloading when reloading shouldn't be happening.
const beforeUnloadTracker = this.#options.standardBrowser ? createBeforeUnloadTracker() : undefined;
const tracker = createBeforeUnloadTracker(this.#options.standardBrowser);

if (beforeEmit) {
deprecated(
'Clerk.setActive({beforeEmit})',
'Use the `redirectUrl` property instead. Example `Clerk.setActive({redirectUrl:"/"})`',
);
beforeUnloadTracker?.startTracking();
this.#setTransitiveState();
await beforeEmit(newSession);
beforeUnloadTracker?.stopTracking();
await tracker.track(async () => {
this.#setTransitiveState();
await beforeEmit(newSession);
});
}

if (redirectUrl && !beforeEmit) {
beforeUnloadTracker?.startTracking();
this.#setTransitiveState();

if (this.client.isEligibleForTouch()) {
const absoluteRedirectUrl = new URL(redirectUrl, window.location.href);

await this.navigate(this.buildUrlWithAuth(this.client.buildTouchUrl({ redirectUrl: absoluteRedirectUrl })));
} else {
await this.navigate(redirectUrl);
}

beforeUnloadTracker?.stopTracking();
await tracker.track(async () => {
if (!this.client) {
// Typescript is not happy because since thinks this.client might have changed to undefined because the function is asynchronous.
return;
}
this.#setTransitiveState();
if (this.client.isEligibleForTouch()) {
const absoluteRedirectUrl = new URL(redirectUrl, window.location.href);
await this.navigate(this.buildUrlWithAuth(this.client.buildTouchUrl({ redirectUrl: absoluteRedirectUrl })));
} else {
await this.navigate(redirectUrl);
}
});
}

//3. Check if hard reloading (onbeforeunload). If not, set the user/session and emit
if (beforeUnloadTracker?.isUnloading()) {
//3. Check if hard reloading (onbeforeunload). If not, set the user/session and emit
if (tracker.isUnloading()) {
return;
}

this.#setAccessors(newSession);

this.#emit();
await onAfterSetActive();
};
Expand Down Expand Up @@ -2127,17 +2157,13 @@ export class Clerk implements ClerkInterface {
#setAccessors = (session?: SignedInSessionResource | null) => {
this.session = session || null;
this.organization = this.#getLastActiveOrganizationFromSession();
this.#aliasUser();
this.user = this.session ? this.session.user : null;
};

#getSessionFromClient = (sessionId: string | undefined): SignedInSessionResource | null => {
return this.client?.signedInSessions.find(x => x.id === sessionId) || null;
};

#aliasUser = () => {
this.user = this.session ? this.session.user : null;
};

#handleImpersonationFab = () => {
this.addListener(({ session }) => {
const isImpersonating = !!session?.actor;
Expand Down
13 changes: 10 additions & 3 deletions packages/clerk-js/src/core/resources/Base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,15 @@ import { ClerkAPIResponseError, ClerkRuntimeError, Client } from './internal';
export type BaseFetchOptions = ClerkResourceReloadParams & {
forceUpdateClient?: boolean;
fetchMaxTries?: number;
skipUpdateClient?: boolean;
};

export type BaseMutateParams = {
action?: string;
body?: any;
method?: HTTPMethod;
path?: string;
skipUpdateClient?: boolean;
};

function assertProductionKeysOnDev(statusCode: number, payloadErrors?: ClerkAPIErrorJSON[]) {
Expand Down Expand Up @@ -105,7 +107,7 @@ export abstract class BaseResource {
}

// TODO: Link to Client payload piggybacking design document
if (requestInit.method !== 'GET' || opts.forceUpdateClient) {
if ((requestInit.method !== 'GET' || opts.forceUpdateClient) && !opts.skipUpdateClient) {
this._updateClient<J>(payload);
}

Expand Down Expand Up @@ -180,8 +182,13 @@ export abstract class BaseResource {
}

protected async _baseMutate<J extends ClerkResourceJSON | null>(params: BaseMutateParams): Promise<this> {
const { action, body, method, path } = params;
const json = await BaseResource._fetch<J>({ method, path: path || this.path(action), body });
const { action, body, method, path, skipUpdateClient } = params;
let json;
if (skipUpdateClient) {
json = await BaseResource._fetch<J>({ method, path: path || this.path(action), body }, { skipUpdateClient });
} else {
json = await BaseResource._fetch<J>({ method, path: path || this.path(action), body });
}
return this.fromJSON((json?.response || json) as J);
}

Expand Down
5 changes: 5 additions & 0 deletions packages/clerk-js/src/core/resources/Client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,11 @@ export class Client extends BaseResource implements ClientResource {
removeSessions(): Promise<ClientResource> {
return this._baseDelete({
path: this.path() + '/sessions',
/**
* Skipping updating the client matches the behaviour of `client.destroy`, which allows broadcasting a sign-out event,
* and delays emitting until `setActive` is called within `Clerk.signOut()`
*/
skipUpdateClient: true,
}).then(e => {
SessionTokenCache.clear();
return e as unknown as ClientResource;
Expand Down
5 changes: 5 additions & 0 deletions packages/clerk-js/src/core/resources/Session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,11 @@ export class Session extends BaseResource implements SessionResource {
SessionTokenCache.clear();
return this._basePost({
action: 'remove',
/**
* Skipping updating the client matches the behaviour of `client.destroy`, which allows broadcasting a sign-out event,
* and delays emitting until `setActive` is called within `Clerk.signOut()`
*/
skipUpdateClient: true,
});
};

Expand Down
Loading