Class: PasskeyAuth::Webauthn::CredentialsController

Inherits:
ApplicationController show all
Defined in:
app/controllers/passkey_auth/webauthn/credentials_controller.rb

Instance Method Summary collapse

Instance Method Details

#createObject



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'app/controllers/passkey_auth/webauthn/credentials_controller.rb', line 13

def create
  webauthn_credential = ::WebAuthn::Credential.from_create(params[:credential])

  # Verify the credential
  challenge = session[:webauthn_registration_challenge]
  unless challenge
    return render json: { error: I18n.t("passkey_auth.webauthn.session_expired") }, status: :unprocessable_content
  end

  begin
    webauthn_credential.verify(challenge)

    # Ensure user has a webauthn_id
    unless current_user.webauthn_id
      current_user.update!(webauthn_id: ::WebAuthn.generate_user_id)
    end

    # Store the credential
    credential = current_user.webauthn_credentials.create!(
      external_id: webauthn_credential.id,
      nickname: params[:nickname] || "Passkey",
      public_key: webauthn_credential.public_key,
      sign_count: webauthn_credential.sign_count
    )

    # Call hook if configured
    PasskeyAuth.on_passkey_created&.call(current_user, credential)

    render json: { success: true }
  rescue ::WebAuthn::Error => e
    Rails.logger.error "WebAuthn verification failed: #{e.message}"
    render json: { error: I18n.t("passkey_auth.webauthn.verification_failed") }, status: :unprocessable_content
  ensure
    session.delete(:webauthn_registration_challenge)
  end
end

#destroyObject



50
51
52
53
54
55
# File 'app/controllers/passkey_auth/webauthn/credentials_controller.rb', line 50

def destroy
  credential = current_user.webauthn_credentials.find(params[:id])
  credential.destroy

  redirect_to webauthn_credentials_path, notice: I18n.t("passkey_auth.webauthn.credential_deleted")
end

#indexObject

Expects Rails Authentication concern to provide:

  • current_user


9
10
11
# File 'app/controllers/passkey_auth/webauthn/credentials_controller.rb', line 9

def index
  @credentials = current_user.webauthn_credentials.order(created_at: :desc)
end