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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
|
# File 'lib/sinja.rb', line 23
def self.registered(app)
abort "Sinatra::JSONAPI (Sinja) is already registered on #{app}!" \
if app.respond_to?(:_sinja)
app.register Sinatra::Namespace
app.disable :protection, :show_exceptions, :static
app.set :_sinja, Sinja::Config.new
app.set :_resource_config, nil
app.set :actions do |*actions|
condition do
actions.each do |action|
raise ForbiddenError, 'You are not authorized to perform this action' \
unless can?(action)
raise MethodNotAllowedError, 'Action or method not implemented or supported' \
unless respond_to?(action)
end
true
end
end
app.set :qcaptures do |*index|
condition do
@qcaptures ||= []
index.to_h.all? do |key, subkeys|
key = key.to_s
params[key].is_a?(Hash) && params[key].any? && Array(subkeys).all? do |subkey|
subkey = subkey.to_s
@qcaptures << params[key].delete(subkey) if params[key].key?(subkey)
end.tap do |ok|
params.delete(key) if ok && params[key].empty?
end
end
end
end
app.set :qparams do |*allow_params|
allow_params = allow_params.to_set
abort "Unexpected query parameter(s) in route definiton" \
unless allow_params.subset?(settings._sinja.query_params.keys.to_set)
condition do
params.each do |key, value|
key = key.to_sym
next if !env['rack.request.query_hash'].key?(key.to_s) ||
settings._sinja.query_params.fetch(key, BasicObject).nil?
raise BadRequestError, "`#{key}' query parameter not allowed" \
unless allow_params.include?(key)
next if env['sinja.normalized'] == params.object_id
if value.instance_of?(String) && settings._sinja.query_params[key] != String
params[key.to_s] = value.split(',')
elsif !value.is_a?(settings._sinja.query_params[key])
raise BadRequestError, "`#{key}' query parameter malformed"
end
end
return true if env['sinja.normalized'] == params.object_id
settings._sinja.query_params.each do |key, klass|
next if klass.nil?
if respond_to?("normalize_#{key}_params")
params[key.to_s] = send("normalize_#{key}_params")
else
params[key.to_s] ||= klass.new
end
end
env['sinja.normalized'] = params.object_id
end
end
app.set(:on) { |block| condition(&block) }
app.mime_type :api_json, MIME_TYPE
app.helpers Helpers::Serializers do
def allow(h={})
s = Set.new
h.each do |method, actions|
s << method if Array(actions).all?(&method(:respond_to?))
end
'Allow'=>s.map(&:upcase).join(',')
end
def attributes
dedasherize_names(data.fetch(:attributes, {}))
end
if method_defined?(:bad_request?)
def bad_request?
false
end
end
def can?(action)
roles = settings._resource_config[:resource].fetch(action, {})[:roles]
roles.nil? || roles.empty? || roles.intersect?(role)
end
def content?
request.body.respond_to?(:size) && request.body.size > 0 || begin
request.body.rewind
request.body.read(1)
end
end
def data
@data ||= {}
@data[request.path] ||= begin
deserialize_request_body.fetch(:data)
rescue NoMethodError, KeyError
raise BadRequestError, 'Malformed {json:api} request payload'
end
end
def normalize_filter_params
return {} unless params[:filter]&.any?
raise BadRequestError, "Unsupported `filter' query parameter(s)" \
unless respond_to?(:filter)
params[:filter].map do |k, v|
[dedasherize(k).to_sym, v]
end.to_h
end
def filter_by?(action)
return if params[:filter].empty?
filter = params[:filter].map { |k, v| [k.to_sym, v] }.to_h
filter_by = settings.resource_config[action][:filter_by]
return filter if filter_by.empty? || filter_by.superset?(filter.keys.to_set)
raise BadRequestError, "Invalid `filter' query parameter(s)"
end
def normalize_sort_params
return {} unless params[:sort]&.any?
raise BadRequestError, "Unsupported `sort' query parameter(s)" \
unless respond_to?(:sort)
params[:sort].map do |k|
dir = k.sub!(/^-/, '') ? :desc : :asc
[dedasherize(k).to_sym, dir]
end.to_h
end
def sort_by?(action)
return if params[:sort].empty?
sort = params[:sort].map { |k, v| [k.to_sym, v] }.to_h
sort_by = settings.resource_config[action][:sort_by]
return sort if sort_by.empty? || sort_by.superset?(sort.keys.to_set)
raise BadRequestError, "Invalid `sort' query parameter(s)"
end
def normalize_page_params
return {} unless params[:page]&.any?
raise BadRequestError, "Unsupported `page' query parameter(s)" \
unless respond_to?(:page)
params[:page].map do |k, v|
[dedasherize(k).to_sym, v]
end.to_h
end
def page_using?
return if params[:page].empty?
page = params[:page].map { |k, v| [k.to_sym, v] }.to_h
return page if (page.keys - settings._sinja.page_using.keys).empty?
raise BadRequestError, "Invalid `page' query parameter(s)"
end
def filter_sort_page?(action)
return enum_for(__callee__, action) unless block_given?
if filter = filter_by?(action) then yield :filter, filter end
if sort = sort_by?(action) then yield :sort, sort end
if page = page_using? then yield :page, page end
end
def filter_sort_page(collection, opts)
collection = filter(collection, opts[:filter]) if opts.key?(:filter)
collection = sort(collection, opts[:sort]) if opts.key?(:sort)
collection, = page(collection, opts[:page]) if opts.key?(:page)
return respond_to?(:finalize) ? finalize(collection) : collection,
end
def halt(code, body=nil)
if exception_class = ERROR_CODES[code]
raise exception_class, body
elsif (400...600).include?(code.to_i)
raise HttpError.new(code.to_i, body)
else
super
end
end
def sideloaded?
env.key?('sinja.passthru')
end
def role
nil
end
def role?(*roles)
Roles[*roles].intersect?(role)
end
def sanity_check!(resource_name, id=nil)
raise ConflictError, 'Resource type in payload does not match endpoint' \
unless data[:type] && data[:type].to_sym == resource_name
raise ConflictError, 'Resource ID in payload does not match endpoint' \
unless id.nil? || data[:id] && data[:id].to_s == id.to_s
end
def transaction
yield
end
end
app.before do
unless sideloaded?
raise NotAcceptableError unless request.preferred_type.entry == MIME_TYPE || request.options?
raise UnsupportedTypeError if content? && (
request.media_type != MIME_TYPE || request.media_type_params.keys.any? { |k| k != 'charset' }
)
end
content_type :api_json
end
app.after do
body serialize_response_body if response.successful?
end
app.not_found do
serialize_errors
end
app.error 400...600 do
serialize_errors
end
app.error StandardError do
env['sinatra.error'].tap do |e|
boom =
if settings._sinja.not_found_exceptions.any?(&e.method(:is_a?))
NotFoundError.new(e.message) unless e.instance_of?(NotFoundError)
elsif settings._sinja.conflict_exceptions.any?(&e.method(:is_a?))
ConflictError.new(e.message) unless e.instance_of?(ConflictError)
elsif settings._sinja.validation_exceptions.any?(&e.method(:is_a?))
UnprocessibleEntityError.new(settings._sinja.validation_formatter.(e)) unless e.instance_of?(UnprocessibleEntityError)
end
handle_exception!(boom) if boom end
serialize_errors
end
end
|