|
3 | 3 | import { EditorContext } from "@/components/providers/editor-context-provider"; |
4 | 4 | import { Browser } from "@capacitor/browser"; |
5 | 5 | import { CapacitorCookies } from "@capacitor/core"; |
| 6 | +import { Preferences } from "@capacitor/preferences"; |
6 | 7 | import { useContext, useEffect } from "react"; |
7 | 8 | import useSWR from "swr"; |
8 | 9 | import { PlatformEnum } from "../enums"; |
@@ -60,14 +61,38 @@ export function useAuth() { |
60 | 61 | ); |
61 | 62 |
|
62 | 63 | useEffect(() => { |
63 | | - if (editorContext?.editorStates.isRefreshSession) { |
64 | | - mutate().then(() => { |
| 64 | + async function refreshSession() { |
| 65 | + if (editorContext?.editorStates.isRefreshSession) { |
| 66 | + const token = await Preferences.get({ |
| 67 | + key: "pulse-editor.session-token", |
| 68 | + }); |
| 69 | + |
| 70 | + /* |
| 71 | + Sometimes other hooks using useSWR are fired right after retuning from deep linking |
| 72 | + before session is refreshed (triggered by window re-focus), causing cookies to be |
| 73 | + set again between when it is removed (if removed in deep link handler) and when |
| 74 | + session is refreshed. |
| 75 | +
|
| 76 | + So a better approach is to clear cookies right here before refreshing session, but |
| 77 | + possibly after other hooks are fired. |
| 78 | + */ |
| 79 | + if (!token.value) { |
| 80 | + // CapacitorCookies.clearAllCookies(); |
| 81 | + CapacitorCookies.deleteCookie({ |
| 82 | + key: "pulse-editor.session-token", |
| 83 | + url: process.env.NEXT_PUBLIC_BACKEND_URL, |
| 84 | + }); |
| 85 | + } |
| 86 | + |
| 87 | + await mutate(); |
65 | 88 | editorContext.setEditorStates((prev) => ({ |
66 | 89 | ...prev, |
67 | 90 | isRefreshSession: false, |
68 | 91 | })); |
69 | | - }); |
| 92 | + } |
70 | 93 | } |
| 94 | + |
| 95 | + refreshSession(); |
71 | 96 | }, [editorContext?.editorStates.isRefreshSession]); |
72 | 97 |
|
73 | 98 | // Open a sign-in page if the user is not signed in. |
@@ -118,11 +143,6 @@ export function useAuth() { |
118 | 143 | process.env.NEXT_PUBLIC_BACKEND_URL + "/api/mobile", |
119 | 144 | ); |
120 | 145 | await Browser.open({ url: url.toString() }); |
121 | | - |
122 | | - await CapacitorCookies.deleteCookie({ |
123 | | - url: window.location.origin, |
124 | | - key: "pulse-editor.session-token", |
125 | | - }); |
126 | 146 | } else { |
127 | 147 | const url = getAPIUrl(`/api/auth/signout`); |
128 | 148 | url.searchParams.set("callbackUrl", window.location.href); |
|
0 commit comments