Class: Clova::Validator

Inherits:
Object
  • Object
show all
Defined in:
lib/clova-speech/validator.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(app_id:) ⇒ Validator

raw_request: is the body of the incoming request, in the form of String request_sign: is the signature, found in the header of the request under “SignatureCEK”



13
14
15
# File 'lib/clova-speech/validator.rb', line 13

def initialize(app_id:)
  @app_id = app_id
end

Instance Attribute Details

#app_idObject

Returns the value of attribute app_id.



9
10
11
# File 'lib/clova-speech/validator.rb', line 9

def app_id
  @app_id
end

Instance Method Details

#valid_app_id?(request_body_str) ⇒ Boolean

Returns:

  • (Boolean)


35
36
37
38
39
# File 'lib/clova-speech/validator.rb', line 35

def valid_app_id?(request_body_str)
  request = JSON.parse(request_body_str)
  request_app_id = request['context']['System']['application']['applicationId']
  app_id == request_app_id
end

#valid_signature?(request_body_str, request_sign) ⇒ Boolean

Returns:

  • (Boolean)


30
31
32
33
# File 'lib/clova-speech/validator.rb', line 30

def valid_signature?(request_body_str, request_sign)
  key = OpenSSL::PKey::RSA.new clova_public_key
  key.public_key.verify(OpenSSL::Digest::SHA256.new, Base64.decode64(request_sign), request_body_str)
end

#validate(raw_request) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/clova-speech/validator.rb', line 17

def validate(raw_request)
  request_body_str = raw_request.body.read
  request_sign = raw_request.env["HTTP_SIGNATURECEK"]

  sign_result = valid_signature?(request_body_str, request_sign)
  app_id_result = valid_app_id?(request_body_str)

  raise 'Bad Request: invalid signature' unless sign_result
  raise 'Bad Request: invalid application id' unless app_id_result

  sign_result && app_id_result
end