@spidy092/auth-client 1.0.8 → 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 +92 -61
  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,112 +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
+
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
49
+ });
39
50
 
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
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
45
63
  });
46
- console.log('Redirecting to centralized Account UI:', accountLoginUrl);
47
- window.location.href = accountLoginUrl;
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
- console.log('Initiating logout for client:', clientKey);
71
+
72
+ console.log('🚪 Smart Logout initiated:', {
73
+ mode: isRouterMode() ? 'ROUTER' : 'CLIENT',
74
+ clientKey,
75
+ hasToken: !!token
76
+ });
55
77
 
56
78
  // Clear local storage immediately
57
79
  clearToken();
58
80
  sessionStorage.clear();
59
- // Don't clear localStorage completely - might break other stuff
60
- // localStorage.clear(); // Remove this line
61
81
 
62
- // Call backend logout if we have a token
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');
94
+
63
95
  if (token) {
64
- fetch(`${authBaseUrl}/logout/${clientKey}`, {
65
- method: 'POST',
66
- credentials: 'include', // ✅ CRITICAL: This sends cookies
67
- headers: {
68
- 'Authorization': `Bearer ${token}`,
69
- 'Content-Type': 'application/json'
70
- }
71
- })
72
- .then(response => response.json())
73
- .then(data => {
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();
74
107
  console.log('Backend logout response:', data);
75
-
76
- // If we get a Keycloak logout URL, redirect there
108
+
77
109
  if (data.keycloakLogoutUrl) {
78
110
  window.location.href = data.keycloakLogoutUrl;
79
111
  return;
80
112
  }
81
-
82
- // Otherwise redirect to login
83
- window.location.href = `${accountUiUrl}/login`;
84
- })
85
- .catch(error => {
86
- console.error('Logout error:', error);
87
- // Always redirect to login even on error
88
- window.location.href = `${accountUiUrl}/login`;
89
- });
90
- } else {
91
- // No token, just redirect to login
92
- window.location.href = `${accountUiUrl}/login`;
113
+ } catch (error) {
114
+ console.warn('Backend logout failed:', error);
115
+ }
93
116
  }
117
+
118
+ // Fallback: redirect to login
119
+ window.location.href = '/login';
94
120
  }
95
121
 
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;
127
+ }
96
128
 
97
129
  export function handleCallback() {
98
130
  const params = new URLSearchParams(window.location.search);
99
131
  const accessToken = params.get('access_token');
100
132
  const error = params.get('error');
101
- // Removed state handling completely
102
133
 
103
- console.log('Handling authentication callback:', {
104
- accessToken,
134
+ console.log('🔄 Handling authentication callback:', {
135
+ mode: isRouterMode() ? 'ROUTER' : 'CLIENT',
136
+ hasAccessToken: !!accessToken,
105
137
  error
106
- // Removed state from logging
107
138
  });
108
-
109
- // Removed all state validation
110
139
 
111
140
  sessionStorage.removeItem('originalApp');
112
141
  sessionStorage.removeItem('returnUrl');
@@ -126,6 +155,8 @@ export function handleCallback() {
126
155
  export async function refreshToken() {
127
156
  const { clientKey, authBaseUrl } = getConfig();
128
157
 
158
+ console.log('🔄 Refreshing token:', { clientKey, mode: isRouterMode() ? 'ROUTER' : 'CLIENT' });
159
+
129
160
  try {
130
161
  const response = await fetch(`${authBaseUrl}/refresh/${clientKey}`, {
131
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.8",
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",