Skip to content
This repository has been archived by the owner on Dec 7, 2021. It is now read-only.

Commit

Permalink
Merge pull request #102 from jamesreggio/add-appstate-callbacks
Browse files Browse the repository at this point in the history
Abandon auth dance if app becomes active without a callback URL
  • Loading branch information
adamjmcgrath authored Jul 17, 2018
2 parents 2f5d80d + 6e88f59 commit 5a4d47d
Showing 1 changed file with 35 additions and 10 deletions.
45 changes: 35 additions & 10 deletions lib/platforms/react-native.js
Original file line number Diff line number Diff line change
@@ -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) => {
Expand All @@ -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;
}));
};

Expand Down

0 comments on commit 5a4d47d

Please sign in to comment.