-
Notifications
You must be signed in to change notification settings - Fork 110
logout when restart the server #718
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
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,9 +1,12 @@ | ||
import { useAccessStore } from "../store"; | ||
import Locale, { getServerLang } from "../locales"; | ||
import { Toast } from "@douyinfe/semi-ui"; | ||
import { SessionManager } from "../utils/session"; | ||
|
||
export class ClientApi { | ||
async get(url: string, params: Record<string, any> = {}): Promise<any> { | ||
// Check token validity before making request | ||
await this.validateTokenBeforeRequest(url); | ||
let queryString = ""; | ||
if (Object.keys(params).length > 0) { | ||
queryString = "?" + new URLSearchParams(params).toString(); | ||
|
@@ -40,6 +43,8 @@ export class ClientApi { | |
} | ||
|
||
async post(url: string, body: Record<string, any> = {}): Promise<any> { | ||
// Check token validity before making request | ||
await this.validateTokenBeforeRequest(url); | ||
const res: Response = await fetch( | ||
this.path(url), | ||
{ | ||
|
@@ -76,6 +81,8 @@ export class ClientApi { | |
} | ||
|
||
async postForm(url: string, formData: FormData = new FormData()): Promise<any> { | ||
// Check token validity before making request | ||
await this.validateTokenBeforeRequest(url); | ||
const res: Response = await fetch( | ||
this.path(url), | ||
{ | ||
|
@@ -104,6 +111,26 @@ export class ClientApi { | |
return resJson.data; | ||
} | ||
|
||
private async validateTokenBeforeRequest(url: string): Promise<void> { | ||
// Skip validation for login-related endpoints to avoid infinite loops | ||
if (url.includes('/login') || url.includes('/serverInfo') || url.includes('/loginType')) { | ||
return; | ||
} | ||
|
||
const accessStore = useAccessStore.getState(); | ||
if (accessStore.token) { | ||
try { | ||
const isValid = await accessStore.checkTokenValidity(); | ||
if (!isValid) { | ||
throw new Error('Token validation failed'); | ||
} | ||
} catch (error) { | ||
// Token validation failed, user will be logged out | ||
throw error; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Are we doing anything in catch? Otherwise it may be unnecessary to catch the error There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. @andythsu yes, we are throwing error as token validation failed and user will be logged out in that case |
||
} | ||
} | ||
} | ||
|
||
path(path: string): string { | ||
const proxyPath = import.meta.env.VITE_PROXY_PATH; | ||
return [proxyPath, path].join(""); | ||
|
@@ -134,7 +161,12 @@ export function getHeaders(): Record<string, string> { | |
const validString = (x: string) => x && x.length > 0; | ||
|
||
if (validString(accessStore.token)) { | ||
headers.Authorization = makeBearer(accessStore.token); | ||
// For synchronous header generation, we'll do basic token validation | ||
// The async server restart check will happen in the session manager | ||
const sessionManager = SessionManager.getInstance(); | ||
if (!sessionManager.isTokenExpired(accessStore.token)) { | ||
headers.Authorization = makeBearer(accessStore.token); | ||
} | ||
} | ||
|
||
return headers; | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,7 +1,8 @@ | ||
import { create } from "zustand"; | ||
import { persist } from "zustand/middleware"; | ||
import { StoreKey } from "../constant"; | ||
import { getInfoApi } from "../api/webapp/login"; | ||
import { getInfoApi, serverInfoApi } from "../api/webapp/login"; | ||
import { SessionManager } from "../utils/session"; | ||
|
||
export enum Role { | ||
ADMIN = "ADMIN", | ||
|
@@ -28,6 +29,8 @@ export interface AccessControlStore { | |
getUserInfo: (_?: boolean) => void; | ||
hasRole: (role: Role) => boolean; | ||
hasPermission: (permission: string | undefined) => boolean; | ||
logout: () => void; | ||
checkTokenValidity: () => Promise<boolean>; | ||
} | ||
|
||
let fetchState: number = 0; // 0 not fetch, 1 fetching, 2 done | ||
|
@@ -78,6 +81,51 @@ export const useAccessStore = create<AccessControlStore>()( | |
const permissions = get().permissions | ||
return permission == undefined || permissions == null || permissions.length == 0 || permissions.includes(permission); | ||
}, | ||
logout() { | ||
const sessionManager = SessionManager.getInstance(); | ||
sessionManager.clearTimeout(); | ||
set(() => ({ | ||
token: "", | ||
userId: "", | ||
userName: "", | ||
nickName: "", | ||
userType: "", | ||
email: "", | ||
phonenumber: "", | ||
sex: "", | ||
avatar: "", | ||
permissions: [], | ||
roles: [], | ||
})); | ||
fetchState = 0; | ||
}, | ||
async checkTokenValidity() { | ||
const token = get().token; | ||
if (!token) return false; | ||
|
||
const sessionManager = SessionManager.getInstance(); | ||
|
||
// Check if token is expired | ||
if (sessionManager.isTokenExpired(token)) { | ||
get().logout(); | ||
return false; | ||
} | ||
|
||
// Check for server restart | ||
try { | ||
const serverInfo = await serverInfoApi(); | ||
if (sessionManager.checkServerRestart(token, serverInfo.serverStart)) { | ||
console.log('Server restart detected, logging out'); | ||
get().logout(); | ||
return false; | ||
} | ||
} catch (error) { | ||
console.error('Error checking server info:', error); | ||
// Don't logout on API error, just continue | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. should we log out here? technically we should never end up in this state, but if we do, it means the server is having issues. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. @andythsu No, we are not logging out here, we are logging the server error here |
||
} | ||
|
||
return true; | ||
}, | ||
}), | ||
{ | ||
name: StoreKey.Access, | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
if this is intended to be shared by multiple classes, we can move it out from this class and then create a separate config class. OR we can create a getter for this field