Class: Validocno::Validator

Inherits:
Object
  • Object
show all
Defined in:
lib/validocno/validator.rb

Constant Summary collapse

CONTROL_URI =
'http://politsei.ee/et/teenused/e-paringud/dokumendi-kehtivuse-kontroll/'

Instance Method Summary collapse

Constructor Details

#initialize(doc_number) ⇒ Validator



8
9
10
11
# File 'lib/validocno/validator.rb', line 8

def initialize(doc_number)
  @doc_number = doc_number
  @csrf_token = csrf_token
end

Instance Method Details

#check_response(response) ⇒ Object



64
65
66
67
# File 'lib/validocno/validator.rb', line 64

def check_response(response)
  return true if response.code == 200
  fail StandardError, "#{response.code}: #{response.message}"
end

#csrf_tokenObject



13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/validocno/validator.rb', line 13

def csrf_token
  response = Validocno::Client.get(CONTROL_URI)
  check_response(response)

  node = response.at_css('form[name="reqForm"] input[name="csrf"]')

  if node.nil? || node['value'].nil?
    fail StandardError, 'CSRF token was not found on page'
  else
    node['value']
  end
end

#response_stringObject



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/validocno/validator.rb', line 26

def response_string
  options = {
    :query => {
      :cmd => 'request',
      :csrf => @csrf_token,
      :docNumber => @doc_number
    }
  }

  response = Validocno::Client.post(CONTROL_URI, options)
  check_response(response)

  node = response.at_css('#content1left')

  if node.nil? || node.children.empty?
    fail StandardError, 'Cannot parse document status string.'
  else
    node.children.last.text.strip
  end
end

#response_stringsObject



56
57
58
59
60
61
62
# File 'lib/validocno/validator.rb', line 56

def response_strings
  {
    :valid => "Dokument #{@doc_number} on kehtiv.",
    :expired => "Dokument #{@doc_number} on kehtetu.",
    :invalid => "Dokumenti #{@doc_number} ei ole välja antud."
  }
end

#validateObject



47
48
49
50
51
52
53
54
# File 'lib/validocno/validator.rb', line 47

def validate
  is_valid = response_string.match(response_strings[:valid]) ? true : false

  {
    :valid => is_valid,
    :message => response_string
  }
end