From 6e88f59567473d7924bbc71320bbf3b96e88adfb Mon Sep 17 00:00:00 2001 From: James Reggio Date: Mon, 2 Jul 2018 16:40:16 -0400 Subject: [PATCH] Abandon auth if app becomes active without a deeplink --- lib/platforms/react-native.js | 45 +++++++++++++++++++++++++++-------- 1 file changed, 35 insertions(+), 10 deletions(-) diff --git a/lib/platforms/react-native.js b/lib/platforms/react-native.js index d69e0fb..cba0000 100644 --- a/lib/platforms/react-native.js +++ b/lib/platforms/react-native.js @@ -1,12 +1,26 @@ -import { Linking } from 'react-native'; // eslint-disable-line import/no-unresolved, max-len +import { Linking, AppState } from 'react-native'; // eslint-disable-line import/no-unresolved, max-len -let previousOnLinkChange; +let appStateTimeout; +let previousLinkingCallback; +let previousAppStateCallback; -export const dance = (authUrl) => { - if (previousOnLinkChange) { - Linking.removeEventListener('url', previousOnLinkChange); +const cleanup = () => { + clearTimeout(appStateTimeout); + + if (previousLinkingCallback) { + Linking.removeEventListener('url', previousLinkingCallback); + previousLinkingCallback = null; } + if (previousAppStateCallback) { + AppState.removeEventListener('change', previousAppStateCallback); + previousAppStateCallback = null; + } +}; + +export const dance = (authUrl) => { + cleanup(); + return Linking.openURL(authUrl) .then(() => new Promise((resolve, reject) => { const handleUrl = (url) => { @@ -17,15 +31,26 @@ export const dance = (authUrl) => { } }; - const onLinkChange = ({ url }) => { - Linking.removeEventListener('url', onLinkChange); - previousOnLinkChange = undefined; + const linkingCallback = ({ url }) => { + cleanup(); handleUrl(url); }; - Linking.addEventListener('url', onLinkChange); + Linking.addEventListener('url', linkingCallback); + previousLinkingCallback = linkingCallback; + + const appStateCallback = (state) => { + // Give time for Linking event to fire. + appStateTimeout = setTimeout(() => { + if (state === 'active') { + cleanup(); + reject('cancelled'); + } + }, 100); + }; - previousOnLinkChange = onLinkChange; + AppState.addEventListener('change', appStateCallback); + previousAppStateCallback = appStateCallback; })); };