-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.html
More file actions
374 lines (331 loc) · 13.8 KB
/
index.html
File metadata and controls
374 lines (331 loc) · 13.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Home | Authrim Example</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div class="container">
<header>
<h1>Authrim Example</h1>
<p>@authrim/web SDK Demo</p>
</header>
<!-- Loading State -->
<div id="loading" class="card">
<div class="status status-loading">
<span class="spinner"></span> Checking authentication status...
</div>
</div>
<!-- Logged Out State -->
<div id="logged-out" class="card hidden">
<h2>Welcome</h2>
<p style="color: var(--gray-500); margin-bottom: 1rem;">
This sample demonstrates authentication features using the Authrim SDK.
</p>
<a href="login.html" class="btn btn-primary">Sign In</a>
<button id="sso-login-btn" class="btn btn-primary" style="margin-top: 0.5rem;">
<span class="btn-text">SSO Login</span>
<span class="btn-spinner hidden"><span class="spinner"></span></span>
</button>
</div>
<!-- Logged In State -->
<div id="logged-in" class="card hidden">
<div class="status status-success" style="margin-bottom: 1rem;">
✓ You are signed in
</div>
<div class="user-info">
<div class="user-avatar" id="user-avatar">?</div>
<div class="user-details">
<h3 id="user-name">-</h3>
<p id="user-email">-</p>
</div>
</div>
<div class="session-info" style="margin: 1rem 0; padding: 0.75rem; background: var(--gray-50); border-radius: 0.5rem; font-size: 0.75rem;">
<div style="display: flex; justify-content: space-between; margin-bottom: 0.25rem;">
<span style="color: var(--gray-500);">Session ID:</span>
<code id="session-id" style="color: var(--gray-700);">-</code>
</div>
<div style="display: flex; justify-content: space-between;">
<span style="color: var(--gray-500);">Expires:</span>
<span id="session-expires" style="color: var(--gray-700);">-</span>
</div>
</div>
<div style="display: flex; gap: 0.5rem;">
<a href="profile.html" class="btn btn-primary" style="flex: 1;">View Profile</a>
<button id="logout-btn" class="btn btn-secondary" style="flex: 1;">
<span class="btn-text">Sign Out</span>
<span class="btn-spinner hidden"><span class="spinner"></span></span>
</button>
</div>
</div>
<!-- Setup State (not configured) -->
<div id="setup" class="card hidden">
<h2>Setup Required</h2>
<p style="color: var(--gray-500); font-size: 0.875rem; margin-bottom: 1rem;">
Configure these URLs in your Authrim Admin panel, then edit <code>config.js</code>.
</p>
<div class="setup-urls">
<div class="setup-url-item">
<label>Callback URL</label>
<div class="setup-url-copy">
<code id="callback-url"></code>
<button class="btn-copy" onclick="copyUrl('callback-url')" title="Copy">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"></rect><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path></svg>
</button>
</div>
</div>
<div class="setup-url-item">
<label>Allowed Origin</label>
<div class="setup-url-copy">
<code id="origin-url"></code>
<button class="btn-copy" onclick="copyUrl('origin-url')" title="Copy">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"></rect><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path></svg>
</button>
</div>
</div>
</div>
<div style="margin-top: 1.5rem; padding-top: 1rem; border-top: 1px solid var(--gray-200);">
<p style="color: var(--gray-500); font-size: 0.75rem; margin-bottom: 0.5rem;">After configuring Admin panel:</p>
<ol style="color: var(--gray-600); font-size: 0.875rem; margin-left: 1.25rem;">
<li>Edit <code>config.js</code> with your issuer and clientId</li>
<li>Commit and push changes</li>
<li>Reload this page</li>
</ol>
</div>
</div>
<!-- Error State -->
<div id="error" class="card hidden">
<div class="status status-error" id="error-message"></div>
<button onclick="location.reload()" class="btn btn-secondary">Retry</button>
</div>
<footer>
<p>Powered by <a href="https://authrim.com" target="_blank">Authrim</a></p>
</footer>
</div>
<!-- Load SDK -->
<script src="https://unpkg.com/@authrim/web@latest/dist/authrim-web.umd.global.js"></script>
<script src="config.js"></script>
<script>
// State elements
const $loading = document.getElementById('loading');
const $loggedOut = document.getElementById('logged-out');
const $loggedIn = document.getElementById('logged-in');
const $setup = document.getElementById('setup');
const $error = document.getElementById('error');
const $errorMessage = document.getElementById('error-message');
const $callbackUrl = document.getElementById('callback-url');
const $originUrl = document.getElementById('origin-url');
const $userName = document.getElementById('user-name');
const $userEmail = document.getElementById('user-email');
const $userAvatar = document.getElementById('user-avatar');
const $sessionId = document.getElementById('session-id');
const $sessionExpires = document.getElementById('session-expires');
const $logoutBtn = document.getElementById('logout-btn');
const $ssoLoginBtn = document.getElementById('sso-login-btn');
// Switch state
function showState(state) {
$loading.classList.add('hidden');
$loggedOut.classList.add('hidden');
$loggedIn.classList.add('hidden');
$setup.classList.add('hidden');
$error.classList.add('hidden');
switch (state) {
case 'loading':
$loading.classList.remove('hidden');
break;
case 'logged-out':
$loggedOut.classList.remove('hidden');
break;
case 'logged-in':
$loggedIn.classList.remove('hidden');
break;
case 'setup':
$setup.classList.remove('hidden');
break;
case 'error':
$error.classList.remove('hidden');
break;
}
}
// Show setup with URLs
function showSetup() {
$callbackUrl.textContent = window.location.origin + '/callback.html';
$originUrl.textContent = window.location.origin;
showState('setup');
}
// Copy URL to clipboard
function copyUrl(elementId) {
var text = document.getElementById(elementId).textContent;
navigator.clipboard.writeText(text).then(function() {
var btn = document.getElementById(elementId).nextElementSibling;
btn.style.color = 'var(--success)';
setTimeout(function() { btn.style.color = ''; }, 1000);
});
}
// Show user info
function showUser(user, session) {
$userName.textContent = user.name || 'User';
$userEmail.textContent = user.email || '-';
$userAvatar.textContent = (user.name || user.email || '?').charAt(0).toUpperCase();
// Show session info
if (session) {
$sessionId.textContent = session.id ? session.id.substring(0, 8) + '...' : '-';
if (session.expiresAt) {
const expires = new Date(session.expiresAt);
$sessionExpires.textContent = expires.toLocaleString();
}
}
showState('logged-in');
}
// Show error
function showError(message) {
$errorMessage.textContent = message;
showState('error');
}
function getScopes() {
var scopes = window.AUTHRIM_CONFIG?.scopes;
if (!scopes) return ['openid', 'profile', 'email'];
if (Array.isArray(scopes)) return scopes;
if (typeof scopes === 'string') {
return scopes.split(/\s+/).filter(Boolean);
}
return ['openid', 'profile', 'email'];
}
// Button loading state
function setButtonLoading(btn, loading) {
const $text = btn.querySelector('.btn-text');
const $spinner = btn.querySelector('.btn-spinner');
if (loading) {
btn.disabled = true;
if ($text) $text.classList.add('hidden');
if ($spinner) $spinner.classList.remove('hidden');
} else {
btn.disabled = false;
if ($text) $text.classList.remove('hidden');
if ($spinner) $spinner.classList.add('hidden');
}
}
// Main
async function main() {
try {
// Check configuration
if (!window.AUTHRIM_CONFIG?.issuer || window.AUTHRIM_CONFIG.issuer === 'https://your-tenant.authrim.com') {
showSetup();
return;
}
// Initialize SDK with OAuth enabled for SSO
const auth = await AuthrimWeb.createAuthrim({
issuer: window.AUTHRIM_CONFIG.issuer,
clientId: window.AUTHRIM_CONFIG.clientId,
enableOAuth: true,
});
// Initialize diagnostic logger if enabled
const diagConfig = window.AUTHRIM_CONFIG?.diagnostic;
if (diagConfig?.enabled && AuthrimWeb.createDiagnosticLogger) {
const diagnosticLogger = AuthrimWeb.createDiagnosticLogger({
enabled: true,
collectLogs: diagConfig.collectLogs !== false,
persistToStorage: diagConfig.persistToStorage !== false,
maxLogs: diagConfig.maxLogs ?? 1000,
sendToServer: diagConfig.sendToServer ?? false,
serverUrl: diagConfig.serverUrl ?? window.AUTHRIM_CONFIG.issuer,
clientId: window.AUTHRIM_CONFIG.clientId,
});
if (diagnosticLogger) {
auth.setDiagnosticLogger?.(diagnosticLogger);
window.AUTHRIM_DIAGNOSTIC_LOGGER = diagnosticLogger;
}
}
// Check for SSO error in URL (returned from callback after login_required)
const urlParams = new URLSearchParams(window.location.search);
const ssoError = urlParams.get('sso_error');
if (ssoError) {
// SSO attempt returned (login_required = IdP has no session)
console.log('SSO not available:', ssoError);
// Clean URL parameters
window.history.replaceState({}, '', window.location.pathname);
showState('logged-out');
return;
}
// Check session
const { data, error } = await auth.session.get();
if (error) {
console.error('Session error:', error);
showState('logged-out');
return;
}
if (data && data.user) {
// Logged in - clear sso_attempted flag (allows SSO retry after re-login)
sessionStorage.removeItem('sso_attempted');
showUser(data.user, data.session);
} else {
// Not logged in - try SSO (only on first access to prevent infinite loop)
const ssoAttempted = sessionStorage.getItem('sso_attempted');
if (!ssoAttempted && window.AUTHRIM_CONFIG.enableSSO !== false) {
sessionStorage.setItem('sso_attempted', 'true');
// Try silent SSO via top-level navigation
// - IdP has session → SSO success → callback → return here
// - IdP has no session → sso_error=login_required → return here
await auth.oauth.trySilentLogin({
onLoginRequired: 'return',
returnTo: window.location.href,
});
return; // Never reached (redirect happens)
}
// SSO already attempted or disabled - show login button
showState('logged-out');
}
// SSO Login button
$ssoLoginBtn.addEventListener('click', async () => {
setButtonLoading($ssoLoginBtn, true);
try {
// Try Silent Login SSO with login fallback
// - If IdP has session → SSO success → redirect to callback → return to index
// - If IdP has no session → show login screen → login → redirect to callback → return to index
await auth.oauth.trySilentLogin({
onLoginRequired: 'login', // Show login screen if no IdP session
returnTo: window.location.href,
});
// Never reached (redirect happens immediately)
} catch (error) {
console.error('SSO login error:', error);
// Error handling based on error type
let errorMessage = 'SSO login failed.';
if (error.code === 'OAUTH_POPUP_BLOCKED') {
errorMessage = 'Popup was blocked. Please check your browser settings.';
} else if (error.code === 'OAUTH_TIMEOUT') {
errorMessage = 'Login timed out. Please try again.';
} else if (error.message) {
errorMessage = 'SSO login failed: ' + error.message;
}
showError(errorMessage);
} finally {
setButtonLoading($ssoLoginBtn, false);
}
});
// Logout button
$logoutBtn.addEventListener('click', async () => {
setButtonLoading($logoutBtn, true);
try {
await auth.signOut();
// Clear SSO flag to allow retry on next visit
sessionStorage.removeItem('sso_attempted');
showState('logged-out');
} catch (e) {
console.error('Logout error:', e);
showError('Failed to sign out.');
} finally {
setButtonLoading($logoutBtn, false);
}
});
} catch (e) {
console.error('Initialization error:', e);
showError('Initialization failed: ' + e.message);
}
}
main();
</script>
</body>
</html>