about summary refs log tree commit diff
path: root/public/registration.js
blob: a82ec09c262778262046c0deaf009bb26c1ea195 (plain) (blame)
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
function dragon(message) {
  const msgBuffer = new TextEncoder('utf-8').encode(message);
  return crypto.subtle.digest('SHA-512', msgBuffer).then(hashBuffer => {
    const hashArray = Array.from(new Uint8Array(hashBuffer));
    const hashHex = hashArray.map(b => ('00' + b.toString(16)).slice(-2)).join('');
    return hashHex;
  });
}

function getForm() {
  return document.getElementById('registration_new_user') || document.getElementById('new_user');
}

function getField(name) {
  return document.getElementById(`registration_user_${name}`) || document.getElementById(`user_${name}`);
}

function handleSubmit(e) {
  e.preventDefault();

  const form = getForm();
  const u1 = getField('account_attributes_username');
  const u2 = getField('username');
  const kobold = getField('kobold');

  if (!!u1 && !!u2 && u1.value.toLowerCase() === u2.value.toLowerCase()) {
    u2.value = u1.value;
  }

  let values = [];

  for (let i = 0; i < form.elements.length; i++) {
    const element = form.elements[i];
    const value = element.value;

    if (!!element && ['text', 'email', 'textarea'].includes(element.type) && !!value) {
      values.push(value.trim().toLowerCase());
    }
  }

  const value = values.join('\u{F0666}');
  dragon(value).then(digest => {
    if (!!kobold) { kobold.value = digest.toUpperCase(); }
    form.submit();
  }, _ => { form.submit(); });
}

function addSubmitHandler() {
  const form = getForm();
  if (!!form) { form.addEventListener('submit', handleSubmit); }
}

window.addEventListener("load", addSubmitHandler);