@alfabit/keycloak 0.0.39 → 0.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.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@alfabit/keycloak",
3
3
  "private": false,
4
- "version": "0.0.39",
4
+ "version": "0.0.40",
5
5
  "type": "module",
6
6
  "license": "UNLICENSED",
7
7
  "main": "src/index.ts",
@@ -1,496 +1,496 @@
1
- import Keycloak, { type KeycloakInitOptions } from 'keycloak-js';
2
- import { inject, reactive, readonly, type Ref, ref } from 'vue';
3
- import { postWebLogin } from '../api/wallet/endpoints';
4
- import { AppNameEnum, APP_NAME, IS_TELEGRAM_MINI_APP, KEYCLOAK_LOGIN_REQUIRED, OPENID_CLIENT_ID, OPENID_REALM, OPENID_URL, LocationEnum, IS_LOCALHOST } from '@alfabit/constants';
5
-
6
- export type TIdpHint = 'email' | 'google' | 'apple';
7
-
8
- export interface IUseKeycloak {
9
- login(email?: string, redirectUri?: string): void;
10
- loginWithGoogle(redirectUri?: string): void;
11
- loginWithApple(redirectUri?: string): void;
12
- loginWithTelegram(redirectUri?: string): void;
13
- loginPopup(idpHint: TIdpHint, redirectUri?: string): void;
14
- logout(redirectUri?: string): void;
15
- register(email?: string, redirectUri?: string): void;
16
- getToken(): string | undefined;
17
- isAtExp(): boolean;
18
- isRtExp(): boolean;
19
-
20
- readonly isAuth: Ref<boolean>;
21
- readonly checkAuth: Ref<boolean>;
22
- readonly keycloak: Ref<Keycloak | null>;
23
- readonly isInitialized: Ref<boolean>;
24
- readonly keycloakUserData: Ref<Keycloak.KeycloakTokenParsed | null>;
25
- }
26
-
27
- export const TOKEN_NAME = 'token';
28
- export const REFRESH_TOKEN_NAME = 'refresh-token';
29
- export const ID_TOKEN_NAME = 'id-token';
30
-
31
- const keycloak = ref<Keycloak | null>(null);
32
-
33
- const isAuth = ref(false);
34
- const checkAuth = ref(false);
35
- const keycloakUserData = ref<Keycloak.KeycloakTokenParsed | null>(null);
36
- const locale = ref('en');
37
-
38
- const dontChangeRedirectUri = ref(false);
39
- const keycloakRedirectUriIsLogout = ref<string | undefined>(undefined);
40
-
41
- export const setKeycloakLocale = (newLocale: LocationEnum) => {
42
- locale.value = newLocale;
43
- };
44
-
45
- export const setDontChangeRedirectUri = (newDontChangeRedirectUri: boolean) => {
46
- dontChangeRedirectUri.value = newDontChangeRedirectUri;
47
- };
48
-
49
- export const setKeycloakRedirectUriIsLogout = (newKeycloakRedirectUriIsLogout: string | undefined) => {
50
- keycloakRedirectUriIsLogout.value = newKeycloakRedirectUriIsLogout;
51
- };
52
-
53
- const isInitialized = ref(false);
54
-
55
- const getUrl = (): string => {
56
- const url = new URL(window.location.href);
57
- const searchParams = new URLSearchParams(window.location.search);
58
-
59
- if (searchParams.has('redirect_uri')) {
60
- const redirectUri = searchParams.get('redirect_uri');
61
- if (!!redirectUri) return redirectUri;
62
- }
63
-
64
- // если в роуте в meta есть параметр keycloakRedirectUriIsLogout - возвращаем его
65
- if (!!keycloakRedirectUriIsLogout.value && typeof keycloakRedirectUriIsLogout.value === 'string') return `${url.origin}/${locale.value}/${keycloakRedirectUriIsLogout.value}`;
66
-
67
- // если в $route.meta (который передаем из родительского приложения) есть параметр dontChangeRedirectUri - то из адреса НЕ нужно удалять или добавлять /user
68
- // если нет - то ничего не делать
69
-
70
- // if (!dontChangeRedirectUri) {
71
-
72
- // const path = url.pathname;
73
- // // Проверяем: путь начинается с /две латинские буквы/ и далее НЕ идёт user/
74
- // const match = path.match(/^\/([a-zA-Z]{2})(\/(?!user\/))/);
75
- // if (match) {
76
-
77
- // console.log('добавляем user')
78
-
79
- // // Вставляем 'user' после двухбуквенного сегмента
80
- // url.pathname = path.replace(/^\/([a-zA-Z]{2})\//, '/$1/user/');
81
- // // Если хочешь обновить текущую страницу:
82
- // // window.location.href = url.toString();
83
- // } else {
84
-
85
- // console.log('удаляем user')
86
-
87
- // url.pathname = path.replace(/^\/([a-zA-Z]{2})\/user\//, '/$1/');
88
- // }
89
- // }
90
- return url.toString();
91
- };
92
-
93
- function isMobile() {
94
- return /Mobi|Android|iPhone|iPad|iPod/i.test(navigator.userAgent);
95
- }
96
-
97
- export const getAuthMethods = () => {
98
- const methods = reactive({
99
- async loginPopup(idpHint: TIdpHint, redirectUri?: string) {
100
- redirectUri = redirectUri ?? getUrl();
101
- if (isMobile()) {
102
- switch (idpHint) {
103
- case 'google':
104
- methods.loginWithGoogle(redirectUri);
105
- break;
106
- case 'apple':
107
- methods.loginWithApple(redirectUri);
108
- break;
109
- default:
110
- methods.login(undefined, redirectUri);
111
- }
112
- return;
113
- }
114
-
115
- let loginUrl = await keycloak.value?.createLoginUrl({
116
- idpHint: idpHint === 'email' ? '' : idpHint,
117
- redirectUri,
118
- });
119
-
120
- let loginWindow = window.open((loginUrl ?? '') + (idpHint === 'google' ? '&prompt=select_account' : ''), 'Login with Google', 'width=500,height=600');
121
-
122
- const messageListener = async (event: MessageEvent) => {
123
- console.log('messageListener', event.data);
124
-
125
- if (event.data.type === 'keycloak-auth-success' && event.data.message === 'success') {
126
- window.removeEventListener('message', messageListener);
127
- //if (!loginWindow || !loginWindow.closed) {
128
- loginWindow?.close();
129
-
130
- console.log('window close', {
131
- loginWindow,
132
- closed: loginWindow?.closed,
133
- });
134
-
135
- //}
136
- setTimeout(() => {
137
- window.location.reload();
138
- console.log('window reload');
139
- }, 200);
140
- }
141
-
142
- // если в popup пришло сообщение о том, что нужно сменить idpHint, то меняем его и открываем новое окно
143
- if (event.data.type === 'keycloak-auth-change') {
144
- loginWindow?.close();
145
- idpHint = event.data.message as TIdpHint;
146
- loginUrl = await keycloak.value?.createLoginUrl({
147
- idpHint,
148
- redirectUri,
149
- });
150
- loginWindow = window.open((loginUrl ?? '') + (idpHint === 'google' ? '&prompt=select_account' : ''), 'Login with Google', 'width=500,height=600');
151
- }
152
- };
153
-
154
- window.addEventListener('message', messageListener);
155
- },
156
-
157
- login(email?: string, redirectUri?: string) {
158
- if (keycloak.value) {
159
- keycloak.value.login({
160
- redirectUri: redirectUri ?? getUrl(),
161
- loginHint: email ?? '',
162
- locale: locale.value,
163
- });
164
- } else {
165
- console.warn('Keycloak not defined! #login');
166
- }
167
- },
168
- logout(redirectUri?: string) {
169
- if (keycloak.value) {
170
- clearTokens();
171
- setTimeout(() => {
172
- keycloak.value &&
173
- keycloak.value.logout({
174
- redirectUri: redirectUri ?? getUrl(),
175
- });
176
- }, 100);
177
- } else {
178
- console.warn('Keycloak not defined! #logout');
179
- }
180
- },
181
- register(email?: string, redirectUri?: string) {
182
- if (keycloak.value) {
183
- keycloak.value.register({
184
- redirectUri: redirectUri ?? getUrl(),
185
- loginHint: email ?? '',
186
- locale: locale.value,
187
- });
188
- } else {
189
- console.warn('Keycloak not defined! #register');
190
- }
191
- },
192
- loginWithGoogle(redirectUri?: string) {
193
- if (keycloak.value) {
194
- keycloak.value
195
- ?.createLoginUrl({
196
- idpHint: 'google',
197
- redirectUri: redirectUri ?? getUrl(),
198
- })
199
- .then((loginUrl) => (window.location.href = `${loginUrl}&prompt=select_account`));
200
- } else {
201
- console.warn('Keycloak not defined! #loginWithGoogle');
202
- }
203
- },
204
- loginWithApple(redirectUri?: string) {
205
- if (keycloak.value) {
206
- keycloak.value.login({
207
- redirectUri: redirectUri ?? getUrl(),
208
- idpHint: 'apple',
209
- locale: locale.value,
210
- });
211
- } else {
212
- console.warn('Keycloak not defined! #loginWithApple');
213
- }
214
- },
215
- loginWithTelegram(redirectUri?: string) {
216
- if (keycloak.value) {
217
- keycloak.value.login({
218
- redirectUri: redirectUri ?? getUrl(),
219
- idpHint: 'telegram',
220
- locale: locale.value,
221
- });
222
- } else {
223
- console.warn('Keycloak not defined! #loginWithTelegram');
224
- }
225
- },
226
- changePassword(redirectUri?: string) {
227
- if (keycloak.value) {
228
- document.cookie = 'from=passport; SameSite=None; Secure';
229
- void keycloak.value.login({
230
- action: 'UPDATE_PASSWORD',
231
- redirectUri: redirectUri ?? getUrl(),
232
- });
233
- } else {
234
- console.warn('Keycloak not defined! #changePassword');
235
- }
236
- },
237
- configureOtp(redirectUri?: string) {
238
- if (keycloak.value) {
239
- document.cookie = 'from=passport; SameSite=None; Secure';
240
- void keycloak.value.login({
241
- action: 'CONFIGURE_TOTP',
242
- redirectUri: redirectUri ?? getUrl(),
243
- });
244
- } else {
245
- console.warn('Keycloak not defined! #configureOtp');
246
- }
247
- },
248
- });
249
- return methods;
250
- };
251
-
252
- function setTokens() {
253
- if (!keycloak.value || typeof window === 'undefined') return;
254
- !!keycloak.value?.token && localStorage.setItem(TOKEN_NAME, keycloak.value.token);
255
- !!keycloak.value?.refreshToken && localStorage.setItem(REFRESH_TOKEN_NAME, keycloak.value.refreshToken);
256
- !!keycloak.value?.idToken && localStorage.setItem(ID_TOKEN_NAME, keycloak.value.idToken);
257
-
258
- !!keycloak.value?.token && sessionStorage.setItem(TOKEN_NAME, keycloak.value.token);
259
- !!keycloak.value?.refreshToken && sessionStorage.setItem(REFRESH_TOKEN_NAME, keycloak.value.refreshToken);
260
- !!keycloak.value?.idToken && sessionStorage.setItem(ID_TOKEN_NAME, keycloak.value.idToken);
261
- }
262
-
263
- function clearTokens() {
264
- if (typeof window === 'undefined') return;
265
- localStorage.removeItem(TOKEN_NAME);
266
- localStorage.removeItem(REFRESH_TOKEN_NAME);
267
- localStorage.removeItem(ID_TOKEN_NAME);
268
- sessionStorage.removeItem(TOKEN_NAME);
269
- sessionStorage.removeItem(REFRESH_TOKEN_NAME);
270
- sessionStorage.removeItem(ID_TOKEN_NAME);
271
- }
272
-
273
- export const getToken = () => (IS_TELEGRAM_MINI_APP && !IS_LOCALHOST ? sessionStorage.getItem(TOKEN_NAME) : localStorage.getItem(TOKEN_NAME)) ?? undefined;
274
-
275
- const parseJwt = (token: unknown) => {
276
- if (typeof token !== 'string') throw new Error('Invalid JWT format: #1');
277
- const [headerB64, payloadB64] = token.split('.');
278
- if (!headerB64 || !payloadB64) throw new Error('Invalid JWT format: #2');
279
- const decodeBase64Url = (str: string) => JSON.parse(atob(str.replace(/-/g, '+').replace(/_/g, '/')));
280
- const header = decodeBase64Url(headerB64);
281
- const payload = decodeBase64Url(payloadB64);
282
- const now = Math.floor(Date.now() / 1000);
283
- const isExpired = payload.exp !== undefined && now > payload.exp;
284
- return {
285
- header,
286
- payload,
287
- isExpired,
288
- expiresAt: payload.exp ? new Date(payload.exp * 1000).toISOString() : null,
289
- };
290
- };
291
-
292
- export const isAtExp = () => {
293
- if (typeof window === 'undefined') return false;
294
- try {
295
- return parseJwt(localStorage.getItem(TOKEN_NAME)).isExpired;
296
- } catch (e) {
297
- return false;
298
- }
299
- };
300
-
301
- export const isRtExp = () => {
302
- if (typeof window === 'undefined') return false;
303
- try {
304
- // если рт не истек, возвращаем true
305
- return parseJwt(localStorage.getItem(REFRESH_TOKEN_NAME)).isExpired;
306
- } catch (e) {
307
- clearTokens();
308
- if (e instanceof Error) {
309
- console.log('checkIsPassportAuth error: ', e.message);
310
- }
311
- return false;
312
- }
313
- };
314
-
315
- // const isPopup = () => {
316
- // console.log('run isPopup');
317
- // // для авторизации в popup - это запускается в дочернем окне
1
+ // import Keycloak, { type KeycloakInitOptions } from 'keycloak-js';
2
+ // import { inject, reactive, readonly, type Ref, ref } from 'vue';
3
+ // import { postWebLogin } from '../api/wallet/endpoints';
4
+ // import { AppNameEnum, APP_NAME, IS_TELEGRAM_MINI_APP, KEYCLOAK_LOGIN_REQUIRED, OPENID_CLIENT_ID, OPENID_REALM, OPENID_URL, LocationEnum, IS_LOCALHOST } from '@alfabit/constants';
5
+
6
+ // export type TIdpHint = 'email' | 'google' | 'apple';
7
+
8
+ // export interface IUseKeycloak {
9
+ // login(email?: string, redirectUri?: string): void;
10
+ // loginWithGoogle(redirectUri?: string): void;
11
+ // loginWithApple(redirectUri?: string): void;
12
+ // loginWithTelegram(redirectUri?: string): void;
13
+ // loginPopup(idpHint: TIdpHint, redirectUri?: string): void;
14
+ // logout(redirectUri?: string): void;
15
+ // register(email?: string, redirectUri?: string): void;
16
+ // getToken(): string | undefined;
17
+ // isAtExp(): boolean;
18
+ // isRtExp(): boolean;
19
+
20
+ // readonly isAuth: Ref<boolean>;
21
+ // readonly checkAuth: Ref<boolean>;
22
+ // readonly keycloak: Ref<Keycloak | null>;
23
+ // readonly isInitialized: Ref<boolean>;
24
+ // readonly keycloakUserData: Ref<Keycloak.KeycloakTokenParsed | null>;
25
+ // }
26
+
27
+ // export const TOKEN_NAME = 'token';
28
+ // export const REFRESH_TOKEN_NAME = 'refresh-token';
29
+ // export const ID_TOKEN_NAME = 'id-token';
30
+
31
+ // const keycloak = ref<Keycloak | null>(null);
32
+
33
+ // const isAuth = ref(false);
34
+ // const checkAuth = ref(false);
35
+ // const keycloakUserData = ref<Keycloak.KeycloakTokenParsed | null>(null);
36
+ // const locale = ref('en');
37
+
38
+ // const dontChangeRedirectUri = ref(false);
39
+ // const keycloakRedirectUriIsLogout = ref<string | undefined>(undefined);
40
+
41
+ // export const setKeycloakLocale = (newLocale: LocationEnum) => {
42
+ // locale.value = newLocale;
43
+ // };
44
+
45
+ // export const setDontChangeRedirectUri = (newDontChangeRedirectUri: boolean) => {
46
+ // dontChangeRedirectUri.value = newDontChangeRedirectUri;
47
+ // };
48
+
49
+ // export const setKeycloakRedirectUriIsLogout = (newKeycloakRedirectUriIsLogout: string | undefined) => {
50
+ // keycloakRedirectUriIsLogout.value = newKeycloakRedirectUriIsLogout;
51
+ // };
52
+
53
+ // const isInitialized = ref(false);
54
+
55
+ // const getUrl = (): string => {
56
+ // const url = new URL(window.location.href);
57
+ // const searchParams = new URLSearchParams(window.location.search);
58
+
59
+ // if (searchParams.has('redirect_uri')) {
60
+ // const redirectUri = searchParams.get('redirect_uri');
61
+ // if (!!redirectUri) return redirectUri;
62
+ // }
63
+
64
+ // // если в роуте в meta есть параметр keycloakRedirectUriIsLogout - возвращаем его
65
+ // if (!!keycloakRedirectUriIsLogout.value && typeof keycloakRedirectUriIsLogout.value === 'string') return `${url.origin}/${locale.value}/${keycloakRedirectUriIsLogout.value}`;
66
+
67
+ // // если в $route.meta (который передаем из родительского приложения) есть параметр dontChangeRedirectUri - то из адреса НЕ нужно удалять или добавлять /user
68
+ // // если нет - то ничего не делать
69
+
70
+ // // if (!dontChangeRedirectUri) {
71
+
72
+ // // const path = url.pathname;
73
+ // // // Проверяем: путь начинается с /две латинские буквы/ и далее НЕ идёт user/
74
+ // // const match = path.match(/^\/([a-zA-Z]{2})(\/(?!user\/))/);
75
+ // // if (match) {
76
+
77
+ // // console.log('добавляем user')
78
+
79
+ // // // Вставляем 'user' после двухбуквенного сегмента
80
+ // // url.pathname = path.replace(/^\/([a-zA-Z]{2})\//, '/$1/user/');
81
+ // // // Если хочешь обновить текущую страницу:
82
+ // // // window.location.href = url.toString();
83
+ // // } else {
84
+
85
+ // // console.log('удаляем user')
86
+
87
+ // // url.pathname = path.replace(/^\/([a-zA-Z]{2})\/user\//, '/$1/');
88
+ // // }
89
+ // // }
90
+ // return url.toString();
91
+ // };
92
+
93
+ // function isMobile() {
94
+ // return /Mobi|Android|iPhone|iPad|iPod/i.test(navigator.userAgent);
95
+ // }
96
+
97
+ // export const getAuthMethods = () => {
98
+ // const methods = reactive({
99
+ // async loginPopup(idpHint: TIdpHint, redirectUri?: string) {
100
+ // redirectUri = redirectUri ?? getUrl();
101
+ // if (isMobile()) {
102
+ // switch (idpHint) {
103
+ // case 'google':
104
+ // methods.loginWithGoogle(redirectUri);
105
+ // break;
106
+ // case 'apple':
107
+ // methods.loginWithApple(redirectUri);
108
+ // break;
109
+ // default:
110
+ // methods.login(undefined, redirectUri);
111
+ // }
112
+ // return;
113
+ // }
114
+
115
+ // let loginUrl = await keycloak.value?.createLoginUrl({
116
+ // idpHint: idpHint === 'email' ? '' : idpHint,
117
+ // redirectUri,
118
+ // });
119
+
120
+ // let loginWindow = window.open((loginUrl ?? '') + (idpHint === 'google' ? '&prompt=select_account' : ''), 'Login with Google', 'width=500,height=600');
121
+
122
+ // const messageListener = async (event: MessageEvent) => {
123
+ // console.log('messageListener', event.data);
124
+
125
+ // if (event.data.type === 'keycloak-auth-success' && event.data.message === 'success') {
126
+ // window.removeEventListener('message', messageListener);
127
+ // //if (!loginWindow || !loginWindow.closed) {
128
+ // loginWindow?.close();
129
+
130
+ // console.log('window close', {
131
+ // loginWindow,
132
+ // closed: loginWindow?.closed,
133
+ // });
134
+
135
+ // //}
136
+ // setTimeout(() => {
137
+ // window.location.reload();
138
+ // console.log('window reload');
139
+ // }, 200);
140
+ // }
141
+
142
+ // // если в popup пришло сообщение о том, что нужно сменить idpHint, то меняем его и открываем новое окно
143
+ // if (event.data.type === 'keycloak-auth-change') {
144
+ // loginWindow?.close();
145
+ // idpHint = event.data.message as TIdpHint;
146
+ // loginUrl = await keycloak.value?.createLoginUrl({
147
+ // idpHint,
148
+ // redirectUri,
149
+ // });
150
+ // loginWindow = window.open((loginUrl ?? '') + (idpHint === 'google' ? '&prompt=select_account' : ''), 'Login with Google', 'width=500,height=600');
151
+ // }
152
+ // };
153
+
154
+ // window.addEventListener('message', messageListener);
155
+ // },
156
+
157
+ // login(email?: string, redirectUri?: string) {
158
+ // if (keycloak.value) {
159
+ // keycloak.value.login({
160
+ // redirectUri: redirectUri ?? getUrl(),
161
+ // loginHint: email ?? '',
162
+ // locale: locale.value,
163
+ // });
164
+ // } else {
165
+ // console.warn('Keycloak not defined! #login');
166
+ // }
167
+ // },
168
+ // logout(redirectUri?: string) {
169
+ // if (keycloak.value) {
170
+ // clearTokens();
171
+ // setTimeout(() => {
172
+ // keycloak.value &&
173
+ // keycloak.value.logout({
174
+ // redirectUri: redirectUri ?? getUrl(),
175
+ // });
176
+ // }, 100);
177
+ // } else {
178
+ // console.warn('Keycloak not defined! #logout');
179
+ // }
180
+ // },
181
+ // register(email?: string, redirectUri?: string) {
182
+ // if (keycloak.value) {
183
+ // keycloak.value.register({
184
+ // redirectUri: redirectUri ?? getUrl(),
185
+ // loginHint: email ?? '',
186
+ // locale: locale.value,
187
+ // });
188
+ // } else {
189
+ // console.warn('Keycloak not defined! #register');
190
+ // }
191
+ // },
192
+ // loginWithGoogle(redirectUri?: string) {
193
+ // if (keycloak.value) {
194
+ // keycloak.value
195
+ // ?.createLoginUrl({
196
+ // idpHint: 'google',
197
+ // redirectUri: redirectUri ?? getUrl(),
198
+ // })
199
+ // .then((loginUrl) => (window.location.href = `${loginUrl}&prompt=select_account`));
200
+ // } else {
201
+ // console.warn('Keycloak not defined! #loginWithGoogle');
202
+ // }
203
+ // },
204
+ // loginWithApple(redirectUri?: string) {
205
+ // if (keycloak.value) {
206
+ // keycloak.value.login({
207
+ // redirectUri: redirectUri ?? getUrl(),
208
+ // idpHint: 'apple',
209
+ // locale: locale.value,
210
+ // });
211
+ // } else {
212
+ // console.warn('Keycloak not defined! #loginWithApple');
213
+ // }
214
+ // },
215
+ // loginWithTelegram(redirectUri?: string) {
216
+ // if (keycloak.value) {
217
+ // keycloak.value.login({
218
+ // redirectUri: redirectUri ?? getUrl(),
219
+ // idpHint: 'telegram',
220
+ // locale: locale.value,
221
+ // });
222
+ // } else {
223
+ // console.warn('Keycloak not defined! #loginWithTelegram');
224
+ // }
225
+ // },
226
+ // changePassword(redirectUri?: string) {
227
+ // if (keycloak.value) {
228
+ // document.cookie = 'from=passport; SameSite=None; Secure';
229
+ // void keycloak.value.login({
230
+ // action: 'UPDATE_PASSWORD',
231
+ // redirectUri: redirectUri ?? getUrl(),
232
+ // });
233
+ // } else {
234
+ // console.warn('Keycloak not defined! #changePassword');
235
+ // }
236
+ // },
237
+ // configureOtp(redirectUri?: string) {
238
+ // if (keycloak.value) {
239
+ // document.cookie = 'from=passport; SameSite=None; Secure';
240
+ // void keycloak.value.login({
241
+ // action: 'CONFIGURE_TOTP',
242
+ // redirectUri: redirectUri ?? getUrl(),
243
+ // });
244
+ // } else {
245
+ // console.warn('Keycloak not defined! #configureOtp');
246
+ // }
247
+ // },
248
+ // });
249
+ // return methods;
250
+ // };
251
+
252
+ // function setTokens() {
253
+ // if (!keycloak.value || typeof window === 'undefined') return;
254
+ // !!keycloak.value?.token && localStorage.setItem(TOKEN_NAME, keycloak.value.token);
255
+ // !!keycloak.value?.refreshToken && localStorage.setItem(REFRESH_TOKEN_NAME, keycloak.value.refreshToken);
256
+ // !!keycloak.value?.idToken && localStorage.setItem(ID_TOKEN_NAME, keycloak.value.idToken);
257
+
258
+ // !!keycloak.value?.token && sessionStorage.setItem(TOKEN_NAME, keycloak.value.token);
259
+ // !!keycloak.value?.refreshToken && sessionStorage.setItem(REFRESH_TOKEN_NAME, keycloak.value.refreshToken);
260
+ // !!keycloak.value?.idToken && sessionStorage.setItem(ID_TOKEN_NAME, keycloak.value.idToken);
261
+ // }
262
+
263
+ // function clearTokens() {
264
+ // if (typeof window === 'undefined') return;
265
+ // localStorage.removeItem(TOKEN_NAME);
266
+ // localStorage.removeItem(REFRESH_TOKEN_NAME);
267
+ // localStorage.removeItem(ID_TOKEN_NAME);
268
+ // sessionStorage.removeItem(TOKEN_NAME);
269
+ // sessionStorage.removeItem(REFRESH_TOKEN_NAME);
270
+ // sessionStorage.removeItem(ID_TOKEN_NAME);
271
+ // }
272
+
273
+ // export const getToken = () => (IS_TELEGRAM_MINI_APP && !IS_LOCALHOST ? sessionStorage.getItem(TOKEN_NAME) : localStorage.getItem(TOKEN_NAME)) ?? undefined;
274
+
275
+ // const parseJwt = (token: unknown) => {
276
+ // if (typeof token !== 'string') throw new Error('Invalid JWT format: #1');
277
+ // const [headerB64, payloadB64] = token.split('.');
278
+ // if (!headerB64 || !payloadB64) throw new Error('Invalid JWT format: #2');
279
+ // const decodeBase64Url = (str: string) => JSON.parse(atob(str.replace(/-/g, '+').replace(/_/g, '/')));
280
+ // const header = decodeBase64Url(headerB64);
281
+ // const payload = decodeBase64Url(payloadB64);
282
+ // const now = Math.floor(Date.now() / 1000);
283
+ // const isExpired = payload.exp !== undefined && now > payload.exp;
284
+ // return {
285
+ // header,
286
+ // payload,
287
+ // isExpired,
288
+ // expiresAt: payload.exp ? new Date(payload.exp * 1000).toISOString() : null,
289
+ // };
290
+ // };
291
+
292
+ // export const isAtExp = () => {
293
+ // if (typeof window === 'undefined') return false;
294
+ // try {
295
+ // return parseJwt(localStorage.getItem(TOKEN_NAME)).isExpired;
296
+ // } catch (e) {
297
+ // return false;
298
+ // }
299
+ // };
300
+
301
+ // export const isRtExp = () => {
302
+ // if (typeof window === 'undefined') return false;
318
303
  // try {
319
- // // Отправляем сообщение родителю
320
- // if (window.opener) {
321
- // console.log('window opener');
322
-
323
- // window.opener.postMessage(
324
- // {
325
- // type: 'keycloak-auth-success',
326
- // message: 'success',
327
- // },
328
- // '*'
329
- // );
304
+ // // если рт не истек, возвращаем true
305
+ // return parseJwt(localStorage.getItem(REFRESH_TOKEN_NAME)).isExpired;
306
+ // } catch (e) {
307
+ // clearTokens();
308
+ // if (e instanceof Error) {
309
+ // console.log('checkIsPassportAuth error: ', e.message);
330
310
  // }
331
- // } catch (err) {
332
- // console.warn('Error in login-popup-redirect.html:', err);
311
+ // return false;
333
312
  // }
334
313
  // };
335
314
 
336
- let isInitKeycloak = false;
337
-
338
- export async function initKeycloak() {
339
- if (!!keycloak.value || typeof window === 'undefined' || isInitKeycloak) return;
340
- isInitKeycloak = true;
341
-
342
- if (!OPENID_URL) throw new Error('Не задана переменная keycloak: url');
343
- if (!OPENID_REALM) throw new Error('Не задана переменная keycloak: realm');
344
- if (!OPENID_CLIENT_ID) throw new Error('Не задана переменная keycloak: clientId');
345
-
346
- // console.log({
347
- // OPENID_URL,
348
- // OPENID_REALM,
349
- // OPENID_CLIENT_ID,
350
-
351
- // VITE_OPENID_URL: import.meta.env?.VITE_OPENID_URL,
352
- // VITE_PUBLIC_KEYCLOAK_URL: import.meta.env?.VITE_PUBLIC_KEYCLOAK_URL,
353
- // VITE_OPENID_REALM: import.meta.env?.VITE_OPENID_REALM,
354
- // VITE_PUBLIC_KEYCLOAK_REALM: import.meta.env?.VITE_PUBLIC_KEYCLOAK_REALM,
355
- // VITE_OPENID_CLIENT_ID: import.meta.env?.VITE_OPENID_CLIENT_ID,
356
- // VITE_PUBLIC_KEYCLOAK_CLIENT_ID: import.meta.env?.VITE_PUBLIC_KEYCLOAK_CLIENT_ID,
357
- // });
358
-
359
- keycloak.value = new Keycloak({
360
- url: OPENID_URL,
361
- realm: OPENID_REALM,
362
- clientId: OPENID_CLIENT_ID,
363
- });
364
-
365
-
366
-
367
- keycloak.value && (keycloak.value.onAuthLogout = () => {
368
- console.warn('>>>>>>>> Сессия истекла');
369
- // например, показать уведомление
370
- // или открыть собственное модальное окно логина
371
- });
372
-
373
-
374
-
375
-
376
- const isNeedAuth = !!getToken() && !isRtExp();
377
-
378
- // window.opener - если находимся в popup (но не в passport), то 100% уже авторизованы и можно поставить login-required
379
- const initOptions: KeycloakInitOptions = {
380
- pkceMethod: 'S256',
381
- checkLoginIframe: false,
382
- // enableLogging: true,
383
- };
384
-
385
- // Устанавливаем onLoad только если нужно
386
- if (KEYCLOAK_LOGIN_REQUIRED || (APP_NAME !== AppNameEnum.PASSPORT)) {
387
- initOptions.onLoad = 'login-required';
388
- } else if (isNeedAuth) {
389
- initOptions.onLoad = 'check-sso';
390
- // clearTokens();
391
- // window.location.href = getUrl() as string;
392
- }
393
-
394
- if (!isNeedAuth) {
395
- clearTokens();
396
- } else {
397
- const token = localStorage.getItem(TOKEN_NAME);
398
- const refreshToken = localStorage.getItem(REFRESH_TOKEN_NAME);
399
- const idToken = localStorage.getItem(ID_TOKEN_NAME);
400
-
401
- if (token) initOptions.token = token;
402
- if (refreshToken) initOptions.refreshToken = refreshToken;
403
- if (idToken) initOptions.idToken = idToken;
404
- }
405
-
406
- try {
407
- const res = await keycloak.value.init(initOptions);
408
-
409
- setTokens();
410
-
411
- if (res) {
412
- //await keycloak.value.updateToken(70);
413
- setTokens();
414
- // isPopup();
415
- keycloakUserData.value = keycloak.value?.tokenParsed ?? null;
416
- isAuth.value = true;
417
- try {
418
- postWebLogin();
419
- } catch (e) { }
420
-
421
- //setTimeout(() => {
422
- setInterval(async () => {
423
- if (!keycloak.value) return;
424
-
425
-
426
- try {
427
- const res = await keycloak.value.updateToken(70);
428
- if (res) {
429
- setTokens();
430
- keycloakUserData.value = keycloak.value?.tokenParsed ?? null;
431
- isAuth.value = true;
432
- try {
433
- postWebLogin();
434
- } catch { }
435
- }
436
- }
437
- catch (e) {
438
- console.warn('Ошибка Keycloak:', e);
439
- keycloak.value?.clearToken();
440
- }
441
-
442
-
443
-
444
- }, 6000);
445
- //}, 60000);
446
- }
447
- return isAuth.value;
448
- } catch (error) {
449
- console.warn('Ошибка Keycloak:', error);
450
- isAuth.value = false;
451
- return false;
452
- } finally {
453
- checkAuth.value = true;
454
- }
455
- }
456
-
457
- interface IKeycliakInit {
458
- keycloakInit?: Ref<Keycloak | null | undefined> | undefined;
459
- }
460
-
461
- export async function createKeycloakInit({ keycloakInit }: IKeycliakInit = {}) {
462
- if (typeof window === 'undefined') return;
463
- if (!!keycloakInit && keycloakInit?.value) {
464
- keycloak.value = keycloakInit.value;
465
- isAuth.value = keycloak.value?.authenticated ?? false;
466
- } else {
467
- await initKeycloak();
468
- }
469
- isInitialized.value = true;
470
- }
471
-
472
- // ...весь остальной код до сюда не меняется...
473
-
474
- let _keycloakInit: IUseKeycloak | null = null;
475
-
476
- export const keycloakInit = (dontChangeRedirectUri?: Ref<boolean>, keycloakRedirectUriIsLogout?: Ref<string | undefined>): IUseKeycloak => {
477
- if (_keycloakInit) return _keycloakInit;
478
-
479
- dontChangeRedirectUri ||= inject('dontChangeRedirectUri', ref(false));
480
- keycloakRedirectUriIsLogout ||= inject('keycloakRedirectUriIsLogout', ref(undefined));
481
-
482
- _keycloakInit = {
483
- keycloak: readonly(keycloak) as Ref<Keycloak | null>,
484
- isInitialized: readonly(isInitialized),
485
- isAuth: readonly(isAuth),
486
- checkAuth: readonly(checkAuth),
487
-
488
- keycloakUserData,
489
-
490
- ...getAuthMethods(),
491
- getToken,
492
- isAtExp,
493
- isRtExp,
494
- };
495
- return _keycloakInit;
496
- };
315
+ // // const isPopup = () => {
316
+ // // console.log('run isPopup');
317
+ // // // для авторизации в popup - это запускается в дочернем окне
318
+ // // try {
319
+ // // // Отправляем сообщение родителю
320
+ // // if (window.opener) {
321
+ // // console.log('window opener');
322
+
323
+ // // window.opener.postMessage(
324
+ // // {
325
+ // // type: 'keycloak-auth-success',
326
+ // // message: 'success',
327
+ // // },
328
+ // // '*'
329
+ // // );
330
+ // // }
331
+ // // } catch (err) {
332
+ // // console.warn('Error in login-popup-redirect.html:', err);
333
+ // // }
334
+ // // };
335
+
336
+ // let isInitKeycloak = false;
337
+
338
+ // export async function initKeycloak() {
339
+ // if (!!keycloak.value || typeof window === 'undefined' || isInitKeycloak) return;
340
+ // isInitKeycloak = true;
341
+
342
+ // if (!OPENID_URL) throw new Error('Не задана переменная keycloak: url');
343
+ // if (!OPENID_REALM) throw new Error('Не задана переменная keycloak: realm');
344
+ // if (!OPENID_CLIENT_ID) throw new Error('Не задана переменная keycloak: clientId');
345
+
346
+ // // console.log({
347
+ // // OPENID_URL,
348
+ // // OPENID_REALM,
349
+ // // OPENID_CLIENT_ID,
350
+
351
+ // // VITE_OPENID_URL: import.meta.env?.VITE_OPENID_URL,
352
+ // // VITE_PUBLIC_KEYCLOAK_URL: import.meta.env?.VITE_PUBLIC_KEYCLOAK_URL,
353
+ // // VITE_OPENID_REALM: import.meta.env?.VITE_OPENID_REALM,
354
+ // // VITE_PUBLIC_KEYCLOAK_REALM: import.meta.env?.VITE_PUBLIC_KEYCLOAK_REALM,
355
+ // // VITE_OPENID_CLIENT_ID: import.meta.env?.VITE_OPENID_CLIENT_ID,
356
+ // // VITE_PUBLIC_KEYCLOAK_CLIENT_ID: import.meta.env?.VITE_PUBLIC_KEYCLOAK_CLIENT_ID,
357
+ // // });
358
+
359
+ // keycloak.value = new Keycloak({
360
+ // url: OPENID_URL,
361
+ // realm: OPENID_REALM,
362
+ // clientId: OPENID_CLIENT_ID,
363
+ // });
364
+
365
+
366
+
367
+ // // keycloak.value && (keycloak.value.onAuthLogout = () => {
368
+ // // console.warn('>>>>>>>> Сессия истекла');
369
+ // // // например, показать уведомление
370
+ // // // или открыть собственное модальное окно логина
371
+ // // });
372
+
373
+
374
+
375
+
376
+ // const isNeedAuth = !!getToken() && !isRtExp();
377
+
378
+ // // window.opener - если находимся в popup (но не в passport), то 100% уже авторизованы и можно поставить login-required
379
+ // const initOptions: KeycloakInitOptions = {
380
+ // pkceMethod: 'S256',
381
+ // checkLoginIframe: false,
382
+ // // enableLogging: true,
383
+ // };
384
+
385
+ // // Устанавливаем onLoad только если нужно
386
+ // if (KEYCLOAK_LOGIN_REQUIRED || (APP_NAME !== AppNameEnum.PASSPORT)) {
387
+ // initOptions.onLoad = 'login-required';
388
+ // } else if (isNeedAuth) {
389
+ // initOptions.onLoad = 'check-sso';
390
+ // // clearTokens();
391
+ // // window.location.href = getUrl() as string;
392
+ // }
393
+
394
+ // if (!isNeedAuth) {
395
+ // clearTokens();
396
+ // } else {
397
+ // const token = localStorage.getItem(TOKEN_NAME);
398
+ // const refreshToken = localStorage.getItem(REFRESH_TOKEN_NAME);
399
+ // const idToken = localStorage.getItem(ID_TOKEN_NAME);
400
+
401
+ // if (token) initOptions.token = token;
402
+ // if (refreshToken) initOptions.refreshToken = refreshToken;
403
+ // if (idToken) initOptions.idToken = idToken;
404
+ // }
405
+
406
+ // try {
407
+ // const res = await keycloak.value.init(initOptions);
408
+
409
+ // setTokens();
410
+
411
+ // if (res) {
412
+ // //await keycloak.value.updateToken(70);
413
+ // setTokens();
414
+ // // isPopup();
415
+ // keycloakUserData.value = keycloak.value?.tokenParsed ?? null;
416
+ // isAuth.value = true;
417
+ // try {
418
+ // postWebLogin();
419
+ // } catch (e) { }
420
+
421
+ // //setTimeout(() => {
422
+ // setInterval(async () => {
423
+ // if (!keycloak.value) return;
424
+
425
+
426
+ // try {
427
+ // const res = await keycloak.value.updateToken(70);
428
+ // if (res) {
429
+ // setTokens();
430
+ // keycloakUserData.value = keycloak.value?.tokenParsed ?? null;
431
+ // isAuth.value = true;
432
+ // try {
433
+ // postWebLogin();
434
+ // } catch { }
435
+ // }
436
+ // }
437
+ // catch (e) {
438
+ // console.warn('Ошибка Keycloak:', e);
439
+ // keycloak.value?.clearToken();
440
+ // }
441
+
442
+
443
+
444
+ // }, 6000);
445
+ // //}, 60000);
446
+ // }
447
+ // return isAuth.value;
448
+ // } catch (error) {
449
+ // console.warn('Ошибка Keycloak:', error);
450
+ // isAuth.value = false;
451
+ // return false;
452
+ // } finally {
453
+ // checkAuth.value = true;
454
+ // }
455
+ // }
456
+
457
+ // interface IKeycliakInit {
458
+ // keycloakInit?: Ref<Keycloak | null | undefined> | undefined;
459
+ // }
460
+
461
+ // export async function createKeycloakInit({ keycloakInit }: IKeycliakInit = {}) {
462
+ // if (typeof window === 'undefined') return;
463
+ // if (!!keycloakInit && keycloakInit?.value) {
464
+ // keycloak.value = keycloakInit.value;
465
+ // isAuth.value = keycloak.value?.authenticated ?? false;
466
+ // } else {
467
+ // await initKeycloak();
468
+ // }
469
+ // isInitialized.value = true;
470
+ // }
471
+
472
+ // // ...весь остальной код до сюда не меняется...
473
+
474
+ // let _keycloakInit: IUseKeycloak | null = null;
475
+
476
+ // export const keycloakInit = (dontChangeRedirectUri?: Ref<boolean>, keycloakRedirectUriIsLogout?: Ref<string | undefined>): IUseKeycloak => {
477
+ // if (_keycloakInit) return _keycloakInit;
478
+
479
+ // dontChangeRedirectUri ||= inject('dontChangeRedirectUri', ref(false));
480
+ // keycloakRedirectUriIsLogout ||= inject('keycloakRedirectUriIsLogout', ref(undefined));
481
+
482
+ // _keycloakInit = {
483
+ // keycloak: readonly(keycloak) as Ref<Keycloak | null>,
484
+ // isInitialized: readonly(isInitialized),
485
+ // isAuth: readonly(isAuth),
486
+ // checkAuth: readonly(checkAuth),
487
+
488
+ // keycloakUserData,
489
+
490
+ // ...getAuthMethods(),
491
+ // getToken,
492
+ // isAtExp,
493
+ // isRtExp,
494
+ // };
495
+ // return _keycloakInit;
496
+ // };