-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.rb
129 lines (113 loc) · 2.59 KB
/
app.rb
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
#!/usr/bin/env ruby
# conding: utf-8
require "sinatra"
require "slim"
require "slim/include"
require "sass"
require "coffee-script"
require "uri"
require "httparty"
configure do
# You must be set to environmental variables
unless ENV["GITHUB_APP_ID"] or ENV["GITHUB_APP_SECRET"]
raise "set GITHUB_APP_ID and GITHUB_APP_SECRET"
end
# disable SSL verify
HTTParty::Basement.default_options.update(verify: false)
# store session to cookie
use Rack::Session::Cookie, :key => 'rack.session',
:expire_after => 2592000, # In seconds
:secret => (ENV["GITHUB_APP_ID"] * 3 + ENV["GITHUB_APP_SECRET"] * 2).crypt("saltsalt")
Slim::Engine.options[:pretty] = false
end
helpers do
# check authorization
def auth?
unless session[:token]
return false
else
return true
end
end
end
# routing to main-page or authorize
get '/' do
if auth?
redirect to '/-/repositories'
else
slim :authorize
end
end
# check authorization under /-/
before '/-/*' do
if auth?
@token = session[:token]
else
request.path_info = '/'
end
end
# show repositories
get '/-/repositories' do
slim :repositories
end
# show posts
get '/-/posts/:owner/:repo/:branch' do |owner, repo, branch|
@owner = owner
@repo = repo
@branch = branch
slim :posts
end
# edit a post
get '/-/edit/:owner/:repo/:branch/:directory/:filename' do |owner, repo, branch, directory, filename|
@owner = owner
@repo = repo
@branch = branch
@directory = directory
@filename = filename
slim :edit
end
# compile coffee-script
get %r{.*/(.+)\.coffee$} do |filename|
coffee filename.to_sym
end
# un-authorize
get '/unauth' do
session.clear
redirect to '/'
end
# authorize
get '/auth' do
query = {
client_id: ENV["GITHUB_APP_ID"],
scope: 'repo',
redirect_uri: "#{env['rack.url_scheme']}://#{env['HTTP_HOST']}/auth.callback",
}.map{|k,v|
"#{k}=#{URI.encode v}"
}.join("&")
redirect "https://github.com/login/oauth/authorize?#{query}"
end
# OAuth callback
get '/auth.callback' do
code = params["code"]
halt 400, "bad request (code)" if code.to_s.empty?
## get oauth token
query = {
body: {
client_id: ENV["GITHUB_APP_ID"],
client_secret: ENV["GITHUB_APP_SECRET"],
code: code
},
headers: {
"Accept" => "application/json"
}
}
res = HTTParty.post("https://github.com/login/oauth/access_token", query)
halt 500, "github auth error" unless res.code == 200
begin
token = JSON.parse(res.body)["access_token"] ## tokenを取得!
session[:token] = token
redirect to '/'
rescue
halt 500, "github auth error"
end
end