codevdesign 1.0.38 → 1.0.40

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,116 +1,116 @@
1
- import axios, { type AxiosInstance, type AxiosError, type AxiosResponse } from 'axios'
2
- import { useAppStore } from '@/store/appStore'
3
- import router from '@/router'
4
-
5
- type ApiReponse<T = unknown> =
6
- // Succès
7
- | {
8
- succes: true
9
- resultat: T
10
- status?: number
11
- message?: string
12
- location?: string
13
- parametres?: unknown
14
- [k: string]: unknown
15
- }
16
- // Échec (le backend peut quand même renvoyer resultat null/absent)
17
- | {
18
- succes: false
19
- resultat?: unknown
20
- status?: number
21
- message?: string
22
- location?: string
23
- parametres?: unknown
24
- [k: string]: unknown
25
- }
26
-
27
- let client: AxiosInstance | null = null
28
- let cachedBaseUrl = '' // pour éviter de régénérer une instance axios si rien n’a changé
29
-
30
- export default {
31
- clearCache: false,
32
-
33
- getAxios(): AxiosInstance {
34
- // Singleton + clearCache
35
- if (client && !this.clearCache) return client
36
-
37
- const appStore = useAppStore()
38
-
39
- const rawUrl = appStore.modeleCharger
40
- ? appStore.appModele!.urlBase
41
- : window.location.origin + import.meta.env.BASE_URL
42
-
43
- const urlBase = rawUrl.endsWith('/') ? rawUrl.slice(0, -1) : rawUrl
44
-
45
- // Si la base URL n'a pas changé et qu'on a déjà un client, on le renvoie
46
- if (client && cachedBaseUrl === urlBase && !this.clearCache) return client
47
- cachedBaseUrl = urlBase
48
-
49
- client = axios.create({
50
- baseURL: `${urlBase}/api`,
51
- withCredentials: true,
52
- timeout: 30_000,
53
- headers: {
54
- Accept: 'application/json',
55
- 'Content-Type': 'application/json',
56
- 'X-Requested-With': 'XMLHttpRequest',
57
- },
58
- // validateStatus: (s) => s >= 200 && s < 300, // défaut axios
59
- })
60
-
61
- client.interceptors.response.use(
62
- (response: AxiosResponse<any>) => {
63
- const data = response.data
64
-
65
- // Détection de la réponse { succes, resultat }
66
- if (data && typeof data === 'object' && 'succes' in data) {
67
- const env = data as ApiReponse
68
- return env.succes === true ? env.resultat : Promise.reject(env)
69
- }
70
-
71
- // Sinon, renvoyer data si présent, sinon la réponse complète
72
- return data ?? response
73
- },
74
-
75
- (error: AxiosError<any>) => {
76
- const status = error.response?.status
77
- const payload = error.response?.data?.resultat ?? { message: error.message }
78
-
79
- // 403 / 404
80
- if (status === 403 || status === 404) {
81
- try {
82
- appStore.lancerErreur(payload)
83
- if (router.currentRoute.value.name !== '403') {
84
- router.push({ name: '403' })
85
- }
86
- } catch {
87
- // no-op
88
- }
89
- return Promise.reject(payload)
90
- }
91
-
92
- // gérer les autres 4XX ici
93
-
94
- // Log minimal
95
- console.error('HTTP error', {
96
- status,
97
- url: error.config?.url,
98
- payload,
99
- })
100
-
101
- // Remonter l’erreur normalisée dans appstore
102
- try {
103
- if (payload?.resultat) appStore.lancerErreur(payload)
104
- else if (payload) appStore.lancerErreur(payload)
105
- } catch {
106
- // no-op
107
- }
108
- return Promise.reject(payload)
109
- },
110
- )
111
-
112
- // reset le flag si on l’avait utilisé pour forcer la recréation de l'instance
113
- this.clearCache = false
114
- return client
115
- },
116
- }
1
+ import axios, { type AxiosInstance, type AxiosError, type AxiosResponse } from 'axios'
2
+ import { useAppStore } from '@/store/appStore'
3
+ import router from '@/router'
4
+
5
+ type ApiReponse<T = unknown> =
6
+ // Succès
7
+ | {
8
+ succes: true
9
+ resultat: T
10
+ status?: number
11
+ message?: string
12
+ location?: string
13
+ parametres?: unknown
14
+ [k: string]: unknown
15
+ }
16
+ // Échec (le backend peut quand même renvoyer resultat null/absent)
17
+ | {
18
+ succes: false
19
+ resultat?: unknown
20
+ status?: number
21
+ message?: string
22
+ location?: string
23
+ parametres?: unknown
24
+ [k: string]: unknown
25
+ }
26
+
27
+ let client: AxiosInstance | null = null
28
+ let cachedBaseUrl = '' // pour éviter de régénérer une instance axios si rien n’a changé
29
+
30
+ export default {
31
+ clearCache: false,
32
+
33
+ getAxios(): AxiosInstance {
34
+ // Singleton + clearCache
35
+ if (client && !this.clearCache) return client
36
+
37
+ const appStore = useAppStore()
38
+
39
+ const rawUrl = appStore.modeleCharger
40
+ ? appStore.appModele!.urlBase
41
+ : window.location.origin + import.meta.env.BASE_URL
42
+
43
+ const urlBase = rawUrl.endsWith('/') ? rawUrl.slice(0, -1) : rawUrl
44
+
45
+ // Si la base URL n'a pas changé et qu'on a déjà un client, on le renvoie
46
+ if (client && cachedBaseUrl === urlBase && !this.clearCache) return client
47
+ cachedBaseUrl = urlBase
48
+
49
+ client = axios.create({
50
+ baseURL: `${urlBase}/api`,
51
+ withCredentials: true,
52
+ timeout: 30_000,
53
+ headers: {
54
+ Accept: 'application/json',
55
+ 'Content-Type': 'application/json',
56
+ 'X-Requested-With': 'XMLHttpRequest',
57
+ },
58
+ // validateStatus: (s) => s >= 200 && s < 300, // défaut axios
59
+ })
60
+
61
+ client.interceptors.response.use(
62
+ (response: AxiosResponse<any>) => {
63
+ const data = response.data
64
+
65
+ // Détection de la réponse { succes, resultat }
66
+ if (data && typeof data === 'object' && 'succes' in data) {
67
+ const env = data as ApiReponse
68
+ return env.succes === true ? env.resultat : Promise.reject(env)
69
+ }
70
+
71
+ // Sinon, renvoyer data si présent, sinon la réponse complète
72
+ return data ?? response
73
+ },
74
+
75
+ (error: AxiosError<any>) => {
76
+ const status = error.response?.status
77
+ const payload = error.response?.data?.resultat ?? { message: error.message }
78
+
79
+ // 403 / 404
80
+ if (status === 403 || status === 404) {
81
+ try {
82
+ appStore.lancerErreur(payload)
83
+ if (router.currentRoute.value.name !== '403') {
84
+ router.push({ name: '403' })
85
+ }
86
+ } catch {
87
+ // no-op
88
+ }
89
+ return Promise.reject(payload)
90
+ }
91
+
92
+ // gérer les autres 4XX ici
93
+
94
+ // Log minimal
95
+ console.error('HTTP error', {
96
+ status,
97
+ url: error.config?.url,
98
+ payload,
99
+ })
100
+
101
+ // Remonter l’erreur normalisée dans appstore
102
+ try {
103
+ if (payload?.resultat) appStore.lancerErreur(payload)
104
+ else if (payload) appStore.lancerErreur(payload)
105
+ } catch {
106
+ // no-op
107
+ }
108
+ return Promise.reject(payload)
109
+ },
110
+ )
111
+
112
+ // reset le flag si on l’avait utilisé pour forcer la recréation de l'instance
113
+ this.clearCache = false
114
+ return client
115
+ },
116
+ }
@@ -1,187 +1,187 @@
1
- class RafraichisseurToken {
2
- private intervalleEnSecondes = 15
3
- private secondesAvantExpirationTokenPourRafraichir = 20
4
- private skewSeconds = 5 // marge anti-derives d’horloge
5
- private popupAffiche = false
6
- private timerId: number | null = null
7
-
8
- // Lance une seule fois
9
- public async demarrer(nomTemoin: string | null, urlPortail: string): Promise<void> {
10
- urlPortail = urlPortail.replace(/\/+$/, '')
11
- if (nomTemoin == null || nomTemoin === '') nomTemoin = 'csqc_jeton_secure_expiration'
12
- await this.verifierJeton(nomTemoin, urlPortail)
13
- if (this.timerId != null) return
14
- this.timerId = window.setInterval(() => {
15
- this.verifierJeton(nomTemoin, urlPortail)
16
- }, this.intervalleEnSecondes * 1000)
17
- }
18
-
19
- // Permet d’arrêter le timer (ex: au logout / destroy)
20
- public arreter(): void {
21
- if (this.timerId != null) {
22
- clearInterval(this.timerId)
23
- this.timerId = null
24
- }
25
- }
26
-
27
- public existeJeton = (nomTemoin: string) => {
28
- return this.estJetonValide(nomTemoin)
29
- }
30
-
31
- private async verifierJeton(nomTemoin: string, urlPortail: string): Promise<void> {
32
- if (this.popupAffiche) return
33
-
34
- if (!this.estJetonValide(nomTemoin)) {
35
- this.rafraichir(nomTemoin, urlPortail)
36
- return
37
- }
38
- }
39
-
40
- private estJetonValide(nomTemoin: string): boolean {
41
- if (this.popupAffiche || !nomTemoin) return true //On fait semblant que c'est valide pour ne pas provoquer un autre affichage du popup.
42
-
43
- const tokenEncode = this.lireCookie(nomTemoin)
44
- if (!tokenEncode) {
45
- return false
46
- }
47
-
48
- let token: any
49
- try {
50
- token = this.parseJwt(tokenEncode)
51
- } catch {
52
- return false
53
- }
54
-
55
- const exp = Number(token?.exp)
56
- if (!Number.isFinite(exp)) {
57
- // exp manquant/invalide → tente refresh
58
-
59
- return false
60
- }
61
-
62
- const now = Math.floor(Date.now() / 1000)
63
- const refreshAt = exp - this.secondesAvantExpirationTokenPourRafraichir - this.skewSeconds
64
- if (now >= refreshAt) {
65
- return false
66
- }
67
-
68
- return true
69
- }
70
-
71
- private async rafraichir(nomCookie: string, urlPortail: string): Promise<void> {
72
- if (!nomCookie) return
73
- const url = this.getRefreshUrl(urlPortail)
74
- const controller = new AbortController()
75
- const timeout = setTimeout(() => controller.abort(), 10_000)
76
-
77
- try {
78
- //Première tentative sans iframe, pour la majorité des cas.
79
- const resp = await fetch(url, {
80
- method: 'POST',
81
- credentials: 'include',
82
- headers: { Accept: 'application/json' },
83
- redirect: 'manual',
84
- signal: controller.signal,
85
- })
86
-
87
- // redirection (souvent => login) → traiter comme non auth
88
-
89
- if (resp.type === 'opaqueredirect' || resp.status === 302) {
90
- this.rafraichirParIframe(nomCookie, urlPortail)
91
- return
92
- }
93
-
94
- // OK ou No Content: le cookie devrait être réécrit
95
- if (resp.status === 200 || resp.status === 204) {
96
- const jeton = this.lireCookie(nomCookie)
97
- if (!jeton) this.rafraichirParIframe(nomCookie, urlPortail)
98
- return
99
- }
100
-
101
- // non auth / expiré (401, 419) + IIS timeout (440)
102
- if (resp.status === 401 || resp.status === 419 || resp.status === 440) {
103
- this.rafraichirParIframe(nomCookie, urlPortail)
104
- return
105
- }
106
-
107
- console.warn('Rafraichisseur token: statut inattendu', resp.status)
108
- } catch (err: any) {
109
- if (err?.name === 'AbortError') console.warn('RafraichisseurToken timeout')
110
- else console.error('Erreur rafraichisseur de token', err)
111
- // on réessaiera au prochain tick
112
- } finally {
113
- clearTimeout(timeout)
114
- }
115
- }
116
-
117
- private rafraichirParIframe(nomCookie: string, urlPortail: string): void {
118
- // Pour éviter les cross référence, on créé un iframe qui appel portail et force la MAJ du jeton ou l'invalidation du jeton, si jamais l'utilisateur n'est plus connecté
119
- // ajax vers le refresh
120
- let iframe = document.createElement('iframe')
121
- const url = this.getRefreshUrl(urlPortail)
122
- iframe.src = `${url}?urlRetour=${encodeURI(window.localStorage.href)}`
123
- iframe.id = 'idRafrToken'
124
- iframe.style.display = 'none'
125
- document.body.appendChild(iframe)
126
- iframe.onload = () => {
127
- const jetonCSQC = this.lireCookie(nomCookie)
128
- if (jetonCSQC == null || jetonCSQC === '') {
129
- this.estDeconnecteAzure(urlPortail)
130
- }
131
-
132
- iframe.remove()
133
- }
134
- }
135
-
136
- private estDeconnecteAzure(urlPortail: string): void {
137
- //on envoie au portail, pas le choix
138
-
139
- const retour = encodeURI(window.location.href)
140
- window.open(`${urlPortail}/home/SeConnecter?urlRetour=${retour}`, '_self')
141
- return
142
- }
143
-
144
- public deconnecterPortail(urlPortail: string): void {
145
- window.location.replace(`${urlPortail}/deconnecte?urlRetour=${encodeURIComponent(window.location.href)}`)
146
- }
147
-
148
- private lireCookie(nom: string): string | null {
149
- if (!document.cookie) return null
150
- const cookies = document.cookie.split(';').map(c => c.trim())
151
- for (const cookie of cookies) {
152
- if (cookie.startsWith(`${nom}=`)) {
153
- try {
154
- return decodeURIComponent(cookie.substring(nom.length + 1))
155
- } catch {
156
- return cookie.substring(nom.length + 1)
157
- }
158
- }
159
- }
160
- return null
161
- }
162
-
163
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
164
- private parseJwt(token: string): any {
165
- const parts = token.split('.')
166
- const base64Url = parts[1]
167
- if (!base64Url) throw new Error('Invalid JWT format')
168
- const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/')
169
- const jsonPayload = decodeURIComponent(
170
- atob(base64)
171
- .split('')
172
- .map(c => `%${`00${c.charCodeAt(0).toString(16)}`.slice(-2)}`)
173
- .join(''),
174
- )
175
- return JSON.parse(jsonPayload)
176
- }
177
-
178
- // URL refresh selon env (dev = proxy Vite ; prod = portail)
179
- private getRefreshUrl(urlPortail: string): string {
180
- if (import.meta.env.MODE === 'development') return '/portail-refresh'
181
- return urlPortail + '/home/Refresh'
182
- }
183
- }
184
-
185
- // Instance
186
- const rafraichisseurToken = new RafraichisseurToken()
187
- export default rafraichisseurToken
1
+ class RafraichisseurToken {
2
+ private intervalleEnSecondes = 15
3
+ private secondesAvantExpirationTokenPourRafraichir = 20
4
+ private skewSeconds = 5 // marge anti-derives d’horloge
5
+ private popupAffiche = false
6
+ private timerId: number | null = null
7
+
8
+ // Lance une seule fois
9
+ public async demarrer(nomTemoin: string | null, urlPortail: string): Promise<void> {
10
+ urlPortail = urlPortail.replace(/\/+$/, '')
11
+ if (nomTemoin == null || nomTemoin === '') nomTemoin = 'csqc_jeton_secure_expiration'
12
+ await this.verifierJeton(nomTemoin, urlPortail)
13
+ if (this.timerId != null) return
14
+ this.timerId = window.setInterval(() => {
15
+ this.verifierJeton(nomTemoin, urlPortail)
16
+ }, this.intervalleEnSecondes * 1000)
17
+ }
18
+
19
+ // Permet d’arrêter le timer (ex: au logout / destroy)
20
+ public arreter(): void {
21
+ if (this.timerId != null) {
22
+ clearInterval(this.timerId)
23
+ this.timerId = null
24
+ }
25
+ }
26
+
27
+ public existeJeton = (nomTemoin: string) => {
28
+ return this.estJetonValide(nomTemoin)
29
+ }
30
+
31
+ private async verifierJeton(nomTemoin: string, urlPortail: string): Promise<void> {
32
+ if (this.popupAffiche) return
33
+
34
+ if (!this.estJetonValide(nomTemoin)) {
35
+ this.rafraichir(nomTemoin, urlPortail)
36
+ return
37
+ }
38
+ }
39
+
40
+ private estJetonValide(nomTemoin: string): boolean {
41
+ if (this.popupAffiche || !nomTemoin) return true //On fait semblant que c'est valide pour ne pas provoquer un autre affichage du popup.
42
+
43
+ const tokenEncode = this.lireCookie(nomTemoin)
44
+ if (!tokenEncode) {
45
+ return false
46
+ }
47
+
48
+ let token: any
49
+ try {
50
+ token = this.parseJwt(tokenEncode)
51
+ } catch {
52
+ return false
53
+ }
54
+
55
+ const exp = Number(token?.exp)
56
+ if (!Number.isFinite(exp)) {
57
+ // exp manquant/invalide → tente refresh
58
+
59
+ return false
60
+ }
61
+
62
+ const now = Math.floor(Date.now() / 1000)
63
+ const refreshAt = exp - this.secondesAvantExpirationTokenPourRafraichir - this.skewSeconds
64
+ if (now >= refreshAt) {
65
+ return false
66
+ }
67
+
68
+ return true
69
+ }
70
+
71
+ private async rafraichir(nomCookie: string, urlPortail: string): Promise<void> {
72
+ if (!nomCookie) return
73
+ const url = this.getRefreshUrl(urlPortail)
74
+ const controller = new AbortController()
75
+ const timeout = setTimeout(() => controller.abort(), 10_000)
76
+
77
+ try {
78
+ //Première tentative sans iframe, pour la majorité des cas.
79
+ const resp = await fetch(url, {
80
+ method: 'POST',
81
+ credentials: 'include',
82
+ headers: { Accept: 'application/json' },
83
+ redirect: 'manual',
84
+ signal: controller.signal,
85
+ })
86
+
87
+ // redirection (souvent => login) → traiter comme non auth
88
+
89
+ if (resp.type === 'opaqueredirect' || resp.status === 302) {
90
+ this.rafraichirParIframe(nomCookie, urlPortail)
91
+ return
92
+ }
93
+
94
+ // OK ou No Content: le cookie devrait être réécrit
95
+ if (resp.status === 200 || resp.status === 204) {
96
+ const jeton = this.lireCookie(nomCookie)
97
+ if (!jeton) this.rafraichirParIframe(nomCookie, urlPortail)
98
+ return
99
+ }
100
+
101
+ // non auth / expiré (401, 419) + IIS timeout (440)
102
+ if (resp.status === 401 || resp.status === 419 || resp.status === 440) {
103
+ this.rafraichirParIframe(nomCookie, urlPortail)
104
+ return
105
+ }
106
+
107
+ console.warn('Rafraichisseur token: statut inattendu', resp.status)
108
+ } catch (err: any) {
109
+ if (err?.name === 'AbortError') console.warn('RafraichisseurToken timeout')
110
+ else console.error('Erreur rafraichisseur de token', err)
111
+ // on réessaiera au prochain tick
112
+ } finally {
113
+ clearTimeout(timeout)
114
+ }
115
+ }
116
+
117
+ private rafraichirParIframe(nomCookie: string, urlPortail: string): void {
118
+ // Pour éviter les cross référence, on créé un iframe qui appel portail et force la MAJ du jeton ou l'invalidation du jeton, si jamais l'utilisateur n'est plus connecté
119
+ // ajax vers le refresh
120
+ let iframe = document.createElement('iframe')
121
+ const url = this.getRefreshUrl(urlPortail)
122
+ iframe.src = `${url}?urlRetour=${encodeURI(window.localStorage.href)}`
123
+ iframe.id = 'idRafrToken'
124
+ iframe.style.display = 'none'
125
+ document.body.appendChild(iframe)
126
+ iframe.onload = () => {
127
+ const jetonCSQC = this.lireCookie(nomCookie)
128
+ if (jetonCSQC == null || jetonCSQC === '') {
129
+ this.estDeconnecteAzure(urlPortail)
130
+ }
131
+
132
+ iframe.remove()
133
+ }
134
+ }
135
+
136
+ private estDeconnecteAzure(urlPortail: string): void {
137
+ //on envoie au portail, pas le choix
138
+
139
+ const retour = encodeURI(window.location.href)
140
+ window.open(`${urlPortail}/home/SeConnecter?urlRetour=${retour}`, '_self')
141
+ return
142
+ }
143
+
144
+ public deconnecterPortail(urlPortail: string): void {
145
+ window.location.replace(`${urlPortail}/deconnecte?urlRetour=${encodeURIComponent(window.location.href)}`)
146
+ }
147
+
148
+ private lireCookie(nom: string): string | null {
149
+ if (!document.cookie) return null
150
+ const cookies = document.cookie.split(';').map(c => c.trim())
151
+ for (const cookie of cookies) {
152
+ if (cookie.startsWith(`${nom}=`)) {
153
+ try {
154
+ return decodeURIComponent(cookie.substring(nom.length + 1))
155
+ } catch {
156
+ return cookie.substring(nom.length + 1)
157
+ }
158
+ }
159
+ }
160
+ return null
161
+ }
162
+
163
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
164
+ private parseJwt(token: string): any {
165
+ const parts = token.split('.')
166
+ const base64Url = parts[1]
167
+ if (!base64Url) throw new Error('Invalid JWT format')
168
+ const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/')
169
+ const jsonPayload = decodeURIComponent(
170
+ atob(base64)
171
+ .split('')
172
+ .map(c => `%${`00${c.charCodeAt(0).toString(16)}`.slice(-2)}`)
173
+ .join(''),
174
+ )
175
+ return JSON.parse(jsonPayload)
176
+ }
177
+
178
+ // URL refresh selon env (dev = proxy Vite ; prod = portail)
179
+ private getRefreshUrl(urlPortail: string): string {
180
+ if (import.meta.env.MODE === 'development') return '/portail-refresh'
181
+ return urlPortail + '/home/Refresh'
182
+ }
183
+ }
184
+
185
+ // Instance
186
+ const rafraichisseurToken = new RafraichisseurToken()
187
+ export default rafraichisseurToken
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "codevdesign",
3
- "version": "1.0.38",
3
+ "version": "1.0.40",
4
4
  "description": "Composants Vuetify 3 pour les projets Codev",
5
5
  "files": [
6
6
  "./**/*.vue",