Skip to content
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,9 @@ public boolean execute(String action, JSONArray args, Callback callbackContext)
host.getActivity().runOnUiThread(() -> clearTokenCookie());
if (callbackContext != null) callbackContext.success();
return true;
case "isLoggedIn":
callbackContext.success(!prefManager.getString(KEY_TOKEN, "").isEmpty());
return true;
case "saveToken":
String token = args.getString(0);
Log.d(TAG, "Saving new token...");
Expand Down
3 changes: 3 additions & 0 deletions platforms/ios/runner/lib/security/AuthenticatorService.swift
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,9 @@ private final class SignInCoordinator: NSObject, ASWebAuthenticationPresentation
self.session = session
if !session.start() { fail(account ? "Unable to open account settings" : "Unable to open sign-in") }
} catch { self.callback = nil; callback.error(error.localizedDescription) }
case "isLoggedIn":
do { callback.success(!(try auth.token(for: URL(string: AppAuthentication.origin)!)).isEmpty) }
catch { callback.error(error.localizedDescription) }
case "saveToken", "logout":
cancel()
Task {
Expand Down
15 changes: 15 additions & 0 deletions src/lib/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,15 @@ class AuthService {
});
}

async #hasToken() {
try {
return Boolean(await this.#exec("isLoggedIn"));
} catch (error) {
console.error("Unable to read sign-in state:", error);
return true;
}
}

async logout() {
try {
const res = await fetch(`${config.API_BASE}/login`, {
Expand Down Expand Up @@ -116,6 +125,12 @@ class AuthService {
*/
async getLoggedInUser(forceFetch = false) {
if (loggedInUser && !forceFetch) return loggedInUser;
if (!(await this.#hasToken())) {
loggedInUser = null;
clearTimeout(cacheTimeout);
localStorage.removeItem(CACHE_USER_KEY);
return null;
}

try {
const res = await fetch(`${config.API_BASE}/login`, {
Expand Down
30 changes: 29 additions & 1 deletion tests/unit/auth.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ let auth;
let loginEvents;
let exec;
let request;
let hasToken;

beforeEach(async () => {
vi.resetModules();
Expand All @@ -23,7 +24,13 @@ beforeEach(async () => {
});
exec = vi.fn();
request = vi.fn();
vi.stubGlobal("Bridge", { exec });
hasToken = true;
vi.stubGlobal("Bridge", {
exec(resolve, reject, service, action, args) {
if (action === "isLoggedIn") return resolve(hasToken);
return exec(resolve, reject, service, action, args);
},
});
vi.stubGlobal("fetch", request);
({ default: auth, loginEvents } = await import("../../src/lib/auth"));
});
Expand Down Expand Up @@ -160,3 +167,24 @@ test("closing account settings offline skips refresh without reporting a signed-
exec.mock.calls[0][0]();
await expect(pending).resolves.toBeUndefined();
});

test("skips the account request when no sign-in token is stored", async () => {
hasToken = false;
localStorage.setItem("cached-logged-in-user", JSON.stringify({ id: 7 }));
await expect(auth.getLoggedInUser()).resolves.toBeNull();
await expect(auth.getLoggedInUser(true)).resolves.toBeNull();
expect(request).not.toHaveBeenCalled();
expect(localStorage["cached-logged-in-user"]).toBeUndefined();
});

test("falls back to the account request when the sign-in state is unreadable", async () => {
vi.spyOn(console, "error").mockImplementation(() => {});
vi.stubGlobal("Bridge", {
exec(resolve, reject) {
reject(new Error("Unsupported action"));
},
});
request.mockResolvedValueOnce(new Response(JSON.stringify({ id: 7 })));
await expect(auth.getLoggedInUser()).resolves.toEqual({ id: 7 });
expect(request).toHaveBeenCalledOnce();
});
Loading