Class: Rack::Auth::Slack

Inherits:
Object
  • Object
show all
Defined in:
lib/rack/auth/slack.rb,
lib/rack/auth/slack/version.rb

Constant Summary collapse

VERSION =
"0.1.0"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(app, slack_secret, version = "v0") ⇒ Slack

Returns a new instance of Slack.



9
10
11
12
13
# File 'lib/rack/auth/slack.rb', line 9

def initialize(app, slack_secret, version = "v0")
  @app = app
  @slack_secret = slack_secret
  @version = version
end

Instance Attribute Details

#slack_secretObject

Returns the value of attribute slack_secret.



7
8
9
# File 'lib/rack/auth/slack.rb', line 7

def slack_secret
  @slack_secret
end

#versionObject

Returns the value of attribute version.



7
8
9
# File 'lib/rack/auth/slack.rb', line 7

def version
  @version
end

Instance Method Details

#call(env) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/rack/auth/slack.rb', line 15

def call(env)
  request = Rack::Request.new(env)

  timestamp = request.env["HTTP_X_SLACK_REQUEST_TIMESTAMP"]
  
  # check that the timestamp is recent (~5 mins) to prevent replay attacks
  if Time.at(timestamp.to_i) < Time.now - (60 * 5)
    return unauthorized
  end
  
  # generate hash
  request_body = request.body.read

  computed_signature = generate_hash(timestamp, request_body)

  # compare generated hash with slack signature
  slack_signature = request.env["HTTP_X_SLACK_SIGNATURE"]

  if computed_signature == slack_signature
    return @app.call(env)
  end

  unauthorized
end

#generate_hash(timestamp, request_body) ⇒ Object



40
41
42
43
44
45
46
# File 'lib/rack/auth/slack.rb', line 40

def generate_hash(timestamp, request_body)
  sig_basestring = "#{self.version}:#{timestamp}:#{request_body}"
  digest = OpenSSL::Digest::SHA256.new
  hex_hash = OpenSSL::HMAC.hexdigest(digest, self.slack_secret, sig_basestring)
  
  "#{self.version}=#{hex_hash}"
end