-
-
Notifications
You must be signed in to change notification settings - Fork 171
/
Copy pathRestHandler.cfc
597 lines (548 loc) · 19.2 KB
/
RestHandler.cfc
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
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
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
/**
* Copyright Since 2005 ColdBox Framework by Luis Majano and Ortus Solutions, Corp
* www.ortussolutions.com
* ---
* Base class for all RESTFul event handlers
*
* @author Luis Majano <lmajano@ortussolutions.com>
*/
component extends="EventHandler" {
// Rest handler marker
this.restHandler = true;
// Default REST Security for ColdBox Resources
this.allowedMethods = {
"index" : "GET",
"new" : "GET",
"get" : "GET",
"create" : "POST",
"show" : "GET",
"list" : "GET",
"edit" : "GET",
"update" : "POST,PUT,PATCH",
"delete" : "DELETE"
};
// Do we reset data on errors?
this.resetDataOnError = false;
/**
* Our Rest handler adds a nice around handler that will be active for all handlers
* that leverage it. So it can add uniformity, exception handling, tracking and more.
*
* @event The request context
* @rc The rc reference
* @prc The prc reference
* @targetAction The action UDF to execute
* @eventArguments The original event arguments
*/
function aroundHandler( event, rc, prc, targetAction, eventArguments ){
try {
// start a resource timer
var stime = getTickCount();
// prepare our response object
arguments.event.getResponse();
// prepare argument execution
var actionArgs = {
"event" : arguments.event,
"rc" : arguments.rc,
"prc" : arguments.prc
};
structAppend( actionArgs, arguments.eventArguments );
// Incoming Format Detection
if ( !isNull( arguments.rc.format ) ) {
arguments.prc.response.setFormat( arguments.rc.format );
}
// Execute action
var actionResults = arguments.targetAction( argumentCollection = actionArgs );
}
// Auth Issues
catch ( "InvalidCredentials" e ) {
arguments.exception = e;
this.onAuthenticationFailure( argumentCollection = arguments );
}
// Auth Issues
catch ( "NotAuthorized" e ) {
arguments.exception = e;
this.onAuthenticationFailure( argumentCollection = arguments );
}
// Token Decoding Issues
catch ( "TokenInvalidException" e ) {
arguments.exception = e;
this.onAuthenticationFailure( argumentCollection = arguments );
}
// Validation Exceptions
catch ( "ValidationException" e ) {
arguments.exception = e;
this.onValidationException( argumentCollection = arguments );
}
// Entity Not Found Exceptions
catch ( "EntityNotFound" e ) {
arguments.exception = e;
this.onEntityNotFoundException( argumentCollection = arguments );
}
// Permission Exceptions
catch ( "PermissionDenied" e ) {
arguments.exception = e;
this.onAuthorizationFailure( argumentCollection = arguments );
}
// Record Not Found
catch ( "RecordNotFound" e ) {
arguments.exception = e;
this.onEntityNotFoundException( argumentCollection = arguments );
}
// Global Catch
catch ( Any e ) {
arguments.exception = e;
this.onAnyOtherException( argumentCollection = arguments );
// If in development, let's show the error template
if ( inDebugMode() ) {
rethrow;
}
}
// Development additions
if ( inDebugMode() ) {
arguments.prc.response
.addHeader( "x-current-route", arguments.event.getCurrentRoute() )
.addHeader( "x-current-routed-url", arguments.event.getCurrentRoutedURL() )
.addHeader( "x-current-routed-namespace", arguments.event.getCurrentRoutedNamespace() )
.addHeader( "x-current-event", arguments.event.getCurrentEvent() );
}
// end timer
arguments.prc.response.setResponseTime( getTickCount() - stime );
// Did the controllers set a view to be rendered? If not use renderdata, else just delegate to view.
if (
isNull( local.actionResults )
AND
!arguments.event.getCurrentView().len()
AND
arguments.event.getRenderData().isEmpty()
) {
// Get response data according to error flag
var responseData = (
arguments.prc.response.getError() ? arguments.prc.response.getDataPacket(
reset = this.resetDataOnError
) : arguments.prc.response.getDataPacket()
);
// Magical renderings
event.renderData(
type = arguments.prc.response.getFormat(),
data = responseData,
contentType = arguments.prc.response.getContentType(),
statusCode = arguments.prc.response.getStatusCode(),
location = arguments.prc.response.getLocation(),
isBinary = arguments.prc.response.getBinary(),
jsonCallback = arguments.prc.response.getJsonCallback()
);
}
// Global Response Headers
arguments.prc.response.addHeader( "x-response-time", arguments.prc.response.getResponseTime() );
// Output the response headers
for ( var thisHeader in arguments.prc.response.getHeaders() ) {
arguments.event.setHTTPHeader( name = thisHeader.name, value = thisHeader.value );
}
// If results detected, just return them, controllers requesting to return results
if ( !isNull( local.actionResults ) ) {
return local.actionResults;
}
}
/**
* Implicit action that detects exceptions on your handlers and processes them
*
* @event The request context
* @rc The rc reference
* @prc The prc reference
* @faultAction The action that blew up
* @exception The thrown exception
* @eventArguments The original event arguments
*/
function onError(
event,
rc,
prc,
faultAction = "",
exception = {},
eventArguments = {}
){
// Try to discover exception, if not, hard error
if (
!isNull( arguments.prc.exception ) && (
isNull( arguments.exception ) || structIsEmpty( arguments.exception )
)
) {
arguments.exception = arguments.prc.exception.getExceptionStruct();
}
// If in development and not in testing mode, then show exception template, easier to debug
if ( inDebugMode() && !isInstanceOf( variables.controller, "MockController" ) ) {
throw( object = arguments.exception );
}
// Log Locally
log.error(
"Error in base handler (#arguments.faultAction#): #arguments.exception.message# #arguments.exception.detail#",
{
"_stacktrace" : arguments.exception.stacktrace,
"httpData" : getHTTPRequestData( false )
}
);
// Setup General Error Response
arguments.event
.getResponse()
.setError( true )
.setData( {} )
.addMessage( "Base Handler Application Error: #arguments.exception.message#" )
.setStatusCode( arguments.event.STATUS.INTERNAL_ERROR );
// Development additions Great for Testing
if ( inDebugMode() ) {
prc.response
.setData(
structKeyExists( arguments.exception, "tagContext" ) ? arguments.exception.tagContext : {}
)
.addMessage( "Detail: #arguments.exception.detail#" )
.addMessage( "StackTrace: #arguments.exception.stacktrace#" );
}
// Render Error Out
event.renderData(
type = prc.response.getFormat(),
data = prc.response.getDataPacket( reset = this.resetDataOnError ),
contentType = prc.response.getContentType(),
statusCode = prc.response.getStatusCode(),
location = prc.response.getLocation(),
isBinary = prc.response.getBinary()
);
}
/**
* Action that can be used when validation exceptions ocur. Can be called manually or automatically
* via thrown exceptions in the around handler
*
* @event The request context
* @rc The rc reference
* @prc The prc reference
* @eventArguments The original event arguments
* @exception The thrown exception
*/
function onValidationException( event, rc, prc, eventArguments, exception = {} ){
// Param Exceptions, just in case
param name="arguments.exception.message" default="";
param name="arguments.exception.extendedInfo" default="";
// Announce exception
announce( "onValidationException", { "exception" : arguments.exception } );
// Log it
log.warn( "onValidationException of (#event.getCurrentEvent()#)", arguments.exception?.extendedInfo ?: "" );
// Setup Response
arguments.event
.getResponse()
.setError( true )
.setData(
isJSON( arguments.exception.extendedInfo ) ? deserializeJSON( arguments.exception.extendedInfo ) : ""
)
.addMessage( "Validation exceptions occurred, please see the data" )
.setStatusCode( arguments.event.STATUS.BAD_REQUEST );
// Render Error Out
arguments.event.renderData(
type = arguments.prc.response.getFormat(),
data = arguments.prc.response.getDataPacket( reset = this.resetDataOnError ),
contentType = arguments.prc.response.getContentType(),
statusCode = arguments.prc.response.getStatusCode(),
location = arguments.prc.response.getLocation(),
isBinary = arguments.prc.response.getBinary()
);
}
/**
* Action that can be used when an entity or record is not found. Can be called manually or automatically
* via thrown exceptions in the around handler
*
* @event The request context
* @rc The rc reference
* @prc The prc reference
* @eventArguments The original event arguments
* @exception The thrown exception
*/
function onEntityNotFoundException( event, rc, prc, eventArguments, exception = {} ){
// Param Exceptions, just in case
param name="arguments.exception.message" default="";
param name="arguments.exception.extendedInfo" default="";
// Announce exception
announce( "onEntityNotFoundException", { "exception" : arguments.exception } );
// Log it
log.warn(
"onEntityNotFoundException of (#event.getCurrentEvent()#)",
arguments.exception?.extendedInfo ?: ""
);
// Setup Response
arguments.event
.getResponse()
.setError( true )
.setData( rc.id ?: "" )
.addMessage(
len( exception.message ) ? exception.message : "The record you requested cannot be found in this system"
)
.setStatusCode( arguments.event.STATUS.NOT_FOUND );
// Render Error Out
arguments.event.renderData(
type = arguments.prc.response.getFormat(),
data = arguments.prc.response.getDataPacket( reset = this.resetDataOnError ),
contentType = arguments.prc.response.getContentType(),
statusCode = arguments.prc.response.getStatusCode(),
location = arguments.prc.response.getLocation(),
isBinary = arguments.prc.response.getBinary()
);
}
/**
* Action used when the framework detects and Invalid HTTP method for the action
*
* @event The request context
* @rc The rc reference
* @prc The prc reference
* @faultAction The action that was secured
* @eventArguments The original event arguments
*/
function onInvalidHTTPMethod( event, rc, prc, faultAction, eventArguments ){
// Log it
log.warn(
"InvalidHTTPMethod Execution of (#arguments.faultAction#): #arguments.event.getHTTPMethod()#",
getHTTPRequestData( false )
);
// Setup Response
arguments.event
.getResponse()
.setError( true )
.addMessage(
"InvalidHTTPMethod Execution of (#arguments.faultAction#): #arguments.event.getHTTPMethod()#"
)
.setStatusCode( arguments.event.STATUS.NOT_ALLOWED );
// Render Error Out
arguments.event.renderData(
type = arguments.prc.response.getFormat(),
data = arguments.prc.response.getDataPacket( reset = this.resetDataOnError ),
contentType = arguments.prc.response.getContentType(),
statusCode = arguments.prc.response.getStatusCode(),
location = arguments.prc.response.getLocation(),
isBinary = arguments.prc.response.getBinary()
);
}
/**
* Action used when the original action does not exist in a handler.
*
* @event The request context
* @rc The rc reference
* @prc The prc reference
* @missingAction The missing action
* @eventArguments The original event arguments
*/
function onMissingAction( event, rc, prc, missingAction, eventArguments ){
// Setup Response
arguments.event
.getResponse()
.setError( true )
.addMessage( "Action '#arguments.missingAction#' could not be found" )
.setStatusCode( arguments.event.STATUS.NOT_FOUND );
// Render Error Out
arguments.event.renderData(
type = arguments.prc.response.getFormat(),
data = arguments.prc.response.getDataPacket( reset = this.resetDataOnError ),
contentType = arguments.prc.response.getContentType(),
statusCode = arguments.prc.response.getStatusCode(),
location = arguments.prc.response.getLocation(),
isBinary = arguments.prc.response.getBinary()
);
}
/**
* Action that can be used for authentication failures. You can point to this action from cbsecurity, cbauth, etc or
* call it a-la-carte.
*
* It also monitors cbsecurity convention of validator results for setting error messages into the data packet
*
* @event The request context
* @rc The rc reference
* @prc The prc reference
* @abort Hard abort the request if passed, defaults to false
* @exception The thrown exception
*
* @return 401
*/
function onAuthenticationFailure(
event = getRequestContext(),
rc = getRequestCollection(),
prc = getRequestCollection( private = true ),
abort = false,
exception = {}
){
// Announce exception
announce( "onAuthenticationFailure", { "exception" : arguments.exception } );
// Log it
log.warn(
"onAuthenticationFailure of (#event.getCurrentEvent()#)",
arguments.prc?.cbSecurity_validatorResults?.messages ?: ""
);
// case when the a jwt token was valid, but expired
if (
!isNull( arguments.prc.cbSecurity_validatorResults ) &&
arguments.prc.cbSecurity_validatorResults.messages CONTAINS "expired"
) {
arguments.event
.getResponse()
.setError( true )
.setStatusCode( arguments.event.STATUS.NOT_AUTHENTICATED )
.addMessage( "Expired Authentication Credentials" );
return;
}
arguments.event
.getResponse()
.setError( true )
.setStatusCode( arguments.event.STATUS.NOT_AUTHENTICATED )
.addMessage( "Invalid or Missing Authentication Credentials" );
/**
* When you need a really hard stop to prevent further execution ( use as last resort )
*/
if ( arguments.abort ) {
event.setHTTPHeader( name = "Content-Type", value = "application/json" );
event.setHTTPHeader( statusCode = "#arguments.event.STATUS.NOT_AUTHENTICATED#" );
writeOutput( toJson( prc.response.getDataPacket( reset = this.resetDataOnError ) ) );
flush;
abort;
}
}
/**
* Action that can be used for authorization failures. You can point to this action from cbsecurity, cbauth, etc or
* call it a-la-carte.
*
* It will check for cbsecurity validation results and set the appropriate error messages
*
* @event The request context
* @rc The rc reference
* @prc The prc reference
* @abort Hard abort the request if passed, defaults to false
* @exception The thrown exception
*/
function onAuthorizationFailure(
event = getRequestContext(),
rc = getRequestCollection(),
prc = getRequestCollection( private = true ),
abort = false,
exception = {}
){
// Announce exception
announce( "onAuthorizationFailure", { "exception" : arguments.exception } );
// Log it
log.warn(
"onAuthorizationFailure of (#event.getCurrentEvent()#)",
arguments.prc?.cbSecurity_validatorResults?.messages ?: ""
);
arguments.event
.getResponse()
.setError( true )
.setStatusCode( arguments.event.STATUS.NOT_AUTHORIZED )
.addMessage( "You are not allowed to access this resource" );
// Check for validator results
if ( !isNull( arguments.prc.cbSecurity_validatorResults ) ) {
arguments.prc.response.addMessage( arguments.prc.cbSecurity_validatorResults.messages );
}
/**
* When you need a really hard stop to prevent further execution ( use as last resort )
*/
if ( arguments.abort ) {
event.setHTTPHeader( name = "Content-Type", value = "application/json" );
event.setHTTPHeader( statusCode = "#arguments.event.STATUS.NOT_AUTHORIZED#" );
writeOutput( serializeJSON( prc.response.getDataPacket( reset = this.resetDataOnError ) ) );
flush;
abort;
}
}
/**
* Action for when a route is invalid or not found. Usually you use this in your router
* as a catch all.
*
* <pre>
* // Catch All Resource
* route( "/:anything" ).to( "MyHandler.onInvalidRoute" );
* </pre>
*
* @event The request context
* @rc The rc reference
* @prc The prc reference
*
* @return 404:Not Found
*/
function onInvalidRoute( event, rc, prc ){
arguments.event
.getResponse()
.setError( true )
.setStatusCode( arguments.event.STATUS.NOT_FOUND )
.addMessage( "The resource requested (#event.getCurrentRoutedURL()#) could not be found" );
}
/**
* Action for 'any' exceptions, ie when not caught by previous catch statements
*
* @event The request context
* @rc The rc reference
* @prc The prc reference
* @eventArguments The original event arguments
* @exception The thrown exception
*/
function onAnyOtherException( event, rc, prc, eventArguments, exception = {} ){
// Param due to inconsistencies with safe navigation operators in all CFML engines
param arguments.exception.type = "";
// Handle a convention of on{type}Exception() in your base handler
if (
len( arguments.exception.type ) && structKeyExists( this, "on#arguments.exception.type#Exception" ) && isCustomFunction(
this[ "on#arguments.exception.type#Exception" ]
)
) {
this[ "on#arguments.exception.type#Exception" ]( argumentCollection = arguments );
return;
}
// Log Exception
log.error(
"Error calling #arguments.event.getCurrentEvent()#: #arguments.exception.message# #arguments.exception.detail#",
{
"_stacktrace" : arguments.exception.stacktrace,
"httpData" : getHTTPRequestData( false )
}
);
// Announce exception
announce( "onException", { "exception" : arguments.exception } );
// Setup General Error Response
arguments.prc.response
.setError( true )
.setData(
inDebugMode() ? {
"environment" : {
"currentRoute" : arguments.event.getCurrentRoute(),
"currentRoutedUrl" : arguments.event.getCurrentRoutedUrl(),
"currentEvent" : arguments.event.getCurrentEvent(),
"timestamp" : getIsoTime()
},
"exception" : {
"stack" : arguments.exception.tagContext.map( ( item ) => item.template & ":" & item.line ),
"type" : arguments.exception.type,
"detail" : arguments.exception.detail,
"extendedInfo" : arguments.exception.extendedInfo
}
} : {}
)
.addMessage( "An exception ocurred: #arguments.exception.message#" )
.setStatusCode( arguments.event.STATUS.INTERNAL_ERROR );
}
/**
* Utility method for when an expectation of the request fails ( e.g. an expected parameter is not provided )
* - It will output a 417 status code (event.STATUS.EXPECTATION_FAILED)
* - Add the error flag
* - Add an failure message to the data packet which you can customize
*
* @event The request context
* @rc The rc reference
* @prc The prc reference
* @message The failure message sent in the request package
*
* @return 417:Expectation Failed
*/
function onExpectationFailed(
event = getRequestContext(),
rc = getRequestCollection(),
prc = getRequestCollection( private = true ),
message = "An expectation for the request failed. Could not proceed"
){
arguments.event
.getResponse()
.setError( true )
.setStatusCode( arguments.event.STATUS.EXPECTATION_FAILED )
.addMessage( arguments.message );
}
}