Skip to content
This repository has been archived by the owner on Dec 9, 2024. It is now read-only.

Commit

Permalink
feat: add tokenExpiredTime
Browse files Browse the repository at this point in the history
  • Loading branch information
ronger-x committed Apr 28, 2024
1 parent 3bc6a4f commit 1c74a7f
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 7 deletions.
2 changes: 2 additions & 0 deletions src/runtime/composables/local/use-auth-state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ export const useAuthState = (): UseAuthStateReturn => {

const setToken = (value: string | null) => {
rawToken.value = value
commonAuthState.tokenExpiredTime.value =
value === null ? null : new Date(new Date().getTime() + config.token.maxAgeInSeconds * 1000)
}

const clearToken = () => {
Expand Down
10 changes: 3 additions & 7 deletions src/runtime/composables/refresh/use-auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,16 +14,12 @@ import { navigateTo, useRuntimeConfig } from '#imports'
const getSession: ReturnType<typeof useLocalAuth>['getSession'] = async (
getSessionOptions = {},
) => {
const config = useTypedConfig(useRuntimeConfig(), 'refresh')

const { token, refreshToken, lastRefreshedAt } = useAuthState()

const { token, tokenExpiredTime, refreshToken } = useAuthState()
if (!token.value && !getSessionOptions.force) {
return
}
if (token.value && refreshToken.value && lastRefreshedAt && lastRefreshedAt.value) {
const isTokenExpired =
new Date().getTime() - lastRefreshedAt.value.getTime() > config.token.maxAgeInSeconds * 1000
if (token.value && refreshToken.value && tokenExpiredTime && tokenExpiredTime.value) {
const isTokenExpired = new Date().getTime() - tokenExpiredTime.value.getTime() > 0
if (isTokenExpired) {
await refresh({ refreshToken: refreshToken.value })
return
Expand Down
6 changes: 6 additions & 0 deletions src/runtime/composables/use-common-auth-state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ type UseCommonAuthStateReturn<T> = {
data: Ref<T | null>
lastRefreshedAt: Ref<Date | null>
status: ComputedRef<SessionStatus>
tokenExpiredTime: Ref<Date | null>
}

/**
Expand Down Expand Up @@ -45,10 +46,15 @@ export const useCommonAuthState = <T = any>(): UseCommonAuthStateReturn<T> => {
return 'unauthenticated'
})

const tokenExpiredTime = useState('auth:token-expired-at', () => {
return null
})

return {
data,
lastRefreshedAt,
loading,
status,
tokenExpiredTime,
}
}

0 comments on commit 1c74a7f

Please sign in to comment.