48 lines
1.4 KiB
JavaScript
48 lines
1.4 KiB
JavaScript
export function setupAuthPanel(root, socket, onLogin) {
|
|
root.innerHTML = `
|
|
<div class="panel hidden">
|
|
<h2>Medieval 2D</h2>
|
|
<div class="row"><input id="auth-user" placeholder="Character name" /></div>
|
|
<div class="row"><input id="auth-pass" type="password" placeholder="Password" /></div>
|
|
<div class="row">
|
|
<button id="auth-register">Register</button>
|
|
<button id="auth-login">Login</button>
|
|
</div>
|
|
<p id="auth-msg"></p>
|
|
</div>
|
|
`;
|
|
const panel = root.firstElementChild;
|
|
const user = panel.querySelector('#auth-user');
|
|
const pass = panel.querySelector('#auth-pass');
|
|
const msg = panel.querySelector('#auth-msg');
|
|
|
|
async function call(path) {
|
|
const res = await fetch(path, {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ username: user.value, password: pass.value })
|
|
});
|
|
return res;
|
|
}
|
|
|
|
panel.querySelector('#auth-register').onclick = async () => {
|
|
const r = await call('/api/register');
|
|
if (r.ok) {
|
|
panel.classList.add('hidden');
|
|
onLogin();
|
|
} else {
|
|
msg.textContent = 'Username taken.';
|
|
}
|
|
};
|
|
|
|
panel.querySelector('#auth-login').onclick = async () => {
|
|
const r = await call('/api/login');
|
|
if (r.ok) {
|
|
panel.classList.add('hidden');
|
|
onLogin();
|
|
} else {
|
|
msg.textContent = 'Invalid login.';
|
|
}
|
|
};
|
|
}
|