Class: Svix::AutoConfig

Inherits:
Object
  • Object
show all
Defined in:
lib/svix/autoconfig.rb

Defined Under Namespace

Classes: InvalidTokenError

Constant Summary collapse

AUTOCONFIG_TOKEN_PREFIX_V1 =
"auto_v1_"

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(token, endpoint_in) ⇒ AutoConfig

Returns a new instance of AutoConfig.



18
19
20
21
22
23
24
25
26
27
28
# File 'lib/svix/autoconfig.rb', line 18

def initialize(token, endpoint_in)
  content = AutoConfig.decode_token!(token)
  @app_id = content.fetch("app_id")
  @endpoint_id = content.fetch("endpoint_id")
  @endpoint = endpoint_in
  @webhook = Webhook.new(content.fetch("endpoint_secret"))
  @client = SvixHttpClient.new(
    content.fetch("token_plaintext"),
    URI(content.fetch("server_url"))
  )
end

Instance Attribute Details

#app_idObject (readonly)

Returns the value of attribute app_id.



16
17
18
# File 'lib/svix/autoconfig.rb', line 16

def app_id
  @app_id
end

#endpointObject (readonly)

Returns the value of attribute endpoint.



16
17
18
# File 'lib/svix/autoconfig.rb', line 16

def endpoint
  @endpoint
end

#endpoint_idObject (readonly)

Returns the value of attribute endpoint_id.



16
17
18
# File 'lib/svix/autoconfig.rb', line 16

def endpoint_id
  @endpoint_id
end

Class Method Details

.decode_token!(token) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/svix/autoconfig.rb', line 43

def decode_token!(token)
  unless token.is_a?(String) && token.start_with?(AUTOCONFIG_TOKEN_PREFIX_V1)
    raise InvalidTokenError
  end

  encoded = token.byteslice(AUTOCONFIG_TOKEN_PREFIX_V1.length..-1)
  json = Base64.decode64(encoded)
  data = JSON.parse(json)
  unless data.is_a?(Hash)
    raise InvalidTokenError
  end

  {
    "app_id" => data.fetch("aid"),
    "endpoint_id" => data.fetch("eid"),
    "server_url" => data.fetch("surl"),
    "endpoint_secret" => data.fetch("esec"),
    "token_plaintext" => data.fetch("tok"),
  }
rescue ArgumentError, JSON::ParserError, KeyError, TypeError
  raise InvalidTokenError
end

Instance Method Details

#subscribeObject



30
31
32
33
34
35
36
# File 'lib/svix/autoconfig.rb', line 30

def subscribe
  EndpointAutoConfig.new(@client).update(
    @app_id,
    @endpoint_id,
    SubscribeIn.new("endpoint" => @endpoint)
  )
end

#verify(payload, headers) ⇒ Object



38
39
40
# File 'lib/svix/autoconfig.rb', line 38

def verify(payload, headers)
  @webhook.verify(payload, headers)
end