Class: Weixin::Middleware
- Inherits:
-
Object
- Object
- Weixin::Middleware
- Defined in:
- lib/weixin/middleware.rb
Constant Summary collapse
- POST_BODY =
'rack.input'.freeze
- WEIXIN_MSG =
'weixin.msg'.freeze
- WEIXIN_MSG_RAW =
'weixin.msg.raw'.freeze
Instance Method Summary collapse
- #_call(env) ⇒ Object
- #call(env) ⇒ Object
-
#initialize(app, app_token, path) ⇒ Middleware
constructor
A new instance of Middleware.
- #invalid_request! ⇒ Object
- #request_is_valid? ⇒ Boolean
Constructor Details
#initialize(app, app_token, path) ⇒ Middleware
Returns a new instance of Middleware.
12 13 14 15 16 |
# File 'lib/weixin/middleware.rb', line 12 def initialize(app, app_token, path) @app = app @app_token = app_token @path = path end |
Instance Method Details
#_call(env) ⇒ Object
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
# File 'lib/weixin/middleware.rb', line 22 def _call(env) if @path == env['PATH_INFO'].to_s && ['GET', 'POST'].include?(env['REQUEST_METHOD']) @req = Rack::Request.new(env) return invalid_request! unless request_is_valid? return [ 200, { 'Content-type' => 'text/plain', 'Content-length' => @req.params['echostr'].length.to_s }, [ @req.params['echostr'] ] ] if @req.get? raw_msg = env[POST_BODY].read begin env.update WEIXIN_MSG => Weixin::Message.factory(raw_msg), WEIXIN_MSG_RAW => raw_msg @app.call(env) rescue Exception => e return [500, { 'Content-type' => 'text/html' }, ["Message parsing error: #{e.to_s}"]] end else @app.call(env) end end |
#call(env) ⇒ Object
18 19 20 |
# File 'lib/weixin/middleware.rb', line 18 def call(env) dup._call(env) end |
#invalid_request! ⇒ Object
46 47 48 |
# File 'lib/weixin/middleware.rb', line 46 def invalid_request! [401, { 'Content-type' => 'text/html', 'Content-Length' => '0'}, []] end |
#request_is_valid? ⇒ Boolean
50 51 52 53 54 55 56 57 58 |
# File 'lib/weixin/middleware.rb', line 50 def request_is_valid? begin param_array = [@app_token, @req.params['timestamp'], @req.params['nonce']] sign = Digest::SHA1.hexdigest( param_array.sort.join ) sign == @req.params['signature'] ? true : false rescue false end end |