Read about our upcoming Code of Conduct on this issue

u2f_registration.rb 1.55 KB
Newer Older
1
2
# frozen_string_literal: true

3
4
# Registration information for U2F (universal 2nd factor) devices, like Yubikeys

5
class U2fRegistration < ApplicationRecord
6
7
  belongs_to :user

Timothy Andrew's avatar
Timothy Andrew committed
8
  def self.register(user, app_id, params, challenges)
9
10
11
12
    u2f = U2F::U2F.new(app_id)
    registration = self.new

    begin
Timothy Andrew's avatar
Timothy Andrew committed
13
      response = U2F::RegisterResponse.load_from_json(params[:device_response])
14
15
16
17
18
      registration_data = u2f.register!(challenges, response)
      registration.update(certificate: registration_data.certificate,
                          key_handle: registration_data.key_handle,
                          public_key: registration_data.public_key,
                          counter: registration_data.counter,
Timothy Andrew's avatar
Timothy Andrew committed
19
20
                          user: user,
                          name: params[:name])
21
    rescue JSON::ParserError, NoMethodError, ArgumentError
22
      registration.errors.add(:base, _('Your U2F device did not send a valid JSON response.'))
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
    rescue U2F::Error => e
      registration.errors.add(:base, e.message)
    end

    registration
  end

  def self.authenticate(user, app_id, json_response, challenges)
    response = U2F::SignResponse.load_from_json(json_response)
    registration = user.u2f_registrations.find_by_key_handle(response.key_handle)
    u2f = U2F::U2F.new(app_id)

    if registration
      u2f.authenticate!(challenges, response, Base64.decode64(registration.public_key), registration.counter)
      registration.update(counter: response.counter)
      true
    end
  rescue JSON::ParserError, NoMethodError, ArgumentError, U2F::Error
    false
  end
end