|
| 1 | +/* Provide functionality for authentication buttons */ |
| 2 | + |
| 3 | +(({ auth }) => { |
| 4 | + // Wire up DOM elements |
| 5 | + const [loginButton, logoutButton, registerButton, accountSettings] = |
| 6 | + ['login', 'logout', 'register', 'accountSettings'].map(id => |
| 7 | + document.getElementById(id) || document.createElement('a')) |
| 8 | + loginButton.addEventListener('click', login) |
| 9 | + logoutButton.addEventListener('click', logout) |
| 10 | + registerButton.addEventListener('click', register) |
| 11 | + |
| 12 | + // Track authentication status and update UI |
| 13 | + auth.trackSession(session => { |
| 14 | + const loggedIn = !!session |
| 15 | + const isOwner = loggedIn && new URL(session.webId).origin === location.origin |
| 16 | + loginButton.classList.toggle('hidden', loggedIn) |
| 17 | + logoutButton.classList.toggle('hidden', !loggedIn) |
| 18 | + accountSettings.classList.toggle('hidden', !isOwner) |
| 19 | + }) |
| 20 | + |
| 21 | + // Log the user in on the client and the server |
| 22 | + async function login () { |
| 23 | + const session = await auth.popupLogin() |
| 24 | + if (session) { |
| 25 | + // Make authenticated request to the server to establish a session cookie |
| 26 | + const {status} = await auth.fetch(location, { method: 'HEAD' }) |
| 27 | + if (status === 401) { |
| 28 | + alert(`Invalid login.\n\nDid you set ${session.idp} as your OIDC provider in your profile ${session.webId}?`) |
| 29 | + await auth.logout() |
| 30 | + } |
| 31 | + // Now that we have a cookie, reload to display the authenticated page |
| 32 | + location.reload() |
| 33 | + } |
| 34 | + } |
| 35 | + |
| 36 | + // Log the user out from the client and the server |
| 37 | + async function logout () { |
| 38 | + await auth.logout() |
| 39 | + location.reload() |
| 40 | + } |
| 41 | + |
| 42 | + // Redirect to the registration page |
| 43 | + function register () { |
| 44 | + const registration = new URL('/register', location) |
| 45 | + registration.searchParams.set('returnToUrl', location) |
| 46 | + location.href = registration |
| 47 | + } |
| 48 | +})(solid) |
0 commit comments