{% load backend_utils %}
<!doctype html>
<html>
  <head>
    <title>Python Social Auth</title>
    <link href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet">
    <link href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap-theme.min.css" rel="stylesheet">
    <link href="//netdna.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet">
    <style>
      h1 { padding: 0 30px; }
      .col-md-2 { width: 18.6667%; }
      .buttons { display: block; table-layout: fixed; border-radius: 7px; border: 1px solid #ccc;
                 margin: 20px; background: #eee; padding: 30px; }
      .buttons > div .btn { margin: 5px 10px; }
      .buttons > div:not(:first-child) { margin-top: 10px; border-top: 1px solid #ccc;
                                         padding-top: 10px; text-align: center; }
      .user-details { text-align: center; font-size: 16px; font-weight: bold; }
      .disconnect-form { padding: 0; margin: 0px 10px; }
      .disconnect-form > a { display: block; margin: 5px 0 !important; }
    </style>
  </head>
  <body>
    <h1>Python Social Auth</h1>

    <div class="buttons">
      {% if user.is_authenticated %}
        <div class="user-details">
          You are logged in as <code>{{ user.username }}</code>!
        </div>
      {% endif %}

      <div class="social">
        {% for sublist in available_backends|social_backends %}
          <div class="row">
            {% for name, backend in sublist %}
              {% associated backend %}
              {% if association %}
                <form class="disconnect-form col-md-2" id="{{ name }}-disconnect" action="{% url "social:disconnect_individual" backend=association.provider association_id=association.id %}" method="post">{% csrf_token %}
                  <a class="btn btn-danger" name="{{ backend|backend_class }}" href="#">
                    <i class="fa fa-{{ name|icon_name }}"></i>
                    Disconnect {{ backend|backend_name }}
                  </a>
                </form>
              {% else %}
                {% if name == "google-plus" %}
                  <div class="col-md-2 btn btn-default" id="{{ name }}-button" name="{{ backend|backend_class }}">
                    <i class="fa fa-{{ name|icon_name }}"></i>
                    {{ backend|backend_name }}
                  </div>
                {% else %}
                  <a class="col-md-2 btn btn-default" id="{{ name }}-button" name="{{ backend|backend_class }}" href="{% url "social:begin" backend=name %}">
                    <i class="fa fa-{{ name|icon_name }}"></i>
                    {{ backend|backend_name }}
                  </a>
                {% endif %}
              {% endif %}
            {% endfor %}
          </div>
        {% endfor %}
      </div>

      <div class="legacy">
        {% for name, backend in available_backends|legacy_backends %}
          {% associated backend %}
          {% if association %}
            <form class="disconnect-form" action="{% url "social:disconnect_individual" backend=association.provider association_id=association.id %}" method="post">{% csrf_token %}
              <a class="btn btn-danger" name="{{ backend|backend_class }}" href="#">
                <i class="fa fa-{{ name|icon_name }}"></i>
                Disconnect {{ backend|backend_name }}
              </a>
            </form>
          {% else %}
            <a class="btn btn-default" name="{{ backend|backend_class }}" href="{% url "social:begin" backend=name %}">
              <i class="fa fa-{{ name|icon_name }}"></i>
              {{ backend|backend_name }}
            </a>
          {% endif %}
        {% endfor %}

        <a class="btn btn-info" name="ajax-login" href="#">
          <i class="fa fa-refresh"></i>
          Ajax
        </a>
      </div>

      <div>
        <a class="btn btn-primary" href="/logout/" id="logout">
          <i class="fa fa-sign-out"></i>
          Logout
        </a>
      </div>
    </div>

    <div id="username-modal" class="modal fade">
      <form action="{% url "social:complete" "username" %}" method="post" role="form">{% csrf_token %}
        <div class="modal-dialog">
          <div class="modal-content">
            <div class="modal-header">
              <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
              <h4 class="modal-title">Email Authentication</h4>
            </div>

            <div class="modal-body">
              <div class="form-group">
                <label class="control-label" for="username">Username:</label>
                <input class="form-control" id="username" type="text" name="username" value="" />
              </div>

              <div class="form-group">
                <label class="control-label" for="password">Password:</label>
                <input class="form-control" id="password" type="password" name="password" value="" />
              </div>

              <div class="form-group">
                <label class="control-label" for="fullname">Full name:</label>
                <input class="form-control" id="fullname" type="text" name="fullname" value="" />
              </div>
            </div>

            <div class="modal-footer">
              <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
              <button type="button" class="btn btn-primary">Login</button>
            </div>
          </div>
        </div>
      </form>
    </div>

    <div id="email-modal" class="modal fade">
      <form action="{% url "social:complete" "email" %}" method="post" role="form">{% csrf_token %}
        <div class="modal-dialog">
          <div class="modal-content">
            <div class="modal-header">
              <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
              <h4 class="modal-title">Email Authentication</h4>
            </div>

            <div class="modal-body">
              <div class="form-group">
                <label class="control-label" for="email">Email address:</label>
                <input class="form-control" id="email" type="email" name="email" value="" />
              </div>

              <div class="form-group">
                <label class="control-label" for="password">Password:</label>
                <input class="form-control" id="password" type="password" name="password" value="" />
              </div>

              <div class="form-group">
                <label class="control-label" for="fullname">Full name:</label>
                <input class="form-control" id="fullname" type="text" name="fullname" value="" />
              </div>
            </div>

            <div class="modal-footer">
              <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
              <button type="button" class="btn btn-primary">Login</button>
            </div>
          </div>
        </div>
      </form>
    </div>

    <div id="livejournal-modal" class="modal fade">
      <form action="{% url "social:begin" "livejournal" %}" method="post" role="form">{% csrf_token %}
        <div class="modal-dialog">
          <div class="modal-content">
            <div class="modal-header">
              <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
              <h4 class="modal-title">LiveJournal OpenId Authentication</h4>
            </div>

            <div class="modal-body">
              <div class="form-group">
                <label class="control-label" for="openid_lj_identifier">LiveJournal ID:</label>
                <input class="form-control" id="openid_lj_identifier" type="text" value="" name="openid_lj_user" />
              </div>
            </div>

            <div class="modal-footer">
              <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
              <button type="button" class="btn btn-primary">Login</button>
            </div>
          </div>
        </div>
      </form>
    </div>

    <div id="openid-modal" class="modal fade">
      <form action="{% url "social:begin" backend="openid" %}" method="post" role="form">{% csrf_token %}
        <div class="modal-dialog">
          <div class="modal-content">
            <div class="modal-header">
              <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
              <h4 class="modal-title">Generic OpenId Authentication</h4>
            </div>

            <div class="modal-body">
              <div class="form-group">
                <label class="control-label" for="openid_identifier">OpenId Provider:</label>
                <input class="form-control" id="openid_identifier" type="text" value="" name="openid_identifier" />
              </div>
            </div>

            <div class="modal-footer">
              <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
              <button type="button" class="btn btn-primary">Login</button>
            </div>
          </div>
        </div>
      </form>
    </div>

    <div id="ajax-login-modal" class="modal fade">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
            <h4 class="modal-title">Ajax Authentication by AccessToken</h4>
          </div>

          <div class="modal-body">
            <form action="#" method="post" class="form-horizontal" role="form">{% csrf_token %}
              <div class="form-group">
                <label class="control-label" for="backend">Backend:</label>
                <select class="form-control" name="backend">
                  <option value=""></option>
                  {% for name, backend in available_backends|oauth_backends %}
                    <option value="{{ name }}">{{ backend|backend_name }}</option>
                  {% endfor %}
                </select>
              </div>

              <div class="form-group">
                <label class="control-label" for="access_token">Access token:</label>
                <input class="form-control" id="access_token" name="access_token" type="text" value="" placeholder="OAuth1 or OAuth2 access token">
              </div>

              <div class="form-group">
                <label class="control-label" for="access_token_secret">Access token secret:</label>
                <input class="form-control" id="access_token_secret" name="access_token_secret" type="text" value="" placeholder="OAuth1 access token secret">
              </div>
            </form>

            <div class="login-result" style="display: none;">
              <p><strong>User Id:</strong><span class="user-id"></span></p>
              <p><strong>Username:</strong><span class="user-username"></span></p>
              <p>This page will be reloaded in 10s and the user should be logged in.</p>
            </div>
          </div>

          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            <button type="button" class="btn btn-primary">Login</button>
          </div>
        </div>
      </div>
    </div>

    <div id="persona-modal" class="modal fade">
      <form action="{% url "social:complete" backend="persona" %}" method="post">{% csrf_token %}
        <div class="modal-dialog">
          <div class="modal-content">
            <div class="modal-header">
              <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
              <h4 class="modal-title">Mozilla Persona Authentication</h4>
            </div>

            <div class="modal-body">
              <p>Login with Mozilla Persona by clicking the <code>Login</code> button below.</p>
              <input type="hidden" name="assertion" value="" />
            </div>

            <div class="modal-footer">
              <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
              <button type="button" class="btn btn-primary">Login</button>
            </div>
          </div>
        </div>
      </form>
    </div>

    {% if backend %}
      <div id="email-required-modal" class="modal fade">
        <form action="{% url "social:complete" backend=backend %}" method="post" role="form">{% csrf_token %}
          <div class="modal-dialog">
            <div class="modal-content">
              <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                <h4 class="modal-title">Email required</h4>
              </div>

              <div class="modal-body">
                <p>An email address is required.</p>
                <div class="form-group">
                  <label class="control-label" for="email">Email address:</label>
                  <input class="form-control" id="email" type="email" name="email" value="" />
                </div>
              </div>

              <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary">Continue</button>
              </div>
            </div>
          </div>
        </form>
      </div>
    {% endif %}

    <div id="validation-sent-modal" class="modal fade">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
            <h4 class="modal-title">Email Validation Sent</h4>
          </div>

          <div class="modal-body">
            <p>An email validation was sent{% if email %} to <code>{{ email }}</code>{% endif %}.</p>
            <p>Click the link sent to finish the authentication process.</p>
          </div>

          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
          </div>
        </div>
      </div>
    </div>

    {% if plus_id %}
    <script src="https://apis.google.com/js/api:client.js"></script>
    <script type="text/javascript">
        gapi.load('auth2', function () {
          var auth2;

          auth2 = gapi.auth2.init({
            client_id: "{{ plus_id }}",
            scope: "{{ plus_scope }}"
          });

          auth2.then(function () {
            var button = document.getElementById("google-plus-button");
            console.log("User is signed-in in Google+ platform?", auth2.isSignedIn.get() ? "Yes" : "No");

            if (button) {
              auth2.attachClickHandler(button, {}, function (googleUser) {
                var authResponse = googleUser.getAuthResponse();
                var $form;
                var $input;

                $form = $("<form>");
                $form.attr("action", "{% url "social:complete" backend="google-plus" %}");
                $form.attr("method", "post");
                $input = $("<input>");
                $input.attr("name", "access_token");
                $input.attr("value", authResponse.access_token);
                $form.append($input);
                $form.append("{% csrf_token %}");
                $(document.body).append($form);
                $form.submit();
              });
            } else if (auth2.isSignedIn.get()) {
              $('#logout').on('click', function (event) {
                event.preventDefault();

                auth2.signOut().then(function () {
                  console.log("Logged out from Google+ platform");
                  document.location = $(event.target).attr('href');
                });
              });
            }
          });
        });
    </script>
    {% endif %}

    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
    <script src="https://login.persona.org/include.js" type="text/javascript"></script>

    <script type="text/javascript">
      var modalDialog = function (modalId, modalLinkName, submitHandler) {
        var $modal;

        $modal = $(modalId).modal({show: false});

        $modal.on('click', '.btn-primary', submitHandler || function (event) {
          event.preventDefault();
          $modal.find('form').submit();
        });

        if (modalLinkName) {
          $('a[name="' + modalLinkName + '"]').on('click', function (event) {
            event.preventDefault();
            $modal.modal('toggle');
          });
        }

        return $modal;
      };

      $(function () {
        var $validationModal, $emailRequired;

        modalDialog('#livejournal-modal', 'livejournal');
        modalDialog('#openid-modal', 'openid');
        modalDialog('#email-modal', 'email');
        modalDialog('#username-modal', 'username');
        $validationModal = modalDialog('#validation-sent-modal');
        $emailRequired = modalDialog('#email-required-modal');

        modalDialog('#ajax-login-modal', 'ajax-login', function (event) {
          var $backend, $accessToken, $accessTokenSecret, $fields, $result;
          event.preventDefault();

          $modal = $(this).closest('.modal');
          $form = $modal.find('form');
          $backend = $modal.find('[name="backend"]');
          $accessToken = $modal.find('[name="access_token"]');
          $accessTokenSecret = $modal.find('[name="access_token_secret"]');
          $result = $modal.find('.login-result');

          $.get('/ajax-auth/' + $backend.val() + '/', {
            access_token: $accessToken.val(),
            access_token_secret: $accessTokenSecret.val(),
          }, function (data, xhr, response) {
            $result.find('.user-id').html(data.id);
            $result.find('.user-username').html(data.username);
            $form.hide();
            $result.show();
            setTimeout(function () { window.location = '/'; }, 10000);
          }, 'json')
        });

        modalDialog('#persona-modal', 'persona', function (event) {
          var $form;
          event.preventDefault();

          $form = $(this).closest('form');
          navigator.id.get(function (assertion) {
            if (assertion) {
              $form.find('[name="assertion"]').val(assertion)
              $form.submit();
            } else {
              alert('An error occurred while getting your assertion, try again.');
            }
          });
        });

        $('.disconnect-form').on('click', 'a.btn', function (event) {
          event.preventDefault();
          $(event.target).closest('form').submit();
        });

        {% if validation_sent %}
          $validationModal.modal('show');
        {% endif %}

        {% if email_required %}
          $emailRequired.modal('show');
        {% endif %}
      });
    </script>
  </body>
</html>
