aboutsummaryrefslogtreecommitdiffstats
path: root/app/api/api.rb
blob: 4c24411e0c29d9de278be1f697951760784df513 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
require "grape/rabl"

class Api < Grape::API
  content_type :json, "application/json"
  default_format :json
  formatter :json, Grape::Formatter::Rabl
  error_formatter :json, ->(message, backtrace, options, env) do
    { error: { message: message } }.to_json
  end

  rescue_from ActiveRecord::RecordNotFound, Aclog::Exceptions::NotFound, rescue_subclasses: true do
    error_response message: "That page does not exists.", status: 404
  end
  rescue_from Aclog::Exceptions::Forbidden, rescue_subclasses: true do
    error_response message: "You do not have permission to access this page.", status: 403
  end
  rescue_from Aclog::Exceptions::OAuthEchoError, rescue_subclasses: true do
    error_response message: "Invalid OAuth Echo data.", status: 401
  end

  rescue_from :all

  helpers TwitterOauthEchoAuthentication

  helpers do
    def session
      env["rack.session"]
    end

    def current_user
      @_current_user ||= begin
        if session.key?(:api_user_id)
          User.find(session[:api_user_id])
        elsif headers["X-Verify-Credentials-Authorization"]
          user_id = authenticate_with_twitter_oauth_echo
          session[:api_user_id] = user_id
          User.find(user_id)
        end
      end
    end

    def logged_in?
      !!current_user
    end

    def authorized?(object)
      case object
      when User
        !object.protected? ||
          logged_in? &&
            (object.id == current_user.id ||
             current_user.account.following?(object))
      when Tweet
        authorized?(object.user)
      else
        raise ArgumentError, "object must be User or Tweet"
      end
    end
  end

  mount ApiTweets
  mount ApiUsers

  route :any, "*path", nodoc: true do
    raise Aclog::Exceptions::NotFound
  end
end