<form method="post" action="/login/tls">
  <div class="form-group">

    <button type="submit" class="btn btn-primary" id="login-tls">
      With Certificate (WebId-TLS)
    </button>

    {{> auth/auth-hidden-fields}}
  </div>
</form>

<script type="text/javascript">
  const button = document.getElementById('login-tls')
  button.addEventListener('click', function(event) {
    event.preventDefault()
    fetch('/login/tls', { method: 'POST', credentials: 'include' })
      .then(function(response) {
        const webId = response.headers.get('user')
        const idp = new URL(webId).origin
        const session = { authType: 'WebID-TLS', webId, idp }
        const authClientNamespace = 'solid-auth-client'
        let authClientStore
        try {
          authClientStore = JSON.parse(localStorage.getItem(authClientNamespace) || '{}')
        } catch (err) {
          authClientStore = {}
        }
        authClientStore.session = session
        localStorage.setItem(authClientNamespace, JSON.stringify(authClientStore))
        return response
      })
      .then(function(response) {
        window.location.href = response.url
      })
  })
</script>
