-
Notifications
You must be signed in to change notification settings - Fork 0
/
supaauth.js
69 lines (63 loc) · 2.63 KB
/
supaauth.js
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
// DOM elements
const contentForm = document.getElementById('content-form');
const authForm = document.getElementById('auth-form');
const messageDiv = document.getElementById('message');
// Check authentication status
async function checkAuth() {
const token = localStorage.getItem('authToken');
if (token) {
try {
const response = await fetch('/api/auth', {
method: 'GET',
headers: {
'Authorization': `Bearer ${token}`
}
});
if (response.ok) {
contentForm.classList.remove('hidden');
authForm.classList.add('hidden');
return;
}
} catch (error) {
console.error('Auth check failed:', error);
}
}
// If we get here, user is not authenticated
contentForm.classList.add('hidden');
authForm.classList.remove('hidden');
localStorage.removeItem('authToken');
}
// Handle auth form submission
authForm.addEventListener('submit', async (e) => {
e.preventDefault();
const email = document.getElementById('email').value;
try {
const response = await fetch('/api/auth', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email })
});
const data = await response.json();
if (!response.ok) throw new Error(data.error);
showMessage('Check your email for the login link!', 'success');
} catch (error) {
showMessage(error.message, 'error');
}
});
// Helper function to show messages
function showMessage(message, type) {
messageDiv.textContent = message;
messageDiv.className = type;
}
// Initial auth check
checkAuth();
// Listen for successful auth redirect
window.addEventListener('load', async () => {
const hashParams = new URLSearchParams(window.location.hash.slice(1));
const accessToken = hashParams.get('access_token');
if (accessToken) {
localStorage.setItem('authToken', accessToken);
await checkAuth();
window.history.replaceState(null, '', window.location.pathname);
}
});