Private
Public Access
1
0

fix: persist auth state across page refreshes using onRehydrateStorage
Some checks failed
CI Pipeline / Rust Format Check (push) Failing after 5s
CI Pipeline / Clippy Lints (push) Successful in 49s
CI Pipeline / Rust Unit Tests (push) Successful in 1m2s
CI Pipeline / Security Audit (push) Successful in 4s
CI Pipeline / Frontend Lint & Type Check (push) Failing after 10s
CI Pipeline / Build .deb & Release (push) Has been skipped

This commit is contained in:
2026-05-07 02:59:09 +00:00
parent 5e63245f65
commit 73df591cd3
3 changed files with 51 additions and 8 deletions

View File

@ -1,3 +1,4 @@
import axios from 'axios'
import { create } from 'zustand'
import { persist } from 'zustand/middleware'
import type { User } from '../types'
@ -7,6 +8,7 @@ interface AuthState {
refreshToken: string | null
user: User | null
isAuthenticated: boolean
isRestoring: boolean
setTokens: (access: string, refresh: string) => void
setUser: (user: User) => void
logout: () => void
@ -19,6 +21,7 @@ export const useAuthStore = create<AuthState>()(
refreshToken: null,
user: null,
isAuthenticated: false,
isRestoring: true,
setTokens: (access, refresh) =>
set({ accessToken: access, refreshToken: refresh, isAuthenticated: true }),
@ -26,12 +29,41 @@ export const useAuthStore = create<AuthState>()(
setUser: (user) => set({ user }),
logout: () =>
set({ accessToken: null, refreshToken: null, user: null, isAuthenticated: false }),
set({ accessToken: null, refreshToken: null, user: null, isAuthenticated: false, isRestoring: false }),
}),
{
name: 'pm-auth',
// Only persist refresh token; access token regenerated on load
partialize: (state) => ({ refreshToken: state.refreshToken, user: state.user }),
onRehydrateStorage: () => {
return (state) => {
if (state?.refreshToken) {
// Proactively refresh the access token using the persisted refresh token
axios.post('/api/v1/auth/refresh', { refresh_token: state.refreshToken })
.then(({ data }) => {
useAuthStore.setState({
accessToken: data.access_token,
refreshToken: data.refresh_token,
isAuthenticated: true,
isRestoring: false,
})
})
.catch(() => {
// Refresh token expired or invalid — clear all auth state
useAuthStore.setState({
accessToken: null,
refreshToken: null,
user: null,
isAuthenticated: false,
isRestoring: false,
})
})
} else {
// No refresh token — not logged in, skip restoration
useAuthStore.setState({ isRestoring: false })
}
}
},
}
)
)