// Generated by CoffeeScript 1.12.8

/*
LemonLDAP::NG WebAuthn registration script
 */

(function() {
  var displayError, register, setMsg, verify, webAuthnError;

  setMsg = function(msg, level) {
    $('#msg').attr('trspan', msg);
    $('#msg').html(window.translate(msg));
    $('#color').removeClass('message-positive message-warning message-danger alert-success alert-warning alert-danger');
    $('#color').addClass("message-" + level);
    if (level === 'positive') {
      level = 'success';
    }
    return $('#color').addClass("alert-" + level);
  };

  displayError = function(j, status, err) {
    var res;
    console.log('Error', err);
    res = JSON.parse(j.responseText);
    if (res && res.error) {
      res = res.error.replace(/.* /, '');
      console.log('Returned error', res);
      return setMsg(res, 'danger');
    }
  };

  webAuthnError = function(error) {
    switch (error.name) {
      case 'unsupported':
        return setMsg('webAuthnUnsupported', 'warning');
      default:
        return setMsg('webAuthnBrowserFailed', 'danger');
    }
  };

  register = function() {
    return $.ajax({
      type: "POST",
      url: portal + "2fregisters/webauthn/registrationchallenge",
      data: {},
      dataType: 'json',
      error: displayError,
      success: function(ch) {
        var request;
        request = ch.request;
        setMsg('webAuthnRegisterInProgress', 'warning');
        $('#u2fPermission').show();
        return WebAuthnUI.WebAuthnUI.createCredential(request).then(function(response) {
          return $.ajax({
            type: "POST",
            url: portal + "2fregisters/webauthn/registration",
            data: {
              state_id: ch.state_id,
              credential: JSON.stringify(response),
              keyName: $('#keyName').val()
            },
            dataType: 'json',
            success: function(resp) {
              if (resp.error) {
                if (resp.error.match(/badName/)) {
                  return setMsg(resp.error, 'danger');
                } else {
                  return setMsg('webAuthnRegisterFailed', 'danger');
                }
              } else if (resp.result) {
                $(document).trigger("mfaAdded", [
                  {
                    "type": "webauthn"
                  }
                ]);
                return setMsg('yourKeyIsRegistered', 'positive');
              }
            },
            error: displayError
          });
        })["catch"](function(error) {
          return webAuthnError(error);
        });
      }
    });
  };

  verify = function() {
    return $.ajax({
      type: "POST",
      url: portal + "2fregisters/webauthn/verificationchallenge",
      data: {},
      dataType: 'json',
      error: displayError,
      success: function(ch) {
        var request;
        request = ch.request;
        setMsg('webAuthnBrowserInProgress', 'warning');
        return WebAuthnUI.WebAuthnUI.getCredential(request).then(function(response) {
          return $.ajax({
            type: "POST",
            url: portal + "2fregisters/webauthn/verification",
            data: {
              state_id: ch.state_id,
              credential: JSON.stringify(response)
            },
            dataType: 'json',
            success: function(resp) {
              if (resp.error) {
                return setMsg('webAuthnFailed', 'danger');
              } else if (resp.result) {
                return setMsg('yourKeyIsVerified', 'positive');
              }
            },
            error: displayError
          });
        })["catch"](function(error) {
          return webAuthnError(error);
        });
      }
    });
  };

  $(document).ready(function() {
    $('#u2fPermission').hide();
    $('#register').on('click', register);
    $('#verify').on('click', verify);
    return $('#goback').attr('href', portal);
  });

}).call(this);
