lib/micropub/server/rails/middleware.rb in micropub-server-rails-0.1.5 vs lib/micropub/server/rails/middleware.rb in micropub-server-rails-0.1.6

- old
+ new

@@ -1,46 +1,67 @@ require 'micropub' module Micropub::Server::Rails class Middleware + class HTTPError < StandardError + def initialize(env, status, body="") + @env = env + @status = status + @body = body + end + end + def initialize(app) @app = app end def call(env) - if env["PATH_INFO"] == "/micropub" - token = Micropub::Token.new(auth_token(env)) - token.valid? ? response : error_response - else - @app.call env + begin + @params = request(env).params + @headers = {"Content-Type" => "text/plain; charset=utf-8"} + if env["PATH_INFO"] == "/micropub" + check_token(env) + micropub_call env + else + @app.call env + end + rescue + error_response(401) end end + def check_token(env) + token = Micropub::Token.new(auth_token(env)) + raise HTTPError.new env, 401 if !token.valid? + end + def auth_token(env) - input = env["HTTP_AUTHORIZATION"] || request(env).params["access_token"] || "" + input = env["HTTP_AUTHORIZATION"] || @params["access_token"] || "" input.split("Bearer ").last end - def response - [201, headers, body] + def micropub_call(env) + router = Micropub::Homesteading::Router.new(@params) + client = Micropub::Client.new(router.as, token: auth_token(env)) + response = client.post(@params.except("access_token")) + + raise HTTPError.new env, response.status if !response.successful? + + @headers["Location"] = response.location + + success_response end - def error_response - [401, {}, body] + def success_response + [201, @headers, [""]] end - def body - [""] + def error_response(status) + [status, {}, [""]] end def request(env) Rack::Request.new(env) end - def headers - { - "Location" => "http://bookisworthy.com/posts/1", - "Content-Type" => "text/plain; charset=utf-8" - } - end end end