Module: TFA::TfaHelper

Defined in:
app/helpers/tfa/tfa_helper.rb

Instance Method Summary collapse

Instance Method Details

#if_tfa(expected_phone: nil, &block) ⇒ Object



36
37
38
39
40
41
42
43
44
# File 'app/helpers/tfa/tfa_helper.rb', line 36

def if_tfa(expected_phone:nil, &block)
  if tfa_valid(expected_phone: expected_phone)
    @tfa = Tfa.find_by(id: params[:tfa_id])
    @tfa.used = true
    @tfa.save

    block.call(@tfa)
  end
end

#no_tfa(expected_phone: nil, &block) ⇒ Object



46
47
48
49
50
# File 'app/helpers/tfa/tfa_helper.rb', line 46

def no_tfa(expected_phone:nil, &block)
  if !tfa_valid(expected_phone: expected_phone)
    block.call
  end
end

#require_tfa(url:, method: :post, http_params: {}, phone_number:, message: "Your two factor authentication code is:\n\n{code}", length: 6) ⇒ Object



3
4
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
# File 'app/helpers/tfa/tfa_helper.rb', line 3

def require_tfa(
  url:,
  method: :post,
  http_params: {},
  phone_number:,
  message: "Your two factor authentication code is:\n\n{code}",
  length: 6
)
  @tfa = Tfa.new
  @tfa.phone = phone_number
  @tfa.used = false

  http_params_ = ""
  http_params.each do |p|
    http_params_ << "#{p[0]}:#{p[1].gsub(':', "\0001").gsub(',', "\0002").gsub('#', "\0003")},"
  end

  @tfa.after = "#{method}###{url}###{http_params_}"
  @tfa.code = rand((10**(length-1))..("9"*length).to_i)
  @tfa.save

  Twilio.send_msg(
    message.gsub("{code}", @tfa.code.to_s),
    to: phone_number
  )

  controller.redirect_to Engine.routes.url_helpers.tfa_verify_path(@tfa)
end

#tfa_friendly_params(p) ⇒ Object



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'app/helpers/tfa/tfa_helper.rb', line 52

def tfa_friendly_params(p)
  p.permit!
  p = p.to_h
  out = {}

  p.each do |param|
    if param[1].class != ActiveSupport::HashWithIndifferentAccess
      out[param[0]] = param[1]
    else
      param[1].each do |p1|
        out["#{param[0]}[#{p1[0]}]"] = p1[1]
      end
    end
  end

  return out
end

#tfa_valid(expected_phone: nil) ⇒ Object



32
33
34
# File 'app/helpers/tfa/tfa_helper.rb', line 32

def tfa_valid(expected_phone:nil)
  params[:tfa_id] && Tfa.find_by(id: params[:tfa_id]).code.to_s == params[:code].to_s && !Tfa.find_by(id: params[:tfa_id]).used && (Tfa.find_by(id: params[:tfa_id]).phone == expected_phone || expected_phone == nil)
end