~singpolyma/sgx-jmp

ref: 7f5da6b61064fd3b0b7c80161d60a5ba8e96b504 sgx-jmp/lib/sip_account.rb -rw-r--r-- 1.7 KiB
7f5da6b6Stephen Paul Weber Merge branch 'customer-not-found' 11 months ago
                                                                                
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
# frozen_string_literal: true

require "em-synchrony/em-http" # For aget vs get
require "securerandom"
require "value_semantics/monkey_patched"

require_relative "./catapult"
require_relative "./mn_words"

class SipAccount
	def self.find(name)
		CATAPULT.endpoint_find(name).then do |found|
			next New.new(username: name) unless found

			new(username: found["name"], url: found["url"])
		end
	end

	module Common
		def with_random_password
			with(password: MN_WORDS.sample(3).join(" "))
		end

	protected

		def create
			CATAPULT.create_endpoint(
				name: username,
				credentials: { password: password }
			).then do |url|
				with(url: url)
			end
		end
	end

	include Common

	value_semantics do
		url String
		username String
		password Either(String, nil), default: nil
	end

	def form
		form = Blather::Stanza::X.new(:result)
		form.title = "Sip Account Reset!"
		form.instructions = "These are your new SIP credentials"

		form.fields = [
			{ var: "username", value: username, label: "Username" },
			{ var: "password", value: password, label: "Password" },
			{ var: "server", value: server, label: "Server" }
		]

		form
	end

	def put
		delete.then { create }
	end

	def delete
		CATAPULT.delete(url).then do |http|
			unless http.response_header.status == 200
				raise "Delete old SIP account failed"
			end

			self
		end
	end

protected

	protected :url, :username, :password

	def server
		CATAPULT.sip_host
	end

	class New
		include Common

		value_semantics do
			username String
			password String, default_generator: -> { MN_WORDS.sample(3).join(" ") }
		end

		def put
			create
		end

		def with(**kwargs)
			if kwargs.key?(:url)
				SipAccount.new(internal_to_h.merge(kwargs))
			else
				super
			end
		end

		protected :username, :password
	end
end