Project

Profile

Help

How to connect?
Download (2.2 KB) Statistics
| Branch: | Revision:

root / doorkeeper_client.rb @ master

1
require "sinatra/base"
2
require "./lib/html_renderer"
3
require 'yaml'
4

    
5
# Load custom environment variables
6
load 'env.rb' if File.exists?('env.rb')
7

    
8
class DoorkeeperClient < Sinatra::Base
9
  enable :sessions
10

    
11
  helpers do
12
    include Rack::Utils
13
    alias_method :h, :escape_html
14

    
15
    def pretty_json(json)
16
      JSON.pretty_generate(json)
17
    end
18

    
19
    def signed_in?
20
      !session[:access_token].nil?
21
    end
22

    
23
    def markdown(text)
24
      options  = { :autolink => true, :space_after_headers => true, :fenced_code_blocks => true }
25
      markdown = Redcarpet::Markdown.new(HTMLRenderer, options)
26
      markdown.render(text)
27
    end
28

    
29
    def markdown_readme
30
      markdown(File.read(File.join(File.dirname(__FILE__), "README.md")))
31
    end
32
  end
33

    
34
  def client(token_method = :post)
35
    OAuth2::Client.new(
36
      ENV['OAUTH2_CLIENT_ID'],
37
      ENV['OAUTH2_CLIENT_SECRET'],
38
      :site         => ENV['SITE'] || "http://doorkeeper-provider.herokuapp.com",
39
      :token_method => token_method,
40
    )
41
  end
42

    
43
  def access_token
44
    OAuth2::AccessToken.new(client, session[:access_token], :refresh_token => session[:refresh_token])
45
  end
46

    
47
  def redirect_uri
48
    ENV['OAUTH2_CLIENT_REDIRECT_URI']
49
  end
50

    
51
  get '/' do
52
    erb :home
53
  end
54

    
55
  get '/about' do
56
    erb :about
57
  end
58

    
59
  get '/sign_in' do
60
    scope = params[:scope]
61
    redirect client.auth_code.authorize_url(:redirect_uri => redirect_uri, :scope => scope)
62
  end
63

    
64
  get '/sign_out' do
65
    session[:access_token] = nil
66
    redirect '/'
67
  end
68

    
69
  get '/callback' do
70
    new_token = client.auth_code.get_token(params[:code], :redirect_uri => redirect_uri)
71
    session[:access_token]  = new_token.token
72
    session[:refresh_token] = new_token.refresh_token
73
    redirect '/'
74
  end
75

    
76
  get '/refresh' do
77
    new_token = access_token.refresh!
78
    session[:access_token]  = new_token.token
79
    session[:refresh_token] = new_token.refresh_token
80
    redirect '/'
81
  end
82

    
83
  get '/explore/*' do
84
    raise "Please call a valid endpoint" unless params[:splat].first
85
    begin
86
      response = access_token.get("/#{params[:splat].first}")
87
      @json = JSON.parse(response.body)
88
      erb :explore, :layout => !request.xhr?
89
    rescue OAuth2::Error => @error
90
      erb :error, :layout => !request.xhr?
91
    end
92
  end
93
end
(6-6/6)