-
Notifications
You must be signed in to change notification settings - Fork 8
/
diba_census_api_authorization_handler.rb
86 lines (68 loc) · 2.06 KB
/
diba_census_api_authorization_handler.rb
1
2
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
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# frozen_string_literal: true
require 'virtus/multiparams'
# An AuthorizationHandler that uses the DibaCensusApiService to create authorizations
class DibaCensusApiAuthorizationHandler < Decidim::AuthorizationHandler
include Virtus::Multiparams
# This is the input (from the user) to validate against
attribute :document_type, Symbol
attribute :id_document, String
attribute :birthdate, Date
# This is the validation to perform
# If passed, is authorized
validates :document_type, inclusion: { in: %i(dni nie passport) }, presence: true
validates :id_document, presence: true
validates :birthdate, presence: true
validate :censed
def metadata
{ birthdate: birthdate.strftime('%Y/%m/%d') }
end
def census_document_types
%i(dni nie passport).map do |type|
[
I18n.t(type, scope: %w[decidim authorization_handlers
diba_census_api_authorization_handler
document_types]),
type
]
end
end
# Checks if the id_document belongs to the census
def censed
return if census_for_user&.birthdate == birthdate
errors.add(:id_document, I18n.t('decidim.census.errors.messages.not_censed'))
end
def unique_id
return unless census_for_user
Digest::SHA256.hexdigest(
"#{census_for_user.id_document}-#{Rails.application.secrets.secret_key_base}"
)
end
def census_for_user
return @census_for_user if defined? @census_for_user
@service = DibaCensusApi.new(api_config)
@census_for_user = @service.call(
birthdate: birthdate,
document_type: document_type_code,
id_document: id_document
)
end
private
def document_type_code
case document_type&.to_sym
when :dni
'01'
when :passport
'02'
when :nie
'03'
end
end
def api_config
{ ine: organization.diba_census_api_ine,
username: organization.diba_census_api_username,
password: organization.diba_census_api_password }
end
def organization
current_organization || user.try(:organization)
end
end