// 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 e, request;
        request = ch.request;
        e = jQuery.Event("webauthnRegistrationAttempt");
        $(document).trigger(e);
        if (!e.isDefaultPrevented()) {
          setMsg('webAuthnRegisterInProgress', 'warning');
          $('#u2fPermission').show();
          return WebAuthnUI.WebAuthnUI.createCredential(request).then(function(response) {
            e = jQuery.Event("webauthnRegistrationSuccess");
            $(document).trigger(e, [response]);
            if (!e.isDefaultPrevented()) {
              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) {
                    e = jQuery.Event("mfaAdded");
                    $(document).trigger(e, [
                      {
                        "type": "webauthn"
                      }
                    ]);
                    if (!e.isDefaultPrevented()) {
                      return window.location.href = window.portal + "2fregisters?continue=1";
                    }
                  }
                },
                error: displayError
              });
            }
          }, function(error) {
            e = jQuery.Event("webauthnRegistrationFailure");
            $(document).trigger(e, [error]);
            if (!e.isDefaultPrevented()) {
              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);
    setTimeout(register, 1000);
    $('#retrybutton').on('click', register);
    return $('#goback').attr('href', portal);
  });

}).call(this);
