I might be diving off into the deep end. I’m new to Stimulus. I’m trying to get passkeys to work in my Rails 7 app using the webauthn gem. I’m looking at the WebAuthn Rails Demo App and slowly adding the code from there into my app when I feel like I understand what it is doing. This means learning what Stimulus is and does.
The demo app takes you to a login screen. If you are new you click and go to a registration screen. On that screen is this form (below). I’ve tried to minimize the code by removing many <div>
s and MDC class identifiers. I hope I haven’t removed too much and the code isn’t too hard to read.
Looking at all the code involved, it appears as if the sequence of events is:
- The user hits submit
- An ajax request is sent to RegistrationsController#create
- It sends back json (assuming success)
- The Ajax success event triggers the new-registration#create
- The credentials are created in the browser
- The browser then issues a second Ajax request to RegistrationsController#callback
- The User record is created in the DB
IF that is correct… how can I tell by looking at the code below that an Ajax request is sent (step 2) when the submit button is pressed rather than an HTML post?
There are three possibilities – all of which may be true.
- The
form_with
adds adata-remote=true
attribute so there may still be remnants of rails-ujs hanging about although so far, I can’t find it. - Because the form has a data-controller attribute, Stimulus is getting involved.
- I’m totally daft and way off base…
<%= form_with scope: :registration,
url: registration_path,
id: "new-registration",
data: {
controller: "new-registration",
action: "ajax:success->new-registration#create ajax:error->new-registration#error"
} do |form| %>
<div class="mdc-text-field mdc-text-field--fullwidth"
data-controller="textfield"
data-target="new-registration.usernameField">
<%= form.text_field :username,
class: "mdc-text-field__input",
placeholder: "Username",
required: true,
autocapitalize: "none",
"aria-controls" => "username-helper-text" %>
</div>
<div class="mdc-text-field mdc-text-field--fullwidth"
data-controller="textfield">
<%= form.text_field :nickname,
class: "mdc-text-field__input",
placeholder: "Security Key nickname",
required: true %>
</div>
<%= form.submit "Register using WebAuthn", class: "mdc-button mdc-button--raised" %>
<% end %>