Class: BotFramework::Server

Inherits:
Object
  • Object
show all
Defined in:
lib/bot_framework/server.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.call(env) ⇒ Object



3
4
5
# File 'lib/bot_framework/server.rb', line 3

def self.call(env)
  new.call(env)
end

Instance Method Details

#call(env) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
# File 'lib/bot_framework/server.rb', line 7

def call(env)
  @request = Rack::Request.new env
  @response = Rack::Response.new
  if @request.post?
    if verify
      receive
    else
      raise InvalidToken
    end
  end
  @response.finish
end

#headersObject



28
29
30
31
32
33
34
35
# File 'lib/bot_framework/server.rb', line 28

def headers
  env = @request.env
  Hash[*env.select { |k, _v| k.start_with? 'HTTP_' }
           .collect { |k, v| [k.sub(/^HTTP_/, ''), v] }
           .collect { |k, v| [k.split('_').collect(&:capitalize).join('-'), v] }
       .sort
       .flatten]
end

#receiveObject

TODO: reply in separate thread t avoid timeout



21
22
23
24
25
26
# File 'lib/bot_framework/server.rb', line 21

def receive
  # Thread.new {
  activity = Activity.new.build_from_hash JSON.parse(@request.body.read)
  Bot.receive(activity)
  # }
end

#verifyObject

Use logger instead of puts



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/bot_framework/server.rb', line 38

def verify
  validator = TokenValidator.new(headers)
  if validator.valid?
    return true
  else
    BotFramework.logger.error "Errors: #{validator.errors}"
    return false
  end
rescue JWT::DecodeError
  [401, { 'Content-Type' => 'text/plain' }, ['A token must be passed.']]
rescue JWT::ExpiredSignature
  [403, { 'Content-Type' => 'text/plain' }, ['The token has expired.']]
rescue JWT::InvalidIssuerError
  [403, { 'Content-Type' => 'text/plain' }, ['The token does not have a valid issuer.']]
rescue JWT::InvalidIatError
  [403, { 'Content-Type' => 'text/plain' }, ['The token does not have a valid "issued at" time.']]
end