Class: Slack::Events::Request

Inherits:
Object
  • Object
show all
Defined in:
lib/slack/events/request.rb

Defined Under Namespace

Classes: InvalidSignature, MissingSigningSecret, TimestampExpired

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(http_request, options = {}) ⇒ Request


12
13
14
15
16
# File 'lib/slack/events/request.rb', line 12

def initialize(http_request, options = {})
  @http_request = http_request
  @signing_secret = options[:signing_secret] || Slack::Events.config.signing_secret
  @signature_expires_in = options[:signature_expires_in] || Slack::Events.config.signature_expires_in
end

Instance Attribute Details

#http_requestObject (readonly)

Returns the value of attribute http_request


8
9
10
# File 'lib/slack/events/request.rb', line 8

def http_request
  @http_request
end

#signature_expires_inObject (readonly)

Returns the value of attribute signature_expires_in


8
9
10
# File 'lib/slack/events/request.rb', line 8

def signature_expires_in
  @signature_expires_in
end

#signing_secretObject (readonly)

Returns the value of attribute signing_secret


8
9
10
# File 'lib/slack/events/request.rb', line 8

def signing_secret
  @signing_secret
end

Instance Method Details

#bodyObject

Request body.


35
36
37
# File 'lib/slack/events/request.rb', line 35

def body
  @body ||= http_request.body.read
end

#expired?Boolean

Returns true if the signature coming from Slack has expired.


40
41
42
# File 'lib/slack/events/request.rb', line 40

def expired?
  timestamp.nil? || (Time.now.to_i - timestamp.to_i).abs > signature_expires_in
end

#signatureObject

The signature is created by combining the signing secret with the body of the request Slack is sending using a standard HMAC-SHA256 keyed hash.


25
26
27
# File 'lib/slack/events/request.rb', line 25

def signature
  @signature ||= http_request.headers['X-Slack-Signature']
end

#timestampObject

Request timestamp.


19
20
21
# File 'lib/slack/events/request.rb', line 19

def timestamp
  @timestamp ||= http_request.headers['X-Slack-Request-Timestamp']
end

#valid?Boolean

Returns true if the signature coming from Slack is valid.


45
46
47
48
49
50
51
52
53
# File 'lib/slack/events/request.rb', line 45

def valid?
  raise MissingSigningSecret unless signing_secret

  digest = OpenSSL::Digest::SHA256.new
  signature_basestring = [version, timestamp, body].join(':')
  hex_hash = OpenSSL::HMAC.hexdigest(digest, signing_secret, signature_basestring)
  computed_signature = [version, hex_hash].join('=')
  computed_signature == signature
end

#verify!Object

Validates the request signature and its expiration.

Raises:


56
57
58
59
60
61
# File 'lib/slack/events/request.rb', line 56

def verify!
  raise TimestampExpired if expired?
  raise InvalidSignature unless valid?

  true
end

#versionObject

Signature version.


30
31
32
# File 'lib/slack/events/request.rb', line 30

def version
  'v0'
end