fix: catch oauth error

This commit is contained in:
Enix 2019-11-05 14:27:52 +08:00
parent 75e914de40
commit aae82fbd2e
No known key found for this signature in database
GPG key ID: FE06F5DFC1C9B8E4
2 changed files with 21 additions and 15 deletions

View file

@ -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<Props, State> {
}
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)
}
}

View file

@ -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()
}