Skip to content

Commit

Permalink
fix: refresh token
Browse files Browse the repository at this point in the history
Signed-off-by: Innei <i@innei.in>
  • Loading branch information
Innei committed Jan 31, 2024
1 parent d1529c5 commit 0ab7f0d
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 14 deletions.
10 changes: 9 additions & 1 deletion src/atoms/owner.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { useMutation } from '@tanstack/react-query'
import { atom, useAtomValue } from 'jotai'

import { getToken, removeToken, setToken } from '~/lib/cookie'
Expand Down Expand Up @@ -65,7 +66,14 @@ export const useOwner = () => useAtomValue(ownerAtom)

export const isLogged = () => jotaiStore.get(isLoggedAtom)

export const refreshToken = async () => {
export const useRefreshToken = () => {
return useMutation({
mutationKey: ['refreshToken'],
mutationFn: refreshToken,
})
}

const refreshToken = async () => {
const token = getToken()
if (!token) return
await apiClient.user.proxy.login.put<{ token: string }>().then((res) => {
Expand Down
15 changes: 2 additions & 13 deletions src/components/layout/header/internal/UserAuth.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@
'use client'

import React, { useEffect } from 'react'
import React from 'react'
import { AnimatePresence } from 'framer-motion'
import dynamic from 'next/dynamic'
import Image from 'next/image'
import { usePathname } from 'next/navigation'

import { useSignIn, useUser } from '@clerk/nextjs'

import { refreshToken, useIsLogged } from '~/atoms'
import { useIsLogged } from '~/atoms'
import { UserArrowLeftIcon } from '~/components/icons/user-arrow-left'
import { MotionButtonBase } from '~/components/ui/button'
import { FloatPopover } from '~/components/ui/float-popover'
Expand Down Expand Up @@ -61,15 +59,6 @@ export function UserAuth() {
const pathname = usePathname()
const isLogged = useIsLogged()

const { isLoaded } = useSignIn()

const user = useUser()

useEffect(() => {
// token 刷新,使用 mx token 替换
if (isLoaded && user.user?.publicMetadata.role === 'admin') refreshToken()
}, [isLoaded, user.user?.publicMetadata.role])

if (isLogged) {
return <OwnerAvatar />
}
Expand Down

0 comments on commit 0ab7f0d

Please sign in to comment.