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

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

Instance Method Summary collapse

Constructor Details

#initialize(public_key:, secret_key:, current_user_method_name: "current_user", _authform_base_url: "https://authform.gatleon.com") ⇒ Concern

Returns a new instance of Concern.



5
6
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
# File 'lib/gatleon/rails/authform/concern.rb', line 5

def initialize(public_key:,
               secret_key:,
               current_user_method_name: "current_user",
               _authform_base_url: "https://authform.gatleon.com")
  super() do
    extend ActiveSupport::Concern

    included do
      helper_method "#{current_user_method_name}".to_sym
      before_action :_exchange_user_voucher_for_user
    end

    private

    # defaults to current_user
    define_method current_user_method_name do
      begin
        json = JSON.parse(cookies[_authform_user_cookie_key])["data"]

        Gatleon::Rails::Authform::User.new(json: json, _form_secret_key: secret_key, _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)

        if response.code.to_i == 200
          # First attempt WITHOUT all - for setting on platforms like heroku that deny setting cookies across all subdomains
          cookies[_authform_user_cookie_key] = {
            value: response.body
          }

          # Then set all - desired behavior for hosting your own domain
          cookies[_authform_user_cookie_key] = {
            value: response.body,
            domain: :all
          }
        end

        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 # allows for multiple forms per site
    end
  end
end