Module: ChatworkWebhookVerify

Defined in:
lib/chatwork_webhook_verify.rb,
lib/chatwork_webhook_verify/railtie.rb,
lib/chatwork_webhook_verify/version.rb,
lib/chatwork_webhook_verify/configuration.rb,
lib/chatwork_webhook_verify/controller_extension.rb

Defined Under Namespace

Modules: ControllerExtension Classes: Configuration, InvalidSignatureError, Railtie

Constant Summary collapse

VERSION =
'1.0.0'

Class Method Summary collapse

Class Method Details

.configChatworkWebhookVerify::Configuration



51
52
53
# File 'lib/chatwork_webhook_verify.rb', line 51

def self.config
  @config ||= Configuration.new
end

.generate_signature(token:, body:) ⇒ String

Parameters:

  • token (String)

    webhook token (default: ChatworkWebhookVerify.config.token)

  • body (String)

    request body

Returns:

  • (String)


45
46
47
48
# File 'lib/chatwork_webhook_verify.rb', line 45

def self.generate_signature(token:, body:)
  secret_key = Base64.decode64(token)
  Base64.strict_encode64(OpenSSL::HMAC.digest(OpenSSL::Digest.new("sha256"), secret_key, body))
end

.verify!(token: nil, body:, signature:) ⇒ Object

Note:

Either token or ChatworkWebhookVerify.config.token is required

Whether signature is valid

Parameters:

  • token (String) (defaults to: nil)

    webhook token (default: ChatworkWebhookVerify.config.token)

  • body (String)

    request body

  • signature (String)

    chatwork_webhook_signature or X-ChatWorkWebhookSignature

Raises:



37
38
39
# File 'lib/chatwork_webhook_verify.rb', line 37

def self.verify!(token: nil, body:, signature:)
  raise InvalidSignatureError unless verify?(token: token, body: body, signature: signature)
end

.verify?(token: nil, body:, signature:) ⇒ Boolean

Note:

Either token or ChatworkWebhookVerify.config.token is required

Whether signature is valid

Parameters:

  • token (String) (defaults to: nil)

    webhook token (default: ChatworkWebhookVerify.config.token)

  • body (String)

    request body

  • signature (String)

    chatwork_webhook_signature or X-ChatWorkWebhookSignature

Returns:

  • (Boolean)

Raises:

  • (ArgumentError)


19
20
21
22
23
24
25
26
# File 'lib/chatwork_webhook_verify.rb', line 19

def self.verify?(token: nil, body:, signature:)
  token ||= config.token

  raise ArgumentError, "Either token or ChatworkWebhookVerify.config.token is required" if !token || token.empty?
  raise ArgumentError, "signature is required" if !signature || signature.empty?

  generate_signature(token: token, body: body) == signature
end