Class: Gatleon::Authform::Rails::Concern

Inherits:
Module
  • Object
show all
Defined in:
lib/gatleon/authform/rails/concern.rb

Instance Method Summary collapse

Constructor Details

#initialize(public_key:, secret_key:, domain: nil, current_user_method_name: "current_user", signon_url_method_name: "signon_url", _authform_base_url: "https://authformapi.gatleon.com") ⇒ Concern

Returns a new instance of Concern.



7
8
9
10
11
12
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/gatleon/authform/rails/concern.rb', line 7

def initialize(public_key:,
               secret_key:,
               domain: nil,
               current_user_method_name: "current_user",
               signon_url_method_name: "signon_url",
               _authform_base_url: "https://authformapi.gatleon.com")
  super() do
    extend ActiveSupport::Concern

    included do
      helper_method "#{current_user_method_name}".to_sym
      helper_method "#{signon_url_method_name}".to_sym

      before_action :_exchange_user_voucher_for_user
    end

    private

    # defaults to signon_url
    define_method signon_url_method_name do
      "#{_authform_base_url}/v1/form/#{public_key}"
    end

    # defaults to current_user
    define_method current_user_method_name do
      begin
        Gatleon::Authform::Rails::User.new(_cookies: cookies,
                                           _authform_user_cookie_key: _authform_user_cookie_key,
                                           _form_secret_key: secret_key,
                                           _domain: domain,
                                           _authform_base_url: _authform_base_url)
      rescue
        nil
      end
    end

    define_method :_exchange_user_voucher_for_user do
      if params[:_authformForm] == public_key && params[:_authformUserVoucher]
        # TODO: headers for api verification
        
        uri = URI("#{_authform_base_url}/v1/exchangeUserVoucherForUser/#{params[:_authformUserVoucher]}")
        response = Net::HTTP.get_response(uri)

        cookies[_authform_user_cookie_key] = _cookie_attrs(response.body) if response.code.to_i == 200

        q = Rack::Utils.parse_query(URI.parse(request.url).query)
        q.delete("_authformUserVoucher")
        q.delete("_authformForm")
        url = q.empty? ? request.path : "#{request.path}?#{q.to_query}"

        redirect_to url, status: 302 # redirect to finish removal of query param
      end
    end

    define_method :_authform_user_cookie_key do
     "#{public_key}_#{XXhash.xxh32(domain)}"
    end

    define_method :_cookie_attrs do |value|
      {
        value: value,
        domain: domain
      }.compact
    end
  end
end