Skip to content

Commit

Permalink
fix: refresh not work
Browse files Browse the repository at this point in the history
  • Loading branch information
ronger-x committed Apr 28, 2024
1 parent cec79ba commit 73eeba8
Showing 1 changed file with 6 additions and 40 deletions.
46 changes: 6 additions & 40 deletions src/runtime/composables/refresh/use-auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import { useAuthFetch } from '../use-auth-fetch'
import { logger } from '../../utils/logger'
import { useAuth as useLocalAuth } from '../local/use-auth'
import { useAuthState } from './use-auth-state'
import type { SessionData } from '#auth'
import { navigateTo, useRuntimeConfig } from '#imports'

/**
Expand All @@ -16,55 +15,22 @@ const getSession: ReturnType<typeof useLocalAuth>['getSession'] = async (
getSessionOptions = {},
) => {
const config = useTypedConfig(useRuntimeConfig(), 'refresh')
const { path, method } = config.endpoints.getSession

const { token, loading, data, refreshToken, lastRefreshedAt, clearToken } = useAuthState()
const { token, refreshToken, lastRefreshedAt } = useAuthState()

let authToken = token.value

if (!authToken && !getSessionOptions.force) {
if (!token.value && !getSessionOptions.force) {
return
}
if (authToken && refreshToken.value && lastRefreshedAt && lastRefreshedAt.value) {
if (token.value && refreshToken.value && lastRefreshedAt && lastRefreshedAt.value) {
const isTokenExpired =
new Date().getTime() - lastRefreshedAt.value.getTime() > config.token.maxAgeInSeconds * 1000
if (isTokenExpired) {
await refresh({ refreshToken: refreshToken.value })
authToken = useAuthState().token.value
}
}

const headers = new Headers(authToken ? { [config.token.headerName]: authToken } : undefined)

loading.value = true

try {
const response = await useAuthFetch<Record<string, any>>(path, undefined, method, { headers })

// 根据 JSON pointer 获取正确的 sessionData
data.value = jsonPointerGet(response, config.sessionData.sessionPointer) as SessionData
} catch (error) {
// 获取 sessionData 出错需要重置登录状态
logger.error(error)
data.value = null
clearToken()
}

loading.value = false
lastRefreshedAt.value = new Date()

// 获取用户信息失败后可以进行的操作
const { required = false, callbackUrl, external, onUnauthenticated } = getSessionOptions

if (required && data.value === null) {
if (onUnauthenticated) {
return onUnauthenticated()
} else {
await navigateTo(callbackUrl ?? '/', { external })
return
}
}

return data.value
const { getSession } = useLocalAuth()
return await getSession()
}
/**
* 登录
Expand Down

0 comments on commit 73eeba8

Please sign in to comment.