Skip to content

refactor the logic of refreshing access_token #10068

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Nov 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions web/app/account/avatar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,9 @@ export default function AppSelector() {
params: {},
})

if (localStorage?.getItem('console_token'))
localStorage.removeItem('console_token')
localStorage.removeItem('setup_status')
localStorage.removeItem('console_token')
localStorage.removeItem('refresh_token')

router.push('/signin')
}
Expand Down
5 changes: 3 additions & 2 deletions web/app/components/header/account-dropdown/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,9 @@ export default function AppSelector({ isMobile }: IAppSelector) {
params: {},
})

if (localStorage?.getItem('console_token'))
localStorage.removeItem('console_token')
localStorage.removeItem('setup_status')
localStorage.removeItem('console_token')
localStorage.removeItem('refresh_token')

router.push('/signin')
}
Expand Down
39 changes: 12 additions & 27 deletions web/app/components/swr-initor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import { SWRConfig } from 'swr'
import { useCallback, useEffect, useState } from 'react'
import type { ReactNode } from 'react'
import { usePathname, useRouter, useSearchParams } from 'next/navigation'
import useRefreshToken from '@/hooks/use-refresh-token'
import { fetchSetupStatus } from '@/service/common'

type SwrInitorProps = {
Expand All @@ -15,12 +14,11 @@ const SwrInitor = ({
}: SwrInitorProps) => {
const router = useRouter()
const searchParams = useSearchParams()
const pathname = usePathname()
const { getNewAccessToken } = useRefreshToken()
const consoleToken = searchParams.get('access_token')
const refreshToken = searchParams.get('refresh_token')
const consoleToken = decodeURIComponent(searchParams.get('access_token') || '')
const refreshToken = decodeURIComponent(searchParams.get('refresh_token') || '')
const consoleTokenFromLocalStorage = localStorage?.getItem('console_token')
const refreshTokenFromLocalStorage = localStorage?.getItem('refresh_token')
const pathname = usePathname()
const [init, setInit] = useState(false)

const isSetupFinished = useCallback(async () => {
Expand All @@ -41,25 +39,6 @@ const SwrInitor = ({
}
}, [])

const setRefreshToken = useCallback(async () => {
try {
if (!(consoleToken || refreshToken || consoleTokenFromLocalStorage || refreshTokenFromLocalStorage))
return Promise.reject(new Error('No token found'))

if (consoleTokenFromLocalStorage && refreshTokenFromLocalStorage)
await getNewAccessToken()

if (consoleToken && refreshToken) {
localStorage.setItem('console_token', consoleToken)
localStorage.setItem('refresh_token', refreshToken)
await getNewAccessToken()
}
}
catch (error) {
return Promise.reject(error)
}
}, [consoleToken, refreshToken, consoleTokenFromLocalStorage, refreshTokenFromLocalStorage, getNewAccessToken])

useEffect(() => {
(async () => {
try {
Expand All @@ -68,17 +47,23 @@ const SwrInitor = ({
router.replace('/install')
return
}
await setRefreshToken()
if (searchParams.has('access_token') || searchParams.has('refresh_token'))
if (!((consoleToken && refreshToken) || (consoleTokenFromLocalStorage && refreshTokenFromLocalStorage))) {
router.replace('/signin')
return
}
if (searchParams.has('access_token') || searchParams.has('refresh_token')) {
consoleToken && localStorage.setItem('console_token', consoleToken)
refreshToken && localStorage.setItem('refresh_token', refreshToken)
router.replace(pathname)
}

setInit(true)
}
catch (error) {
router.replace('/signin')
}
})()
}, [isSetupFinished, setRefreshToken, router, pathname, searchParams])
}, [isSetupFinished, router, pathname, searchParams, consoleToken, refreshToken, consoleTokenFromLocalStorage, refreshTokenFromLocalStorage])

return init
? (
Expand Down
5 changes: 1 addition & 4 deletions web/app/signin/normalForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,9 @@ import cn from '@/utils/classnames'
import { getSystemFeatures, invitationCheck } from '@/service/common'
import { defaultSystemFeatures } from '@/types/feature'
import Toast from '@/app/components/base/toast'
import useRefreshToken from '@/hooks/use-refresh-token'
import { IS_CE_EDITION } from '@/config'

const NormalForm = () => {
const { getNewAccessToken } = useRefreshToken()
const { t } = useTranslation()
const router = useRouter()
const searchParams = useSearchParams()
Expand All @@ -38,7 +36,6 @@ const NormalForm = () => {
if (consoleToken && refreshToken) {
localStorage.setItem('console_token', consoleToken)
localStorage.setItem('refresh_token', refreshToken)
getNewAccessToken()
router.replace('/apps')
return
}
Expand Down Expand Up @@ -71,7 +68,7 @@ const NormalForm = () => {
setSystemFeatures(defaultSystemFeatures)
}
finally { setIsLoading(false) }
}, [consoleToken, refreshToken, message, router, invite_token, isInviteLink, getNewAccessToken])
}, [consoleToken, refreshToken, message, router, invite_token, isInviteLink])
useEffect(() => {
init()
}, [init])
Expand Down
99 changes: 0 additions & 99 deletions web/hooks/use-refresh-token.ts

This file was deleted.

130 changes: 78 additions & 52 deletions web/service/base.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { refreshAccessTokenOrRelogin } from './refresh-token'
import { API_PREFIX, IS_CE_EDITION, PUBLIC_API_PREFIX } from '@/config'
import Toast from '@/app/components/base/toast'
import type { AnnotationReply, MessageEnd, MessageReplace, ThoughtItem } from '@/app/components/base/chat/chat/type'
Expand Down Expand Up @@ -356,39 +357,8 @@ const baseFetch = <T>(
if (!/^(2|3)\d{2}$/.test(String(res.status))) {
const bodyJson = res.json()
switch (res.status) {
case 401: {
if (isPublicAPI) {
return bodyJson.then((data: ResponseError) => {
if (data.code === 'web_sso_auth_required')
requiredWebSSOLogin()

if (data.code === 'unauthorized') {
removeAccessToken()
globalThis.location.reload()
}

return Promise.reject(data)
})
}
const loginUrl = `${globalThis.location.origin}/signin`
bodyJson.then((data: ResponseError) => {
if (data.code === 'init_validate_failed' && IS_CE_EDITION && !silent)
Toast.notify({ type: 'error', message: data.message, duration: 4000 })
else if (data.code === 'not_init_validated' && IS_CE_EDITION)
globalThis.location.href = `${globalThis.location.origin}/init`
else if (data.code === 'not_setup' && IS_CE_EDITION)
globalThis.location.href = `${globalThis.location.origin}/install`
else if (location.pathname !== '/signin' || !IS_CE_EDITION)
globalThis.location.href = loginUrl
else if (!silent)
Toast.notify({ type: 'error', message: data.message })
}).catch(() => {
// Handle any other errors
globalThis.location.href = loginUrl
})

break
}
case 401:
return Promise.reject(resClone)
case 403:
bodyJson.then((data: ResponseError) => {
if (!silent)
Expand Down Expand Up @@ -484,7 +454,9 @@ export const upload = (options: any, isPublicAPI?: boolean, url?: string, search
export const ssePost = (
url: string,
fetchOptions: FetchOptionType,
{
otherOptions: IOtherOptions,
) => {
const {
isPublicAPI = false,
onData,
onCompleted,
Expand All @@ -507,8 +479,7 @@ export const ssePost = (
onTextReplace,
onError,
getAbortController,
}: IOtherOptions,
) => {
} = otherOptions
const abortController = new AbortController()

const options = Object.assign({}, baseOptions, {
Expand All @@ -532,21 +503,29 @@ export const ssePost = (
globalThis.fetch(urlWithPrefix, options as RequestInit)
.then((res) => {
if (!/^(2|3)\d{2}$/.test(String(res.status))) {
res.json().then((data: any) => {
if (isPublicAPI) {
if (data.code === 'web_sso_auth_required')
requiredWebSSOLogin()

if (data.code === 'unauthorized') {
removeAccessToken()
globalThis.location.reload()
}
if (res.status === 401)
return
}
Toast.notify({ type: 'error', message: data.message || 'Server Error' })
})
onError?.('Server Error')
if (res.status === 401) {
refreshAccessTokenOrRelogin(TIME_OUT).then(() => {
ssePost(url, fetchOptions, otherOptions)
}).catch(() => {
res.json().then((data: any) => {
if (isPublicAPI) {
if (data.code === 'web_sso_auth_required')
requiredWebSSOLogin()

if (data.code === 'unauthorized') {
removeAccessToken()
globalThis.location.reload()
}
}
})
})
}
else {
res.json().then((data) => {
Toast.notify({ type: 'error', message: data.message || 'Server Error' })
})
onError?.('Server Error')
}
return
}
return handleStream(res, (str: string, isFirstMessage: boolean, moreInfo: IOnDataMoreInfo) => {
Expand All @@ -568,7 +547,54 @@ export const ssePost = (

// base request
export const request = <T>(url: string, options = {}, otherOptions?: IOtherOptions) => {
return baseFetch<T>(url, options, otherOptions || {})
return new Promise<T>((resolve, reject) => {
const otherOptionsForBaseFetch = otherOptions || {}
baseFetch<T>(url, options, otherOptionsForBaseFetch).then(resolve).catch((errResp) => {
if (errResp?.status === 401) {
return refreshAccessTokenOrRelogin(TIME_OUT).then(() => {
baseFetch<T>(url, options, otherOptionsForBaseFetch).then(resolve).catch(reject)
}).catch(() => {
const {
isPublicAPI = false,
silent,
} = otherOptionsForBaseFetch
const bodyJson = errResp.json()
if (isPublicAPI) {
return bodyJson.then((data: ResponseError) => {
if (data.code === 'web_sso_auth_required')
requiredWebSSOLogin()

if (data.code === 'unauthorized') {
removeAccessToken()
globalThis.location.reload()
}

return Promise.reject(data)
})
}
const loginUrl = `${globalThis.location.origin}/signin`
bodyJson.then((data: ResponseError) => {
if (data.code === 'init_validate_failed' && IS_CE_EDITION && !silent)
Toast.notify({ type: 'error', message: data.message, duration: 4000 })
else if (data.code === 'not_init_validated' && IS_CE_EDITION)
globalThis.location.href = `${globalThis.location.origin}/init`
else if (data.code === 'not_setup' && IS_CE_EDITION)
globalThis.location.href = `${globalThis.location.origin}/install`
else if (location.pathname !== '/signin' || !IS_CE_EDITION)
globalThis.location.href = loginUrl
else if (!silent)
Toast.notify({ type: 'error', message: data.message })
}).catch(() => {
// Handle any other errors
globalThis.location.href = loginUrl
})
})
}
else {
reject(errResp)
}
})
})
}

// request methods
Expand Down
Loading
Loading