Sha256: ef7a1f717bcf376e1f7e587689faa863b6ec957a2d92a2687e85cc8aa8f001c7

Contents?: true

Size: 1.76 KB

Versions: 1

Compression:

Stored size: 1.76 KB

Contents

require 'micropub'

module Micropub::Server::Rails
  class Middleware
    class HTTPError < StandardError
      attr_reader :status
      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" => "application/x-www-form-urlencoded"}
        if env["PATH_INFO"] == "/micropub"
          micropub_call env
        else
          @app.call env
        end
      rescue HTTPError => env
        error_response(env.status)
      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)
      case env["REQUEST_METHOD"]
      when "GET" then syndicate_to env
      when "POST" then post env
      else
        raise HTTPError.new env, 405
      end
    end

    def syndicate_to(env)
      # TODO: Remove hardcoded syndicate link
      [200, @headers, ["syndicate-to[]=twitter.com%2fbookis"]]
    end

    def post(env)
      check_token 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

      [201, @headers, [""]]
    end

    def error_response(status)
      [status, {}, [""]]
    end

    def request(env)
      Rack::Request.new(env)
    end

  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
micropub-server-rails-0.1.8 lib/micropub/server/rails/middleware.rb