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) 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"] || @params["access_token"] || "" input.split("Bearer ").last end 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 success_response [201, @headers, [""]] end def error_response(status) [status, {}, [""]] end def request(env) Rack::Request.new(env) end end end