Merge branch 'master' into registry-791

This commit is contained in:
Artur Beljajev 2018-06-09 08:01:10 +03:00
commit 36b137eb84
129 changed files with 2226 additions and 3275 deletions

View file

@ -13,9 +13,9 @@ class Ability
case @user.class.to_s
when 'AdminUser'
@user.roles.each { |role| send(role) } if @user.roles
@user.roles&.each { |role| send(role) }
when 'ApiUser'
@user.roles.each { |role| send(role) } if @user.roles
@user.roles&.each { |role| send(role) }
when 'RegistrantUser'
static_registrant
end

View file

@ -1,158 +0,0 @@
class BankLink
module Base
def prepend_size(value)
value = (value || "").to_s.strip
string = ""
string << sprintf("%03i", value.size)
string << value
end
end
class Request
include Base
include ActionView::Helpers::NumberHelper
# need controller here in order to handle random ports and domains
# I don't want to do it but has to
attr_accessor :type, :invoice, :controller
def initialize(type, invoice, controller)
@type, @invoice, @controller = type, invoice, controller
end
def url
ENV["payments_#{type}_url"]
end
def fields
@fields ||= (hash = {}
hash["VK_SERVICE"] = "1012"
hash["VK_VERSION"] = "008"
hash["VK_SND_ID"] = ENV["payments_#{type}_seller_account"]
hash["VK_STAMP"] = invoice.number
hash["VK_AMOUNT"] = number_with_precision(invoice.total, :precision => 2, :separator => ".")
hash["VK_CURR"] = invoice.currency
hash["VK_REF"] = ""
hash["VK_MSG"] = invoice.order
hash["VK_RETURN"] = controller.registrar_return_payment_with_url(type)
hash["VK_CANCEL"] = controller.registrar_return_payment_with_url(type)
hash["VK_DATETIME"] = Time.now.strftime("%Y-%m-%dT%H:%M:%S%z")
hash["VK_MAC"] = calc_mac(hash)
hash["VK_ENCODING"] = "UTF-8"
hash["VK_LANG"] = "ENG"
hash)
end
def calc_mac(fields)
pars = %w(VK_SERVICE VK_VERSION VK_SND_ID VK_STAMP VK_AMOUNT VK_CURR VK_REF
VK_MSG VK_RETURN VK_CANCEL VK_DATETIME).freeze
data = pars.map{|e| prepend_size(fields[e]) }.join
sign(data)
end
def make_transaction
transaction = BankTransaction.where(description: fields["VK_MSG"]).first_or_initialize(
reference_no: invoice.reference_no,
currency: invoice.currency,
iban: invoice.seller_iban
)
transaction.save!
end
private
def sign(data)
private_key = OpenSSL::PKey::RSA.new(File.read(ENV["payments_#{type}_seller_private"]))
signed_data = private_key.sign(OpenSSL::Digest::SHA1.new, data)
signed_data = Base64.encode64(signed_data).gsub(/\n|\r/, '')
signed_data
end
end
class Response
include Base
include ActionView::Helpers::NumberHelper
attr_accessor :type, :params, :invoice
def initialize(type, params)
@type, @params = type, params
@invoice = Invoice.find_by(number: params["VK_STAMP"]) if params["VK_STAMP"].present?
end
def valid?
!!validate
end
def ok?
params["VK_SERVICE"] == "1111"
end
def complete_payment
if valid?
transaction = BankTransaction.find_by(description: params["VK_MSG"])
transaction.sum = BigDecimal.new(params["VK_AMOUNT"].to_s)
transaction.bank_reference = params['VK_T_NO']
transaction.buyer_bank_code = params["VK_SND_ID"]
transaction.buyer_iban = params["VK_SND_ACC"]
transaction.buyer_name = params["VK_SND_NAME"]
transaction.paid_at = Time.parse(params["VK_T_DATETIME"])
transaction.save!
transaction.autobind_invoice
end
end
def validate
case params["VK_SERVICE"]
when "1111"
validate_success && validate_amount && validate_currency
when "1911"
validate_cancel
else
false
end
end
def validate_success
pars = %w(VK_SERVICE VK_VERSION VK_SND_ID VK_REC_ID VK_STAMP VK_T_NO VK_AMOUNT VK_CURR
VK_REC_ACC VK_REC_NAME VK_SND_ACC VK_SND_NAME VK_REF VK_MSG VK_T_DATETIME).freeze
@validate_success ||= (
data = pars.map{|e| prepend_size(params[e]) }.join
verify_mac(data, params["VK_MAC"])
)
end
def validate_cancel
pars = %w(VK_SERVICE VK_VERSION VK_SND_ID VK_REC_ID VK_STAMP VK_REF VK_MSG).freeze
@validate_cancel ||= (
data = pars.map{|e| prepend_size(params[e]) }.join
verify_mac(data, params["VK_MAC"])
)
end
def validate_amount
source = number_with_precision(BigDecimal.new(params["VK_AMOUNT"].to_s), precision: 2, separator: ".")
target = number_with_precision(invoice.total, precision: 2, separator: ".")
source == target
end
def validate_currency
invoice.currency == params["VK_CURR"]
end
def verify_mac(data, mac)
bank_public_key = OpenSSL::X509::Certificate.new(File.read(ENV["payments_#{type}_bank_certificate"])).public_key
bank_public_key.verify(OpenSSL::Digest::SHA1.new, Base64.decode64(mac), data)
end
end
end

View file

@ -45,8 +45,10 @@ class Directo < ActiveRecord::Base
end
data = builder.to_xml.gsub("\n",'')
response = RestClient::Request.execute(url: ENV['directo_invoice_url'], method: :post, payload: {put: "1", what: "invoice", xmldata: data}, verify_ssl: false).to_s
dump_result_to_db(mappers, response)
Rails.logger.info("[Directo] XML request: #{data}")
response = RestClient::Request.execute(url: ENV['directo_invoice_url'], method: :post, payload: {put: "1", what: "invoice", xmldata: data}, verify_ssl: false)
Rails.logger.info("[Directo] Directo responded with code: #{response.code}, body: #{response.body}")
dump_result_to_db(mappers, response.to_s)
end
STDOUT << "#{Time.zone.now.utc} - Directo receipts sending finished. #{counter} of #{total} are sent\n"
@ -165,11 +167,15 @@ class Directo < ActiveRecord::Base
end
data = builder.to_xml.gsub("\n",'')
Rails.logger.info("[Directo] XML request: #{data}")
if debug
STDOUT << "#{Time.zone.now.utc} - Directo xml had to be sent #{data}\n"
else
response = RestClient::Request.execute(url: ENV['directo_invoice_url'], method: :post, payload: {put: "1", what: "invoice", xmldata: data}, verify_ssl: false).to_s
response = RestClient::Request.execute(url: ENV['directo_invoice_url'], method: :post, payload: {put: "1", what: "invoice", xmldata: data}, verify_ssl: false)
Rails.logger.info("[Directo] Directo responded with code: #{response.code}, body: #{response.body}")
response = response.to_s
Setting.directo_monthly_number_last = directo_next
Nokogiri::XML(response).css("Result").each do |res|
Directo.create!(request: data, response: res.as_json.to_h, invoice_number: directo_next)
@ -190,4 +196,3 @@ class Directo < ActiveRecord::Base
@pricelists[account_activity.price_id] = account_activity.price
end
end

View file

@ -147,7 +147,7 @@ class Epp::Contact < Contact
end
if doc = attach_legal_document(Epp::Domain.parse_legal_document_from_frame(frame))
frame.css("legalDocument").first.content = doc.path if doc && doc.persisted?
frame.css("legalDocument").first.content = doc.path if doc&.persisted?
self.legal_document_id = doc.id
end
@ -238,7 +238,7 @@ class Epp::Contact < Contact
)
self.legal_documents = [doc]
frame.css("legalDocument").first.content = doc.path if doc && doc.persisted?
frame.css("legalDocument").first.content = doc.path if doc&.persisted?
self.legal_document_id = doc.id
end

View file

@ -197,7 +197,7 @@ class Epp::Domain < Domain
)
self.legal_documents = [doc]
frame.css("legalDocument").first.content = doc.path if doc && doc.persisted?
frame.css("legalDocument").first.content = doc.path if doc&.persisted?
self.legal_document_id = doc.id
end
# rubocop: enable Metrics/PerceivedComplexity
@ -472,7 +472,7 @@ class Epp::Domain < Domain
at.deep_merge!(attrs_from(frame.css('rem'), current_user, 'rem'))
if doc = attach_legal_document(Epp::Domain.parse_legal_document_from_frame(frame))
frame.css("legalDocument").first.content = doc.path if doc && doc.persisted?
frame.css("legalDocument").first.content = doc.path if doc&.persisted?
self.legal_document_id = doc.id
end
@ -547,7 +547,7 @@ class Epp::Domain < Domain
check_discarded
if doc = attach_legal_document(Epp::Domain.parse_legal_document_from_frame(frame))
frame.css("legalDocument").first.content = doc.path if doc && doc.persisted?
frame.css("legalDocument").first.content = doc.path if doc&.persisted?
end
if Setting.request_confirmation_on_domain_deletion_enabled &&

View file

@ -6,7 +6,8 @@ class LegalDocument < ActiveRecord::Base
if ENV['legal_document_types'].present?
TYPES = ENV['legal_document_types'].split(',').map(&:strip)
else
TYPES = %w(pdf bdoc ddoc zip rar gz tar 7z odt doc docx).freeze
TYPES = %w(pdf asice asics sce scs adoc edoc bdoc ddoc zip rar gz tar 7z odt
doc docx).freeze
end
attr_accessor :body

View file

@ -0,0 +1,15 @@
module PaymentOrders
PAYMENT_INTERMEDIARIES = ENV['payments_intermediaries'].to_s.strip.split(', ').freeze
PAYMENT_BANKLINK_BANKS = ENV['payments_banks'].to_s.strip.split(', ').freeze
PAYMENT_METHODS = [PAYMENT_INTERMEDIARIES, PAYMENT_BANKLINK_BANKS].flatten.freeze
def self.create_with_type(type, invoice, opts = {})
raise ArgumentError unless PAYMENT_METHODS.include?(type)
if PAYMENT_BANKLINK_BANKS.include?(type)
BankLink.new(type, invoice, opts)
elsif type == 'every_pay'
EveryPay.new(type, invoice, opts)
end
end
end

View file

@ -0,0 +1,146 @@
module PaymentOrders
class BankLink < Base
BANK_LINK_VERSION = '008'
NEW_TRANSACTION_SERVICE_NUMBER = '1012'
SUCCESSFUL_PAYMENT_SERVICE_NUMBER = '1111'
CANCELLED_PAYMENT_SERVICE_NUMBER = '1911'
NEW_MESSAGE_KEYS = %w(VK_SERVICE VK_VERSION VK_SND_ID VK_STAMP VK_AMOUNT
VK_CURR VK_REF VK_MSG VK_RETURN VK_CANCEL
VK_DATETIME).freeze
SUCCESS_MESSAGE_KEYS = %w(VK_SERVICE VK_VERSION VK_SND_ID VK_REC_ID VK_STAMP
VK_T_NO VK_AMOUNT VK_CURR VK_REC_ACC VK_REC_NAME
VK_SND_ACC VK_SND_NAME VK_REF VK_MSG
VK_T_DATETIME).freeze
CANCEL_MESSAGE_KEYS = %w(VK_SERVICE VK_VERSION VK_SND_ID VK_REC_ID VK_STAMP
VK_REF VK_MSG).freeze
def form_fields
hash = {}
hash["VK_SERVICE"] = NEW_TRANSACTION_SERVICE_NUMBER
hash["VK_VERSION"] = BANK_LINK_VERSION
hash["VK_SND_ID"] = seller_account
hash["VK_STAMP"] = invoice.number
hash["VK_AMOUNT"] = number_with_precision(invoice.total, precision: 2, separator: ".")
hash["VK_CURR"] = invoice.currency
hash["VK_REF"] = ""
hash["VK_MSG"] = invoice.order
hash["VK_RETURN"] = return_url
hash["VK_CANCEL"] = return_url
hash["VK_DATETIME"] = Time.zone.now.strftime("%Y-%m-%dT%H:%M:%S%z")
hash["VK_MAC"] = calc_mac(hash)
hash["VK_ENCODING"] = "UTF-8"
hash["VK_LANG"] = "ENG"
hash
end
def valid_response_from_intermediary?
return false unless response
case response["VK_SERVICE"]
when SUCCESSFUL_PAYMENT_SERVICE_NUMBER
valid_successful_transaction?
when CANCELLED_PAYMENT_SERVICE_NUMBER
valid_cancel_notice?
else
false
end
end
def complete_transaction
return unless valid_successful_transaction?
transaction = BankTransaction.find_by(
description: invoice.order,
currency: invoice.currency,
iban: invoice.seller_iban
)
transaction.sum = response['VK_AMOUNT']
transaction.bank_reference = response['VK_T_NO']
transaction.buyer_bank_code = response["VK_SND_ID"]
transaction.buyer_iban = response["VK_SND_ACC"]
transaction.buyer_name = response["VK_SND_NAME"]
transaction.paid_at = Time.parse(response["VK_T_DATETIME"])
transaction.save!
transaction.autobind_invoice
end
def settled_payment?
response["VK_SERVICE"] == SUCCESSFUL_PAYMENT_SERVICE_NUMBER
end
private
def valid_successful_transaction?
valid_success_notice? && valid_amount? && valid_currency?
end
def valid_cancel_notice?
valid_mac?(response, CANCEL_MESSAGE_KEYS)
end
def valid_success_notice?
valid_mac?(response, SUCCESS_MESSAGE_KEYS)
end
def valid_amount?
source = number_with_precision(
BigDecimal.new(response["VK_AMOUNT"]), precision: 2, separator: "."
)
target = number_with_precision(
invoice.total, precision: 2, separator: "."
)
source == target
end
def valid_currency?
invoice.currency == response["VK_CURR"]
end
def sign(data)
private_key = OpenSSL::PKey::RSA.new(File.read(seller_certificate))
signed_data = private_key.sign(OpenSSL::Digest::SHA1.new, data)
signed_data = Base64.encode64(signed_data).gsub(/\n|\r/, '')
signed_data
end
def calc_mac(fields)
pars = NEW_MESSAGE_KEYS
data = pars.map { |element| prepend_size(fields[element]) }.join
sign(data)
end
def valid_mac?(hash, keys)
data = keys.map { |element| prepend_size(hash[element]) }.join
verify_mac(data, hash["VK_MAC"])
end
def verify_mac(data, mac)
bank_public_key = OpenSSL::X509::Certificate.new(File.read(bank_certificate)).public_key
bank_public_key.verify(OpenSSL::Digest::SHA1.new, Base64.decode64(mac), data)
end
def prepend_size(value)
value = (value || "").to_s.strip
string = ""
string << format("%03i", value.size)
string << value
end
def seller_account
ENV["payments_#{type}_seller_account"]
end
def seller_certificate
ENV["payments_#{type}_seller_private"]
end
def bank_certificate
ENV["payments_#{type}_bank_certificate"]
end
end
end

View file

@ -0,0 +1,33 @@
module PaymentOrders
class Base
include ActionView::Helpers::NumberHelper
attr_reader :type,
:invoice,
:return_url,
:response_url,
:response
def initialize(type, invoice, opts = {})
@type = type
@invoice = invoice
@return_url = opts[:return_url]
@response_url = opts[:response_url]
@response = opts[:response]
end
def create_transaction
transaction = BankTransaction.where(description: invoice.order).first_or_initialize(
reference_no: invoice.reference_no,
currency: invoice.currency,
iban: invoice.seller_iban
)
transaction.save!
end
def form_url
ENV["payments_#{type}_url"]
end
end
end

View file

@ -0,0 +1,84 @@
module PaymentOrders
class EveryPay < Base
USER = ENV['payments_every_pay_api_user'].freeze
KEY = ENV['payments_every_pay_api_key'].freeze
ACCOUNT_ID = ENV['payments_every_pay_seller_account'].freeze
SUCCESSFUL_PAYMENT = %w(settled authorized).freeze
def form_fields
base_json = base_params
base_json[:nonce] = SecureRandom.hex(15)
hmac_fields = (base_json.keys + ['hmac_fields']).sort.uniq!
base_json[:hmac_fields] = hmac_fields.join(',')
hmac_string = hmac_fields.map { |key, _v| "#{key}=#{base_json[key]}" }.join('&')
hmac = OpenSSL::HMAC.hexdigest('sha1', KEY, hmac_string)
base_json[:hmac] = hmac
base_json
end
def valid_response_from_intermediary?
return false unless response
valid_hmac? && valid_amount? && valid_account?
end
def settled_payment?
SUCCESSFUL_PAYMENT.include?(response[:payment_state])
end
def complete_transaction
return unless valid_response_from_intermediary? && settled_payment?
transaction = BankTransaction.find_by(
description: invoice.order,
currency: invoice.currency,
iban: invoice.seller_iban
)
transaction.sum = response[:amount]
transaction.paid_at = Date.strptime(response[:timestamp], '%s')
transaction.buyer_name = response[:cc_holder_name]
transaction.save!
transaction.autobind_invoice
end
private
def base_params
{
api_username: USER,
account_id: ACCOUNT_ID,
timestamp: Time.now.to_i.to_s,
callback_url: response_url,
customer_url: return_url,
amount: number_with_precision(invoice.total, precision: 2),
order_reference: SecureRandom.hex(15),
transaction_type: 'charge',
hmac_fields: ''
}.with_indifferent_access
end
def valid_hmac?
hmac_fields = response[:hmac_fields].split(',')
hmac_hash = {}
hmac_fields.map do |field|
symbol = field.to_sym
hmac_hash[symbol] = response[symbol]
end
hmac_string = hmac_hash.map { |key, _v| "#{key}=#{hmac_hash[key]}" }.join('&')
expected_hmac = OpenSSL::HMAC.hexdigest('sha1', KEY, hmac_string)
expected_hmac == response[:hmac]
end
def valid_amount?
invoice.total == BigDecimal.new(response[:amount])
end
def valid_account?
response[:account_id] == ACCOUNT_ID
end
end
end

View file

@ -1,2 +1,23 @@
class TechDomainContact < DomainContact
# Audit log is needed, therefore no raw SQL
def self.replace(current_contact, new_contact)
affected_domains = []
skipped_domains = []
tech_contacts = where(contact: current_contact)
transaction do
tech_contacts.each do |tech_contact|
if tech_contact.domain.discarded?
skipped_domains << tech_contact.domain.name
next
end
tech_contact.contact = new_contact
tech_contact.save!
affected_domains << tech_contact.domain.name
end
end
return affected_domains.sort, skipped_domains.sort
end
end

View file

@ -36,6 +36,7 @@ class WhoisRecord < ActiveRecord::Base
registrant = domain.registrant
@disclosed = []
h[:disclaimer] = disclaimer_text if disclaimer_text.present?
h[:name] = domain.name
h[:status] = domain.statuses.map { |x| status_map[x] || x }
h[:registered] = domain.registered_at.try(:to_s, :iso8601)
@ -120,4 +121,10 @@ class WhoisRecord < ActiveRecord::Base
def destroy_whois_record
Whois::Record.where(name: name).delete_all
end
private
def disclaimer_text
Setting.registry_whois_disclaimer
end
end