| 13 | export const timeout = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); |
| 14 | |
| 15 | export const ConnectToGitHub = () => { |
| 16 | const opener = window.open(GITHUB_AUTH_URL, '_blank', OPEN_WINDOW_FEATURES); |
| 17 | |
| 18 | return new Promise((resolve) => { |
| 19 | const handleAuthMessage = (event: MessageEvent) => { |
| 20 | // Note that though the browser block opening window and popup a tip, |
| 21 | // the user can be still open it from the tip. In this case, the `opener` |
| 22 | // is null, and we should still process the authorizing message |
| 23 | const isValidOpener = !!(opener && event.source === opener); |
| 24 | const isValidOrigin = event.origin === AUTH_PAGE_ORIGIN; |
| 25 | const isValidResponse = event.data ? event.data.type === 'authorizing' : false; |
| 26 | if (!isValidOpener || !isValidOrigin || !isValidResponse) { |
| 27 | return; |
| 28 | } |
| 29 | window.removeEventListener('message', handleAuthMessage); |
| 30 | resolve(event.data?.payload); |
| 31 | }; |
| 32 | |
| 33 | window.addEventListener('message', handleAuthMessage); |
| 34 | // if there isn't any message from opener window in 300s, remove the message handler |
| 35 | timeout(300 * 1000).then(() => { |
| 36 | window.removeEventListener('message', handleAuthMessage); |
| 37 | resolve({ error: 'authorizing_timeout', error_description: 'Authorizing timeout' }); |
| 38 | }); |
| 39 | }); |
| 40 | }; |