A lib/backend_sgx.rb => lib/backend_sgx.rb +35 -0
@@ 0,0 1,35 @@
+# frozen_string_literal: true
+
+class BackendSgx
+ def initialize(jid=CONFIG[:sgx], creds=CONFIG[:creds])
+ @jid = jid
+ @creds = creds
+ end
+
+ def register!(customer_id, tel)
+ ibr = mkibr(:set, customer_id)
+ ibr.nick = @creds[:account]
+ ibr.username = @creds[:username]
+ ibr.password = @creds[:password]
+ ibr.phone = tel
+ IQ_MANAGER.write(ibr)
+ end
+
+ def registered?(customer_id)
+ IQ_MANAGER.write(mkibr(:get, customer_id)).catch { nil }.then do |result|
+ if result&.respond_to?(:registered?) && result&.registered?
+ result
+ else
+ false
+ end
+ end
+ end
+
+protected
+
+ def mkibr(type, customer_id)
+ ibr = IBR.new(type, @jid)
+ ibr.from = "customer_#{customer_id}@#{CONFIG[:component][:jid]}"
+ ibr
+ end
+end
M lib/customer.rb => lib/customer.rb +5 -5
@@ 73,12 73,12 @@ class Customer
@plan && @expires_at > Time.now
end
+ def register!(tel)
+ BACKEND_SGX.register!(customer_id, tel)
+ end
+
def registered?
- ibr = IBR.new(:get, CONFIG[:sgx])
- ibr.from = "customer_#{@customer_id}@#{CONFIG[:component][:jid]}"
- IQ_MANAGER.write(ibr).catch { nil }.then do |result|
- result&.respond_to?(:registered?) && result&.registered?
- end
+ BACKEND_SGX.registered?(customer_id)
end
protected
A test/test_backend_sgx.rb => test/test_backend_sgx.rb +54 -0
@@ 0,0 1,54 @@
+# frozen_string_literal: true
+
+require "test_helper"
+require "backend_sgx"
+
+BackendSgx::IQ_MANAGER = Minitest::Mock.new
+
+class BackendSgxTest < Minitest::Test
+ def setup
+ @sgx = BackendSgx.new
+ end
+
+ def test_registered
+ BackendSgx::IQ_MANAGER.expect(
+ :write,
+ EMPromise.resolve(IBR.new.tap { |ibr| ibr.registered = true }),
+ [Matching.new do |ibr|
+ assert_equal :get, ibr.type
+ assert_equal "customer_test@component", ibr.from.to_s
+ end]
+ )
+ assert @sgx.registered?("test").sync
+ end
+ em :test_registered
+
+ def test_registered_not_registered
+ BackendSgx::IQ_MANAGER.expect(
+ :write,
+ EMPromise.resolve(IBR.new.tap { |ibr| ibr.registered = false }),
+ [Matching.new do |ibr|
+ assert_equal :get, ibr.type
+ assert_equal "customer_test@component", ibr.from.to_s
+ end]
+ )
+ refute @sgx.registered?("test").sync
+ end
+ em :test_registered_not_registered
+
+ def test_register!
+ BackendSgx::IQ_MANAGER.expect(
+ :write,
+ EMPromise.resolve(OpenStruct.new(error?: false)),
+ [Matching.new do |ibr|
+ assert_equal "customer_test@component", ibr.from.to_s
+ assert_equal "test_bw_account", ibr.nick
+ assert_equal "test_bw_user", ibr.username
+ assert_equal "test_bw_password", ibr.password
+ assert_equal "+15555550000", ibr.phone
+ end]
+ )
+ @sgx.register!("test", "+15555550000")
+ BackendSgx::IQ_MANAGER.verify
+ end
+end