Sha256: ffc77fc2f3b0c64a21cad91f178f3ed95231b5ec188844f401fdaccbea58e2be

Contents?: true

Size: 1.44 KB

Versions: 2

Compression:

Stored size: 1.44 KB

Contents

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

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
micropub-server-rails-0.1.7 lib/micropub/server/rails/middleware.rb
micropub-server-rails-0.1.6 lib/micropub/server/rails/middleware.rb