Repository navigation
Expand file tree
/
Copy pathQuick.Core.Mvc.Controller.pas
More file actions
547 lines (454 loc) · 15.5 KB
/
Copy pathQuick.Core.Mvc.Controller.pas
File metadata and controls
547 lines (454 loc) · 15.5 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
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
{ ***************************************************************************
Copyright (c) 2016-2026 Kike Perez
Unit : Quick.Core.Mvc.Controller
Description : Core Mvc Controller
Author : Kike Perez
Version : 1.0
Created : 30/08/2019
Modified : 06/06/2020
This file is part of QuickCore: https://github.com/exilon/QuickCore
***************************************************************************
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*************************************************************************** }
unit Quick.Core.Mvc.Controller;
interface
{$i QuickCore.inc}
uses
{$IFDEF DEBUG_ROUTING}
Quick.Debug.Utils,
{$ENDIF}
System.SysUtils,
Quick.Logger.Intf,
Quick.HttpServer.Types,
Quick.HttpServer.Request,
Quick.HttpServer.Response,
Quick.Core.Mvc.ActionResult,
Quick.Core.Mvc.Context,
Quick.Core.Mvc.Routing,
Quick.Core.Mvc.ActionInvoker,
Quick.Core.Mvc.ViewFeatures,
Quick.Core.Security.Claims;
type
IHttpController = interface
['{D2A3C605-360C-4B6C-844B-5745F97865D9}']
procedure Execute(aRequestContext : TRequestContext; aViewEngine : IViewEngine);
end;
TExecuteEvent = procedure(aRequestContext : TRequestContext) of object;
{$M+}
THttpController = class(TController,IHttpController)
private
fHttpContext : THttpContextBase;
fRequest : IHttpRequest;
fResponse : IHttpResponse;
fRoute : THttpRoute;
fLogger : ILogger;
fOnResultExecuting : TExecuteEvent;
fOnResultExecuted : TExecuteEvent;
fViewData : TViewDataDictionary;
fViewEngine : IViewEngine;
function GetContext: THttpContextBase;
procedure SetContext(const Value: THttpContextBase);
function GetUser: TClaimsPrincipal;
protected
function StatusCode(const aStatusCode : THttpStatusCode; const aStatusText : string = '') : TStatusResult; overload;
function StatusCode(aStatusCode : Integer; const aStatusText : string = '') : TStatusResult; overload;
function Ok(const aStatusText : string = '') : TStatusResult;
function Accepted(const aStatusText : string = '') : TStatusResult;
function BadRequest(const aStatusText : string = '') : TStatusResult;
function NotFound(const aStatusText : string = '') : TStatusResult;
function Forbid(const aStatusText : string = '') : TStatusResult;
function Unauthorized(const aStatusText : string = '') : TStatusResult;
function Redirect(const aURL : string) : TRedirectResult;
function RedirectPermanent(const aURL : string) : TRedirectResult;
function Content(const aContentText : string) : TContentResult;
function Json(aObject: TObject; aOnlyPublishedProperties : Boolean = False): TJsonResult; overload;
function Json(const aJsonText : string): TJsonResult; overload;
function View(const aView : string = '') : TViewResult;
{ Resource-based authorization helper.
Evaluates the named policy against the current User and the supplied
resource object. Returns True when the policy succeeds.
Requires IAuthorizationService to be registered via AddAuthorization(). }
function AuthorizeResource(aResource: TObject; const aPolicyName: string): Boolean; overload;
public
destructor Destroy; override;
//property Resolver : IDependencyResolver read fResolver;
property Route : THttpRoute read fRoute;
property Request : IHttpRequest read fRequest;
property Response : IHttpResponse read fResponse;
property ViewData : TViewDataDictionary read fViewData write fViewData;
property Logger : ILogger read fLogger;
property HttpContext : THttpContextBase read GetContext write SetContext;
property User : TClaimsPrincipal read GetUser;
property OnResultExecuting : TExecuteEvent read fOnResultExecuting write fOnResultExecuting;
property OnResultExecuted : TExecuteEvent read fOnResultExecuted write fOnResultExecuted;
//property OnException
//property OnAuthorization
procedure Execute(aRequestContext : TRequestContext; aViewEngine : IViewEngine); virtual;
end;
{$M-}
THttpControllerClass = class of THttpController;
{ Attributes }
ActionName = class(TCustomAttribute)
private
fName : string;
public
constructor Create(const aName: string);
property Name : string read fName;
end;
NonAction = class(TCustomAttribute);
TMethodVerbAttribute = class(TCustomAttribute)
private
fRoute : string;
public
constructor Create(const aRoute : string = '');
property Route : string read fRoute;
end;
HttpGet = class(TMethodVerbAttribute);
HttpPost = class(TMethodVerbAttribute);
HttpPut = class(TMethodVerbAttribute);
HttpDelete = class(TMethodVerbAttribute);
HttpMethod = class(TCustomAttribute)
private
fName : string;
public
constructor Create(const aName: string);
property Name : string read fName;
end;
AcceptVerbs = class(TCustomAttribute)
private
fMethodVerbs : TMethodVerbs;
public
constructor Create(const aVerbs: TMethodVerbs);
property Verbs : TMethodVerbs read fMethodVerbs;
end;
Route = class(TCustomAttribute)
private
fURL : string;
public
constructor Create(const aURL: string);
property URL : string read fURL;
end;
Authorize = class(TCustomAttribute)
private
fRoles : string;
public
constructor Create(const aRoles : string = '');
property Roles : string read fRoles;
end;
AuthorizePolicy = class(TCustomAttribute)
private
fName : string;
public
constructor Create(const aName : string);
property Name : string read fName;
end;
AllowAnonymous = class(TCustomAttribute);
OutputCache = class(TCustomAttribute)
private
fDuration : Integer;
public
constructor Create(aDurationMS : Integer);
property Duration : Integer read fDuration;
end;
FromBody = class(TCustomAttribute);
FromQuery = class(TCustomAttribute)
private
fName : string;
public
constructor Create(const aName : string = '');
property Name : string read fName;
end;
FromHeader = class(TCustomAttribute)
private
fName : string;
public
constructor Create(const aName : string = '');
property Name : string read fName;
end;
/// <summary>Bind a controller constructor parameter from a named (keyed) DI registration.
/// Equivalent to .NET 8 [FromKeyedServices("key")].
/// Example: constructor Create([FromKeyedServices('secondary')] aRepo: IRepository);</summary>
FromKeyedServices = class(TCustomAttribute)
private
fKey : string;
public
constructor Create(const aKey : string);
property Key : string read fKey;
end;
ApiController = class(TCustomAttribute);
(* Applied to a controller to declare which API version(s) it implements.
Use with [Route('api/v<major>/[controller]')] for URL-based versioning. *)
ApiVersion = class(TCustomAttribute)
private
fVersion : string;
fDeprecated : Boolean;
public
constructor Create(const aVersion : string; aDeprecated : Boolean = False);
property Version : string read fVersion;
property Deprecated : Boolean read fDeprecated;
end;
procedure RegisterController(aHttpController : THttpControllerClass);
var
RegisteredControllers : TArray<THttpControllerClass>;
implementation
uses
RTTI,
Quick.Core.Mvc.Filters,
Quick.Core.Security.Authorization;
procedure RegisterController(aHttpController : THttpControllerClass);
begin
RegisteredControllers := RegisteredControllers + [aHttpController];
end;
{ ApiVersion }
constructor ApiVersion.Create(const aVersion : string; aDeprecated : Boolean);
begin
fVersion := aVersion;
fDeprecated := aDeprecated;
end;
{ FromQuery }
constructor FromQuery.Create(const aName : string);
begin
fName := aName;
end;
{ FromHeader }
constructor FromHeader.Create(const aName : string);
begin
fName := aName;
end;
{ FromKeyedServices }
constructor FromKeyedServices.Create(const aKey : string);
begin
fKey := aKey;
end;
{ TMethodVerbAttribute }
constructor TMethodVerbAttribute.Create(const aRoute: string);
begin
fRoute := aRoute;
end;
{ THttpMethod }
constructor HttpMethod.Create(const aName: string);
begin
fName := Name;
end;
{ THttpPath }
constructor Route.Create(const aURL: string);
begin
fURL := aURL;
end;
{ OutputCache }
constructor OutputCache.Create(aDurationMS: Integer);
begin
fDuration := aDurationMS;
end;
{ ActionName }
constructor ActionName.Create(const aName: string);
begin
fName := aName;
end;
{ AcceptVerbs }
constructor AcceptVerbs.Create(const aVerbs: TMethodVerbs);
begin
fMethodVerbs := aVerbs;
end;
{ THttpController }
procedure THttpController.Execute(aRequestContext : TRequestContext; aViewEngine : IViewEngine);
var
ctx : TRttiContext;
rtype : TRttiType;
rmethod : TRttiMethod;
attr : TCustomAttribute;
filterAttr : TActionFilterAttribute;
execCtx : TActionExecutingContext;
doneCtx : TActionExecutedContext;
actionError : Exception;
actionContext : TActionContext;
begin
{$IFDEF DEBUG_ROUTING}
TDebugger.Enter(Self,Format('Execute (%s)',[aRequestContext.HttpContext.Request.URL])).TimeIt;
{$ENDIF}
if Assigned(fOnResultExecuting) then fOnResultExecuting(aRequestContext);
fRequest := aRequestContext.HttpContext.Request;
fHttpContext := aRequestContext.HttpContext;
fResponse := aRequestContext.HttpContext.Response;
fRoute := aRequestContext.HttpContext.Route;
fViewData := TViewDataDictionary.Create;
fViewEngine := aViewEngine;
// --- collect action filters from controller class + action method ---
execCtx := TActionExecutingContext.Create(aRequestContext);
doneCtx := nil;
actionError := nil;
rtype := nil;
rmethod := nil;
try
rtype := ctx.GetType(aRequestContext.HttpContext.Route.ControllerClass);
if rtype <> nil then
rmethod := rtype.GetMethod(aRequestContext.HttpContext.Route.ActionMethodName);
// OnActionExecuting: controller-level filters first, then method-level
if rtype <> nil then
for attr in rtype.GetAttributes do
if attr is TActionFilterAttribute then
begin
filterAttr := TActionFilterAttribute(attr);
filterAttr.OnActionExecuting(execCtx);
if execCtx.Canceled then Break;
end;
if (not execCtx.Canceled) and (rmethod <> nil) then
for attr in rmethod.GetAttributes do
if attr is TActionFilterAttribute then
begin
filterAttr := TActionFilterAttribute(attr);
filterAttr.OnActionExecuting(execCtx);
if execCtx.Canceled then Break;
end;
if execCtx.Canceled then
begin
// short-circuit: execute the assigned result if any
if Assigned(execCtx.Result) then
begin
actionContext := TActionContext.Create(aRequestContext.HttpContext, aRequestContext.RouteData);
try
execCtx.Result.ExecuteResult(actionContext);
finally
actionContext.Free;
end;
end;
end
else
begin
// execute controller action method
try
TActionInvoker.Invoke(Self, aRequestContext);
except
on E : Exception do
begin
actionError := E;
raise;
end;
end;
end;
finally
// OnActionExecuted: method-level first, then controller-level
doneCtx := TActionExecutedContext.Create(aRequestContext, actionError);
try
if rmethod <> nil then
for attr in rmethod.GetAttributes do
if attr is TActionFilterAttribute then
TActionFilterAttribute(attr).OnActionExecuted(doneCtx);
if rtype <> nil then
for attr in rtype.GetAttributes do
if attr is TActionFilterAttribute then
TActionFilterAttribute(attr).OnActionExecuted(doneCtx);
finally
doneCtx.Free;
execCtx.Free;
end;
end;
if Assigned(fOnResultExecuted) then fOnResultExecuted(aRequestContext);
end;
function THttpController.GetContext: THttpContextBase;
begin
Result := fHttpContext;
end;
procedure THttpController.SetContext(const Value: THttpContextBase);
begin
fHttpContext := Value;
end;
function THttpController.GetUser: TClaimsPrincipal;
begin
if fHttpContext <> nil then Result := fHttpContext.User
else Result := nil;
end;
function THttpController.AuthorizeResource(aResource: TObject; const aPolicyName: string): Boolean;
var
authService : IAuthorizationService;
authResult : TAuthorizationResult;
begin
if fHttpContext = nil then Exit(False);
authService := fHttpContext.RequestServices.GetService<IAuthorizationService>;
if authService = nil then
raise EAuthorizationError.Create('IAuthorizationService is not registered. Call services.Extension<TAuthorizationServiceExtension>.AddAuthorization(...)');
authResult := authService.Authorize(fHttpContext.User, aResource, aPolicyName);
Result := authResult.Succeeded;
end;
function THttpController.Json(aObject: TObject; aOnlyPublishedProperties : Boolean = False): TJsonResult;
begin
Result := TJsonResult.Create(aObject,aOnlyPublishedProperties);
end;
function THttpController.Json(const aJsonText: string): TJsonResult;
begin
Result := TJsonResult.Create(aJsonText);
end;
function THttpController.StatusCode(const aStatusCode: THttpStatusCode; const aStatusText: string): TStatusResult;
begin
Result := TStatusResult.Create(Integer(aStatusCode),aStatusText);
end;
function THttpController.StatusCode(aStatusCode: Integer; const aStatusText: string): TStatusResult;
begin
Result := TStatusResult.Create(aStatusCode,aStatusText);
end;
function THttpController.Ok(const aStatusText: string): TStatusResult;
begin
Result := TStatusResult.Create(200,aStatusText);
end;
function THttpController.Accepted(const aStatusText: string): TStatusResult;
begin
Result := TStatusResult.Create(202,aStatusText);
end;
function THttpController.NotFound(const aStatusText: string): TStatusResult;
begin
Result := TStatusResult.Create(404,aStatusText);
end;
function THttpController.BadRequest(const aStatusText: string): TStatusResult;
begin
Result := TStatusResult.Create(400,aStatusText);
end;
function THttpController.Forbid(const aStatusText: string): TStatusResult;
begin
Result := TStatusResult.Create(403,aStatusText);
end;
function THttpController.Unauthorized(const aStatusText: string): TStatusResult;
begin
Result := TStatusResult.Create(401,aStatusText);
end;
function THttpController.Content(const aContentText: string): TContentResult;
begin
Result := TContentResult.Create(aContentText);
end;
destructor THttpController.Destroy;
begin
fViewData.Free;
inherited;
end;
function THttpController.Redirect(const aURL: string): TRedirectResult;
begin
Result := TRedirectResult.Create(302,aURL);
end;
function THttpController.RedirectPermanent(const aURL: string): TRedirectResult;
begin
Result := TRedirectResult.Create(301,aURL);
end;
function THttpController.View(const aView: string = ''): TViewResult;
begin
Result := TViewResult.Create(aView);
Result.ViewData := fViewData;
Result.ViewEngine := fViewEngine;
end;
{ Authorize }
constructor Authorize.Create(const aRoles: string = '');
begin
fRoles := aRoles;
end;
{ AuthorizePolicy }
constructor AuthorizePolicy.Create(const aName: string);
begin
fName := aName;
end;
end.