@spidy092/auth-client 1.0.7 → 1.0.9

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.
Files changed (4) hide show
  1. package/config.js +15 -4
  2. package/core.js +100 -46
  3. package/index.js +8 -5
  4. package/package.json +1 -1
package/config.js CHANGED
@@ -1,8 +1,11 @@
1
+ // auth-client/config.js
1
2
  let config = {
2
3
  clientKey: null,
3
4
  authBaseUrl: null,
4
5
  redirectUri: null,
5
- usePkce: false, // optional future
6
+ accountUiUrl: null,
7
+ isRouter: false, // ✅ Add router flag
8
+ usePkce: false,
6
9
  };
7
10
 
8
11
  export function setConfig(customConfig = {}) {
@@ -14,13 +17,21 @@ export function setConfig(customConfig = {}) {
14
17
  ...config,
15
18
  ...customConfig,
16
19
  redirectUri: customConfig.redirectUri || window.location.origin + '/callback',
20
+ // ✅ Auto-detect router mode
21
+ isRouter: customConfig.isRouter || customConfig.clientKey === 'account-ui'
17
22
  };
23
+
24
+ console.log(`🔧 Auth Client Mode: ${config.isRouter ? 'ROUTER' : 'CLIENT'}`, {
25
+ clientKey: config.clientKey,
26
+ isRouter: config.isRouter
27
+ });
18
28
  }
19
29
 
20
30
  export function getConfig() {
21
31
  return { ...config };
22
32
  }
23
33
 
24
-
25
-
26
- // pass client key and authbaseurl and redirectUri
34
+ // ✅ Helper function
35
+ export function isRouterMode() {
36
+ return config.isRouter;
37
+ }
package/core.js CHANGED
@@ -1,89 +1,141 @@
1
+ // auth-client/core.js
1
2
  import { setToken, clearToken, getToken } from './token';
2
- import { getConfig } from './config';
3
+ import { getConfig, isRouterMode } from './config';
3
4
 
4
- export function login(clientKeyArg, redirectUriArg) { // Removed stateArg
5
+ export function login(clientKeyArg, redirectUriArg) {
5
6
  const {
6
- clientKey: defaultClientKey,
7
- authBaseUrl,
8
- redirectUri: defaultRedirectUri,
9
- accountUiUrl
7
+ clientKey: defaultClientKey,
8
+ authBaseUrl,
9
+ redirectUri: defaultRedirectUri,
10
+ accountUiUrl
10
11
  } = getConfig();
11
12
 
12
13
  const clientKey = clientKeyArg || defaultClientKey;
13
14
  const redirectUri = redirectUriArg || defaultRedirectUri;
14
- // Removed state generation
15
15
 
16
- console.log('Initiating login with parameters:', {
16
+ console.log('🔄 Smart Login initiated:', {
17
+ mode: isRouterMode() ? 'ROUTER' : 'CLIENT',
17
18
  clientKey,
18
19
  redirectUri
19
- // Removed state from logging
20
20
  });
21
-
21
+
22
22
  if (!clientKey || !redirectUri) {
23
23
  throw new Error('Missing clientKey or redirectUri');
24
24
  }
25
25
 
26
- // Store only app info, no state
26
+ // Store app info
27
27
  sessionStorage.setItem('originalApp', clientKey);
28
28
  sessionStorage.setItem('returnUrl', redirectUri);
29
29
 
30
- // --- ENTERPRISE LOGIC ---
31
- // If we are already in Account-UI, go straight to the backend
32
- if (window.location.origin === accountUiUrl && clientKey === 'account-ui') {
33
- // Direct SSO kick-off for Account-UI (no state parameter)
34
- const backendLoginUrl = `${authBaseUrl}/login/${clientKey}?redirect_uri=${encodeURIComponent(redirectUri)}`;
35
- console.log('Redirecting directly to auth backend:', backendLoginUrl);
36
- window.location.href = backendLoginUrl;
37
- return;
30
+ // Smart Router Logic
31
+ if (isRouterMode()) {
32
+ // Router mode: Direct backend authentication
33
+ return routerLogin(clientKey, redirectUri);
34
+ } else {
35
+ // Client mode: Redirect to centralized login
36
+ return clientLogin(clientKey, redirectUri);
38
37
  }
38
+ }
39
39
 
40
- // Otherwise, centralized login flow (for other apps, no state)
41
- const accountLoginUrl = `${accountUiUrl}/login?` + new URLSearchParams({
42
- client: clientKey,
43
- redirect_uri: redirectUri
44
- // Removed state
40
+ // Router mode: Direct backend call
41
+ function routerLogin(clientKey, redirectUri) {
42
+ const { authBaseUrl } = getConfig();
43
+ const backendLoginUrl = `${authBaseUrl}/login/${clientKey}?redirect_uri=${encodeURIComponent(redirectUri)}`;
44
+
45
+ console.log('🏭 Router Login: Direct backend authentication', {
46
+ clientKey,
47
+ redirectUri,
48
+ backendUrl: backendLoginUrl
45
49
  });
46
- console.log('Redirecting to centralized Account UI:', accountLoginUrl);
47
- window.location.href = accountLoginUrl;
50
+
51
+ window.location.href = backendLoginUrl;
52
+ }
53
+
54
+ // ✅ Client mode: Centralized login
55
+ function clientLogin(clientKey, redirectUri) {
56
+ const { accountUiUrl } = getConfig();
57
+ const centralizedLoginUrl = `${accountUiUrl}/login?client=${clientKey}&redirect_uri=${encodeURIComponent(redirectUri)}`;
58
+
59
+ console.log('🔄 Client Login: Redirecting to centralized login', {
60
+ clientKey,
61
+ redirectUri,
62
+ centralizedUrl: centralizedLoginUrl
63
+ });
64
+
65
+ window.location.href = centralizedLoginUrl;
48
66
  }
49
67
 
50
68
  export function logout() {
51
69
  const { clientKey, authBaseUrl, accountUiUrl } = getConfig();
52
70
  const token = getToken();
53
-
54
- if (!token) {
55
- window.location.href = `${accountUiUrl}/login`;
56
- return;
57
- }
58
71
 
72
+ console.log('🚪 Smart Logout initiated:', {
73
+ mode: isRouterMode() ? 'ROUTER' : 'CLIENT',
74
+ clientKey,
75
+ hasToken: !!token
76
+ });
77
+
78
+ // Clear local storage immediately
59
79
  clearToken();
80
+ sessionStorage.clear();
81
+
82
+ if (isRouterMode()) {
83
+ // Router logout: Backend logout for all sessions
84
+ return routerLogout(clientKey, authBaseUrl, accountUiUrl, token);
85
+ } else {
86
+ // Client logout: Simple redirect to centralized login
87
+ return clientLogout(clientKey, accountUiUrl);
88
+ }
89
+ }
90
+
91
+ // ✅ Router logout
92
+ async function routerLogout(clientKey, authBaseUrl, accountUiUrl, token) {
93
+ console.log('🏭 Router Logout: Backend logout for all sessions');
60
94
 
61
- // Call logout endpoint
62
- fetch(`${authBaseUrl}/logout/${clientKey}`, {
63
- method: 'POST',
64
- credentials: 'include',
65
- headers: {
66
- 'Authorization': `Bearer ${token}`
95
+ if (token) {
96
+ try {
97
+ const response = await fetch(`${authBaseUrl}/logout/${clientKey}`, {
98
+ method: 'POST',
99
+ credentials: 'include',
100
+ headers: {
101
+ 'Authorization': `Bearer ${token}`,
102
+ 'Content-Type': 'application/json'
103
+ }
104
+ });
105
+
106
+ const data = await response.json();
107
+ console.log('Backend logout response:', data);
108
+
109
+ if (data.keycloakLogoutUrl) {
110
+ window.location.href = data.keycloakLogoutUrl;
111
+ return;
112
+ }
113
+ } catch (error) {
114
+ console.warn('Backend logout failed:', error);
67
115
  }
68
- }).catch(console.error);
116
+ }
117
+
118
+ // Fallback: redirect to login
119
+ window.location.href = '/login';
120
+ }
69
121
 
70
- // Redirect to Account UI logout page
71
- window.location.href = `${accountUiUrl}/logout?client=${clientKey}`;
122
+ // Client logout
123
+ function clientLogout(clientKey, accountUiUrl) {
124
+ console.log('🔄 Client Logout: Redirecting to centralized login');
125
+ const logoutUrl = `${accountUiUrl}/login?client=${clientKey}&logout=true`;
126
+ window.location.href = logoutUrl;
72
127
  }
73
128
 
74
129
  export function handleCallback() {
75
130
  const params = new URLSearchParams(window.location.search);
76
131
  const accessToken = params.get('access_token');
77
132
  const error = params.get('error');
78
- // Removed state handling completely
79
133
 
80
- console.log('Handling authentication callback:', {
81
- accessToken,
134
+ console.log('🔄 Handling authentication callback:', {
135
+ mode: isRouterMode() ? 'ROUTER' : 'CLIENT',
136
+ hasAccessToken: !!accessToken,
82
137
  error
83
- // Removed state from logging
84
138
  });
85
-
86
- // Removed all state validation
87
139
 
88
140
  sessionStorage.removeItem('originalApp');
89
141
  sessionStorage.removeItem('returnUrl');
@@ -103,6 +155,8 @@ export function handleCallback() {
103
155
  export async function refreshToken() {
104
156
  const { clientKey, authBaseUrl } = getConfig();
105
157
 
158
+ console.log('🔄 Refreshing token:', { clientKey, mode: isRouterMode() ? 'ROUTER' : 'CLIENT' });
159
+
106
160
  try {
107
161
  const response = await fetch(`${authBaseUrl}/refresh/${clientKey}`, {
108
162
  method: 'POST',
package/index.js CHANGED
@@ -1,4 +1,5 @@
1
- import { setConfig, getConfig } from './config';
1
+ // auth-client/index.js
2
+ import { setConfig, getConfig, isRouterMode } from './config';
2
3
  import { login, logout, handleCallback, refreshToken } from './core';
3
4
  import { getToken, setToken, clearToken } from './token';
4
5
  import api from './api';
@@ -8,6 +9,7 @@ export const auth = {
8
9
  // 🔧 Config
9
10
  setConfig,
10
11
  getConfig,
12
+ isRouterMode, // ✅ Expose router mode check
11
13
 
12
14
  // 🔐 Core flows
13
15
  login,
@@ -26,23 +28,24 @@ export const auth = {
26
28
  // 🧪 Utilities
27
29
  decodeToken,
28
30
  isTokenExpired,
29
-
31
+
30
32
  // 🔄 Auto-refresh setup
31
33
  startTokenRefresh: () => {
32
34
  const interval = setInterval(async () => {
33
35
  const token = getToken();
34
- if (token && isTokenExpired(token, 300)) { // Refresh 5 min before expiry
36
+ if (token && isTokenExpired(token, 300)) {
35
37
  try {
36
38
  await refreshToken();
39
+ console.log('🔄 Auto-refresh successful');
37
40
  } catch (err) {
38
41
  console.error('Auto-refresh failed:', err);
39
42
  clearInterval(interval);
40
43
  }
41
44
  }
42
- }, 60000); // Check every minute
45
+ }, 60000);
43
46
  return interval;
44
47
  }
45
48
  };
46
49
 
47
50
  export { AuthProvider } from './react/AuthProvider';
48
- export { useAuth } from './react/useAuth';
51
+ export { useAuth } from './react/useAuth';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@spidy092/auth-client",
3
- "version": "1.0.7",
3
+ "version": "1.0.9",
4
4
  "description": "Scalable frontend auth SDK for centralized login using Keycloak + Auth Service.",
5
5
  "main": "index.js",
6
6
  "module": "index.js",