From aae82fbd2eb754a7fbbd77892016dd279e68b0f6 Mon Sep 17 00:00:00 2001 From: Enix Date: Tue, 5 Nov 2019 14:27:52 +0800 Subject: [PATCH] fix: catch oauth error --- src/components/SettingsBar.tsx | 29 +++++++++++++++++------------ src/utils/general.ts | 7 ++++--- 2 files changed, 21 insertions(+), 15 deletions(-) diff --git a/src/components/SettingsBar.tsx b/src/components/SettingsBar.tsx index 856a384..1aa686d 100644 --- a/src/components/SettingsBar.tsx +++ b/src/components/SettingsBar.tsx @@ -1,3 +1,4 @@ +import { raiseError } from 'analytics' import Icon from 'components/Icon' import { oauth } from 'env' import * as React from 'react' @@ -110,19 +111,23 @@ export default class SettingsBar extends React.PureComponent { } private async trySetUpAccessTokenWithCode() { - const search = parseURLSearch() - if ('code' in search) { - const res = await JSONRequest('https://github.com/login/oauth/access_token', { - code: search.code, - client_id: oauth.clientId, - client_secret: oauth.clientSecret, - }) - const { access_token: accessToken, scope } = res - if (scope !== 'repo' || !accessToken) { - throw new Error(`Cannot resolve token response: '${JSON.stringify(res)}'`) + try { + const search = parseURLSearch() + if ('code' in search) { + const res = await JSONRequest('https://github.com/login/oauth/access_token', { + code: search.code, + client_id: oauth.clientId, + client_secret: oauth.clientSecret, + }) + const { access_token: accessToken, scope } = res + if (scope !== 'repo' || !accessToken) { + throw new Error(`Cannot resolve token response: '${JSON.stringify(res)}'`) + } + window.history.pushState({}, 'removed code', window.location.pathname.replace(/#.*$/, '')) + this.setState({ accessToken }, () => this.saveToken('')) } - window.history.pushState({}, 'removed code', window.location.pathname.replace(/#.*$/, '')) - this.setState({ accessToken }, () => this.saveToken('')) + } catch (err) { + raiseError(err) } } diff --git a/src/utils/general.ts b/src/utils/general.ts index 9161a75..9fc3281 100644 --- a/src/utils/general.ts +++ b/src/utils/general.ts @@ -113,9 +113,8 @@ export function parseURLSearch(search: string = window.location.search) { return parsed } -export async function JSONRequest(url: string, data: any, method = 'post') { +export async function JSONRequest(url: string, data: any, extra: RequestInit = { method: 'post' }) { return (await fetch(url, { - method, mode: 'cors', cache: 'no-cache', credentials: 'same-origin', @@ -124,8 +123,10 @@ export async function JSONRequest(url: string, data: any, method = 'post') { Accept: 'application/json', }, redirect: 'follow', - referrer: 'no-referrer', + referrerPolicy: 'no-referrer', + method: extra.method || 'post', body: JSON.stringify(data), + ...extra, })).json() }