@samitouri / QOSami-HFS / commits / 12887398

fix: each login was not replacing but adding a timer for the session

Massimo Melina committed Sep 7, 2024 at 15:27 UTC 12887398a41017521df48c3bfb5d0ec0b566c4d7
3 files changed +13 -8
admin/src/LoginRequired.ts
+2 -3
@@ -69,8 +69,7 @@ async function login(username: string, password: string) {
69
70 // login was successful, update state
71 state.loginRequired = false
72 - sessionRefresher(res)
72 + refreshSession(res)
73 }
74
75 -const sessionRefresher = makeSessionRefresher(state)
76 -sessionRefresher(getHFS().session)
75 +const refreshSession = makeSessionRefresher(state)
frontend/src/login.ts
+2 -3
@@ -16,7 +16,7 @@ async function login(username:string, password:string) {
16 const stopWorking = working()
17 return srpClientSequence(username, password, apiCall).then(res => {
18 stopWorking()
19 - sessionRefresher(res)
19 + refreshSession(res)
20 state.loginRequired = false
21 return res
22 }, (err: any) => {
@@ -28,8 +28,7 @@ async function login(username:string, password:string) {
28 })
29 }
30
31 -const sessionRefresher = makeSessionRefresher(state)
32 -sessionRefresher(getHFS().session)
31 +const refreshSession = makeSessionRefresher(state)
32
33 export function logout() {
34 return apiCall('logout', {}, { modal: working }).catch(res => {
shared/index.ts
+9 -2
@@ -102,15 +102,22 @@ export function getPrefixUrl() {
102 }
103
104 export function makeSessionRefresher(state: any) {
105 - return function sessionRefresher(response: any) {
105 + let timeout: any
106 + const initial = getHFS().session
107 + refreshSession(initial)
108 + return refreshSession
109 +
110 + function refreshSession(response: any) {
111 if (!response) return
112 const { exp } = response
113 + Object.assign(initial, response) // keep it updated, not necessary, just in case someone is looking at this instead of the state
114 Object.assign(state, _.pick(response, ['username', 'adminUrl', 'canChangePassword', 'accountExp']))
115 if (!response.username || !exp) return
116 const delta = new Date(exp).getTime() - Date.now()
117 const t = _.clamp(delta - 30_000, 4_000, 600_000)
118 console.debug('session refresh in', Math.round(t / 1000))
113 - setTimeout(() => apiCall('refresh_session').then(sessionRefresher), t)
119 + clearTimeout(timeout)
120 + timeout = setTimeout(() => apiCall('refresh_session').then(refreshSession), t)
121 }
122 }
123