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) ⇒ Request

Returns a new instance of Request.



10
11
12
# File 'lib/slack/events/request.rb', line 10

def initialize(http_request)
  @http_request = http_request
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

Instance Method Details

#bodyObject

Request body.



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

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

#expired?Boolean

Returns true if the signature coming from Slack has expired.

Returns:

  • (Boolean)


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

def expired?
  timestamp.nil? || (Time.now.to_i - timestamp.to_i).abs > Slack::Events.config.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.



21
22
23
# File 'lib/slack/events/request.rb', line 21

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

#timestampObject

Request timestamp.



15
16
17
# File 'lib/slack/events/request.rb', line 15

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

#valid?Boolean

Returns true if the signature coming from Slack is valid.

Returns:

  • (Boolean)

Raises:



41
42
43
44
45
46
47
48
49
# File 'lib/slack/events/request.rb', line 41

def valid?
  raise MissingSigningSecret unless Slack::Events.config.signing_secret

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

#verify!Object

Validates the request signature and its expiration.

Raises:



52
53
54
55
56
57
# File 'lib/slack/events/request.rb', line 52

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

  true
end

#versionObject

Signature version.



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

def version
  'v0'
end