-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
207 lines (186 loc) · 6.23 KB
/
app.js
File metadata and controls
207 lines (186 loc) · 6.23 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
import { createAuth0Client } from '@auth0/auth0-spa-js';
// DOM elements
const loading = document.getElementById('loading');
const error = document.getElementById('error');
const errorDetails = document.getElementById('error-details');
const app = document.getElementById('app');
const loggedOutSection = document.getElementById('logged-out');
const loggedInSection = document.getElementById('logged-in');
const loginBtn = document.getElementById('login-btn');
const logoutBtn = document.getElementById('logout-btn');
const callApiBtn = document.getElementById('call-api-btn');
const apiOutput = document.getElementById('api-output');
const profileContainer = document.getElementById('profile');
let auth0Client;
// Initialize Auth0 client
async function initAuth0() {
try {
// Validate environment variables
const domain = import.meta.env.VITE_AUTH0_DOMAIN;
const clientId = import.meta.env.VITE_AUTH0_CLIENT_ID;
if (!domain || !clientId) {
throw new Error('Auth0 configuration missing. Please check your .env.local file for VITE_AUTH0_DOMAIN and VITE_AUTH0_CLIENT_ID');
}
auth0Client = await createAuth0Client({
domain: domain,
clientId: clientId,
authorizationParams: {
redirect_uri: window.location.origin
}
});
// Check if user is returning from login
if (window.location.search.includes('code=') && window.location.search.includes('state=')) {
await handleRedirectCallback();
}
// Update UI based on authentication state
await updateUI();
} catch (err) {
console.error('Auth0 initialization error:', err);
showError(err.message);
}
}
// Handle redirect callback
async function handleRedirectCallback() {
try {
await auth0Client.handleRedirectCallback();
// Clean up the URL to remove query parameters
window.history.replaceState({}, document.title, window.location.pathname);
} catch (err) {
console.error('Redirect callback error:', err);
showError(err.message);
}
}
// Update UI based on authentication state
async function updateUI() {
try {
const isAuthenticated = await auth0Client.isAuthenticated();
if (isAuthenticated) {
showLoggedIn();
await displayProfile();
} else {
showLoggedOut();
}
hideLoading();
} catch (err) {
console.error('UI update error:', err);
showError(err.message);
}
}
// Display user profile
async function displayProfile() {
try {
const user = await auth0Client.getUser();
const placeholderImage = `data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='110' height='110' viewBox='0 0 110 110'%3E%3Ccircle cx='55' cy='55' r='55' fill='%2363b3ed'/%3E%3Cpath d='M55 50c8.28 0 15-6.72 15-15s-6.72-15-15-15-15 6.72-15 15 6.72 15 15 15zm0 7.5c-10 0-30 5.02-30 15v3.75c0 2.07 1.68 3.75 3.75 3.75h52.5c2.07 0 3.75-1.68 3.75-3.75V72.5c0-9.98-20-15-30-15z' fill='%23fff'/%3E%3C/svg%3E`;
profileContainer.innerHTML = `
<div style="display: flex; flex-direction: column; align-items: center; gap: 1rem;">
<img
src="${user.picture || placeholderImage}"
alt="${user.name || 'User'}"
class="profile-picture"
style="
width: 110px;
height: 110px;
border-radius: 50%;
object-fit: cover;
border: 3px solid #63b3ed;
"
onerror="this.src='${placeholderImage}'"
/>
<div style="text-align: center;">
<div class="profile-name" style="font-size: 2rem; font-weight: 600; color: #f7fafc; margin-bottom: 0.5rem;">
${user.name || 'User'}
</div>
<div class="profile-email" style="font-size: 1.15rem; color: #a0aec0;">
${user.email || 'No email provided'}
</div>
</div>
</div>
`;
} catch (err) {
console.error('Error displaying profile:', err);
}
}
// Retrieve Access Token and call API (MOCKED)
async function callProtectedApi() {
apiOutput.textContent = 'Calling API...';
try {
// 1. Get the Access Token silently
const token = await auth0Client.getTokenSilently({
authorizationParams: {
// NOTE: Since you don't have a real API endpoint,
// we use a placeholder audience and scope for demonstration.
audience: 'https://my-protected-api',
scope: 'read:data'
}
});
// 2. MOCK the API call (Replace this with a real fetch to your API)
const response = await new Promise(resolve => setTimeout(() => {
resolve({
status: 200,
json: async () => ({
message: "Protected data successfully retrieved!",
user_id: (await auth0Client.getUser()).sub,
token_type: "Bearer",
token_length: token.length
})
});
}, 1500)); // Simulate network latency
const data = await response.json();
// 3. Display the result
apiOutput.textContent = JSON.stringify(data, null, 2);
} catch (error) {
console.error('Error calling protected API:', error);
apiOutput.textContent = `Error: ${error.message}`;
}
}
// Event handlers
async function login() {
try {
await auth0Client.loginWithRedirect();
} catch (err) {
console.error('Login error:', err);
showError(err.message);
}
}
async function logout() {
try {
await auth0Client.logout({
logoutParams: {
returnTo: window.location.origin
}
});
} catch (err) {
console.error('Logout error:', err);
showError(err.message);
}
}
// UI state management
function showLoading() {
loading.style.display = 'block';
error.style.display = 'none';
app.style.display = 'none';
}
function hideLoading() {
loading.style.display = 'none';
app.style.display = 'flex';
}
function showError(message) {
loading.style.display = 'none';
app.style.display = 'none';
error.style.display = 'block';
errorDetails.textContent = message;
}
function showLoggedIn() {
loggedOutSection.style.display = 'none';
loggedInSection.style.display = 'flex';
}
function showLoggedOut() {
loggedInSection.style.display = 'none';
loggedOutSection.style.display = 'flex';
}
// Event listeners
loginBtn.addEventListener('click', login);
logoutBtn.addEventListener('click', logout);
callApiBtn.addEventListener('click', callProtectedApi);
// Initialize the app
initAuth0();