module ChatworkWebhookVerify

Constants

VERSION

Public Class Methods

config() click to toggle source

@return [ChatworkWebhookVerify::Configuration]

# File lib/chatwork_webhook_verify.rb, line 51
def self.config
  @config ||= Configuration.new
end
generate_signature(token:, body:) click to toggle source

@param token [String] webhook token (default: `ChatworkWebhookVerify.config.token`) @param body [String] request body

@return [String]

# 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:) click to toggle source

Whether signature is valid

@param token [String] webhook token (default: `ChatworkWebhookVerify.config.token`) @param body [String] request body @param signature [String] chatwork_webhook_signature or X-ChatWorkWebhookSignature

@raise [InvalidSignatureError] signature is invalid

@note Either `token` or `ChatworkWebhookVerify.config.token` is required

# 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:) click to toggle source

Whether signature is valid

@param token [String] webhook token (default: `ChatworkWebhookVerify.config.token`) @param body [String] request body @param signature [String] chatwork_webhook_signature or X-ChatWorkWebhookSignature

@return [Boolean]

@note Either `token` or `ChatworkWebhookVerify.config.token` is required

# 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