forked from kelsin/18xx
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.rb
More file actions
201 lines (158 loc) · 4.26 KB
/
Copy pathapi.rb
File metadata and controls
201 lines (158 loc) · 4.26 KB
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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
# frozen_string_literal: true
PRODUCTION = ENV['RACK_ENV'] == 'production'
require 'message_bus'
require 'opal'
require 'require_all'
require 'roda'
require 'snabberb'
require_relative 'models'
require_relative 'lib/assets'
require_relative 'lib/mail'
require_rel './models'
MessageBus.configure(
backend: :postgres,
backend_options: {
host: DB.opts[:host],
user: DB.opts[:user],
dbname: DB.opts[:database],
password: DB.opts[:password],
port: DB.opts[:port],
},
clear_every: 10,
)
MessageBus.reliable_pub_sub.max_backlog_size = 1
MessageBus.reliable_pub_sub.max_global_backlog_size = 100_000
MessageBus.reliable_pub_sub.max_backlog_age = 172_800 # 2 days
class Api < Roda
opts[:check_dynamic_arity] = false
opts[:check_arity] = :warn
plugin :default_headers,
'Content-Type' => 'text/html',
'X-Frame-Options' => 'deny',
'X-Content-Type-Options' => 'nosniff',
'Cache-Control' => 'no-cache, max-age=0, must-revalidate, no-store',
'X-XSS-Protection' => '1; mode=block'
plugin :content_security_policy do |csp|
csp.default_src :self
csp.style_src :self
csp.form_action :self
csp.script_src :self
csp.connect_src :self
csp.base_uri :none
csp.frame_ancestors :none
end
LOGGER = Logger.new('log/rack/rack.log')
plugin :common_logger, LOGGER
plugin :not_found do
halt(404, 'Page not found')
end
plugin :error_handler
error do |e|
puts e.backtrace.reverse
puts "#{e.class}: #{e.message}"
LOGGER.error e.backtrace
{ error: e.message }
end
plugin :public
plugin :hash_routes
plugin :streaming
plugin :json
plugin :json_parser
plugin :halt
ASSETS = Assets.new(precompiled: PRODUCTION)
use MessageBus::Rack::Middleware
use Rack::Deflater unless PRODUCTION
STANDARD_ROUTES = %w[
/ about hotseat login map new_game profile signup tiles tutorial
].freeze
Dir['./routes/*'].sort.each { |file| require file }
hash_routes do
on 'api' do |hr|
hr.hash_routes :api
hr.is 'chat', method: 'post' do
not_authorized! unless user
publish(
'/chat',
50,
user: user.to_h,
message: hr.params['message'],
created_at: Time.now.strftime('%m/%d %H:%M:%S'),
)
end
end
end
route do |r|
r.public unless PRODUCTION
puts "************** #{r.path} *************"
r.hash_branches
r.root do
render_with_games
end
r.on STANDARD_ROUTES do
render_with_games
end
r.on 'game', Integer do |id|
halt(404, 'Game not found') unless (game = Game[id])
halt(400, 'Game has not started yet') if game.status == 'new'
render(game_data: game.to_h(include_actions: true))
end
end
def render_with_games
render(games: Game.home_games(user, **request.params).map(&:to_h))
end
def render(**needs)
return debug(**needs) if request.params['debug'] && !PRODUCTION
script = Snabberb.prerender_script(
'Index',
'App',
'app',
javascript_include_tags: ASSETS.js_tags,
app_route: request.path,
**needs,
)
ASSETS.context.eval(script)
end
def debug(**needs)
needs = Snabberb.wrap(app_route: request.path, **needs)
attach_func = "Opal.$$.App.$attach('app', #{needs})"
<<~HTML
<html>
<head>
<meta charset="utf-8">
<title>18xx.games</title>
</head>
<body>
<div id="app"></div>
#{ASSETS.js_tags}
<script>#{attach_func}</script>
</body>
</html>
HTML
end
def session
return unless (token = request.env['HTTP_AUTHORIZATION'])
@session ||= Session.find(token: token)
end
def user
session&.valid? ? session.user : nil
end
def halt(code, message)
request.halt(code, error: message)
end
def not_authorized!
halt(401, 'You are not authorized to make this request')
end
def publish(channel, limit = nil, **data)
MessageBus.publish(
channel,
data.merge('_client_id': request.params['_client_id']),
max_backlog_size: limit,
)
{}
end
MessageBus.user_id_lookup do |env|
next unless (token = env['HTTP_AUTHORIZATION'])
Session.where(token: token).update(updated_at: Sequel::CURRENT_TIMESTAMP)
nil
end
end