Repository navigation
Expand file tree
/
Copy pathServiceMetadata.cs
More file actions
1071 lines (888 loc) · 40.8 KB
/
Copy pathServiceMetadata.cs
File metadata and controls
1071 lines (888 loc) · 40.8 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
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
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using ServiceStack.Auth;
using ServiceStack.Configuration;
using ServiceStack.DataAnnotations;
using ServiceStack.FluentValidation;
using ServiceStack.NativeTypes;
using ServiceStack.NativeTypes.CSharp;
using ServiceStack.Text;
using ServiceStack.Web;
namespace ServiceStack.Host
{
public class ServiceMetadata
{
public ServiceMetadata(List<RestPath> restPaths)
{
this.restPaths = restPaths;
this.RequestTypes = new HashSet<Type>();
this.ServiceTypes = new HashSet<Type>();
this.ResponseTypes = new HashSet<Type>();
this.OperationsMap = new Dictionary<Type, Operation>();
this.OperationsResponseMap = new Dictionary<Type, Operation>();
this.OperationNamesMap = new Dictionary<string, Operation>();
this.ForceInclude = new HashSet<Type>();
}
public Dictionary<Type, Operation> OperationsMap { get; protected set; }
public Dictionary<Type, Operation> OperationsResponseMap { get; protected set; }
public Dictionary<string, Operation> OperationNamesMap { get; protected set; }
public HashSet<Type> RequestTypes { get; protected set; }
public HashSet<Type> ServiceTypes { get; protected set; }
public HashSet<Type> ResponseTypes { get; protected set; }
private readonly List<RestPath> restPaths;
public Dictionary<Type, List<Action<Operation>>> ConfigureOperations { get; protected set; } = new();
public IEnumerable<Operation> Operations => OperationsMap.Values;
public HashSet<Type> ForceInclude { get; set; }
public void Add(Type serviceType, Type requestType, Type responseType)
{
if (requestType.IsArray) //Custom AutoBatched requests
{
this.ServiceTypes.Add(serviceType);
return;
}
this.ServiceTypes.Add(serviceType);
this.RequestTypes.Add(requestType);
var restrictTo = requestType.FirstAttribute<RestrictAttribute>()
?? serviceType.FirstAttribute<RestrictAttribute>();
var reqFilterAttrs = new[] { requestType, serviceType }
.SelectMany(x => x.AllAttributes().OfType<IRequestFilterBase>()).ToList();
var resFilterAttrs = (responseType != null ? new[] { responseType, serviceType } : new[] { serviceType })
.SelectMany(x => x.AllAttributes().OfType<IResponseFilterBase>()).ToList();
var authAttrs = reqFilterAttrs.OfType<AuthenticateAttribute>().ToList();
var actions = serviceType.GetRequestActions(requestType);
var actionUpperNames = actions.Select(x => x.NameUpper).Distinct().ToList();
authAttrs.AddRange(actions.SelectMany(x => x.AllAttributes<AuthenticateAttribute>()));
var tagAttrs = requestType.AllAttributes<TagAttribute>().ToList();
var operation = new Operation
{
ServiceType = serviceType,
RequestType = requestType,
ResponseType = responseType,
RestrictTo = restrictTo,
Actions = actionUpperNames,
Method = ServiceClientUtils.GetHttpMethod(requestType)
?? actionUpperNames.FirstOrDefault(x => x != "ANY")
?? HttpMethods.Post,
Routes = new List<RestPath>(),
RequestFilterAttributes = reqFilterAttrs,
ResponseFilterAttributes = resFilterAttrs,
RequiresAuthentication = authAttrs.Count > 0,
RequiredRoles = authAttrs.OfType<RequiredRoleAttribute>().SelectMany(x => x.RequiredRoles).ToList(),
RequiresAnyRole = authAttrs.OfType<RequiresAnyRoleAttribute>().SelectMany(x => x.RequiredRoles).ToList(),
RequiredPermissions = authAttrs.OfType<RequiredPermissionAttribute>().SelectMany(x => x.RequiredPermissions).ToList(),
RequiresAnyPermission = authAttrs.OfType<RequiresAnyPermissionAttribute>().SelectMany(x => x.RequiredPermissions).ToList(),
Tags = tagAttrs,
};
this.OperationsMap[requestType] = operation;
this.OperationNamesMap[operation.Name.ToLowerInvariant()] = operation;
if (responseType != null)
{
this.ResponseTypes.Add(responseType);
this.OperationsResponseMap[responseType] = operation;
}
//Only count non-core ServiceStack Services, i.e. defined outside of ServiceStack.dll or Swagger
var nonCoreServicesCount = OperationsMap.Values
.Count(x => x.ServiceType.Assembly != typeof(Service).Assembly
&& x.ServiceType.FullName != "ServiceStack.Api.OpenApi.OpenApiService"
&& x.ServiceType.Name != "__AutoQueryServices"
&& x.ServiceType.Name != "__AutoQueryDataServices");
LicenseUtils.AssertValidUsage(LicenseFeature.ServiceStack, QuotaType.Operations, nonCoreServicesCount);
}
public void AfterInit()
{
foreach (var restPath in restPaths)
{
if (!OperationsMap.TryGetValue(restPath.RequestType, out var operation))
continue;
operation.Routes.Add(restPath);
}
foreach (var entry in ConfigureOperations)
{
if (!OperationsMap.TryGetValue(entry.Key, out var op))
continue;
foreach (var configure in entry.Value)
{
configure(op);
}
}
}
readonly HashSet<Assembly> excludeAssemblies = new HashSet<Assembly>
{
typeof(string).Assembly, //mscorelib
typeof(Uri).Assembly, //System
typeof(ServiceStackHost).Assembly, //ServiceStack
typeof(UrnId).Assembly, //ServiceStack.Common
typeof(ErrorResponse).Assembly, //ServiceStack.Interfaces
};
public List<Assembly> GetOperationAssemblies()
{
var assemblies = Operations
.SelectMany(x => x.GetAssemblies())
.Where(x => !excludeAssemblies.Contains(x));
return assemblies.ToList();
}
public List<OperationDto> GetOperationDtos()
{
return OperationsMap.Values
.Map(x => x.ToOperationDto())
.OrderBy(x => x.Name)
.ToList();
}
public List<Operation> GetOperationsByTag(string tag) =>
Operations.Where(x => x.Tags.Any(t => t.Name == tag)).ToList();
public List<Operation> GetOperationsByTags(string[] tags) =>
Operations.Where(x => x.Tags.Any(t => Array.IndexOf(tags, t.Name) >= 0)).ToList();
public Operation GetOperation(Type requestType)
{
if (requestType == null)
return null;
OperationsMap.TryGetValue(requestType, out var op);
return op;
}
public List<ActionMethod> GetImplementedActions(Type serviceType, Type requestType)
{
if (!typeof(IService).IsAssignableFrom(serviceType))
throw new NotSupportedException("All Services must implement IService");
return serviceType.GetActions()
.Where(x => x.GetParameters()[0].ParameterType == requestType)
.ToList();
}
public Type GetOperationType(string operationTypeName)
{
var opName = operationTypeName.ToLowerInvariant();
if (!OperationNamesMap.TryGetValue(opName, out var operation))
{
var arrayPos = opName.LastIndexOf('[');
if (arrayPos >= 0)
{
opName = opName.Substring(0, arrayPos);
OperationNamesMap.TryGetValue(opName, out operation);
return operation?.RequestType.MakeArrayType();
}
}
return operation?.RequestType;
}
public Type GetServiceTypeByRequest(Type requestType)
{
OperationsMap.TryGetValue(requestType, out var operation);
return operation?.ServiceType;
}
public Type GetServiceTypeByResponse(Type responseType)
{
OperationsResponseMap.TryGetValue(responseType, out var operation);
return operation?.ServiceType;
}
public Type GetResponseTypeByRequest(Type requestType)
{
OperationsMap.TryGetValue(requestType, out var operation);
return operation?.ResponseType;
}
public List<Type> GetAllOperationTypes()
{
var allTypes = new List<Type>(RequestTypes);
foreach (var responseType in ResponseTypes)
{
allTypes.AddIfNotExists(responseType);
}
return allTypes;
}
public List<string> GetAllOperationNames()
{
return Operations.Select(x => x.RequestType.GetOperationName()).OrderBy(operation => operation).ToList();
}
public List<string> GetOperationNamesForMetadata(IRequest httpReq)
{
return Operations
.Where(x => !x.RequestType.ExcludesFeature(Feature.Metadata) || x.RequestType.ForceInclude())
.Select(x => x.RequestType.GetOperationName()).OrderBy(operation => operation).ToList();
}
public List<string> GetOperationNamesForMetadata(IRequest httpReq, Format format)
{
var formatRequestAttr = format.ToRequestAttribute();
return Operations
.Where(x => !x.RequestType.ExcludesFeature(Feature.Metadata) && x.RestrictTo.CanShowTo(formatRequestAttr) || x.RequestType.ForceInclude())
.Select(x => x.RequestType.GetOperationName()).OrderBy(operation => operation).ToList();
}
public bool IsAuthorized(Operation operation, IRequest req, IAuthSession session)
{
if (HostContext.HasValidAuthSecret(req))
return true;
if (operation.RequiresAuthentication && !session.IsAuthenticated)
return false;
var authRepo = HostContext.AppHost.GetAuthRepository(req);
using (authRepo as IDisposable)
{
var allRoles = session.GetRoles(authRepo);
if (!operation.RequiredRoles.IsEmpty() && !operation.RequiredRoles.All(allRoles.Contains))
return false;
var allPerms = session.GetPermissions(authRepo);
if (!operation.RequiredPermissions.IsEmpty() && !operation.RequiredPermissions.All(allPerms.Contains))
return false;
if (!operation.RequiresAnyRole.IsEmpty() && !operation.RequiresAnyRole.Any(allRoles.Contains))
return false;
if (!operation.RequiresAnyPermission.IsEmpty() && !operation.RequiresAnyPermission.Any(allPerms.Contains))
return false;
return true;
}
}
public async Task<bool> IsAuthorizedAsync(Operation operation, IRequest req, IAuthSession session)
{
if (HostContext.HasValidAuthSecret(req))
return true;
if (operation.RequiresAuthentication && !session.IsAuthenticated)
return false;
var authRepo = HostContext.AppHost.GetAuthRepositoryAsync(req);
await using (authRepo as IAsyncDisposable)
{
var allRoles = await session.GetRolesAsync(authRepo).ConfigAwait();
if (!operation.RequiredRoles.IsEmpty() && !operation.RequiredRoles.All(allRoles.Contains))
return false;
var allPerms = await session.GetPermissionsAsync(authRepo).ConfigAwait();
if (!operation.RequiredPermissions.IsEmpty() && !operation.RequiredPermissions.All(allPerms.Contains))
return false;
if (!operation.RequiresAnyRole.IsEmpty() && !operation.RequiresAnyRole.Any(allRoles.Contains))
return false;
if (!operation.RequiresAnyPermission.IsEmpty() && !operation.RequiresAnyPermission.Any(allPerms.Contains))
return false;
return true;
}
}
public bool IsVisible(IRequest httpReq, Operation operation)
{
if (HostContext.Config is { EnableAccessRestrictions: false } || operation.RequestType.ForceInclude())
return true;
if (operation.RequestType.ExcludesFeature(Feature.Metadata))
return false;
if (operation.RestrictTo == null) return true;
//Less fine-grained on /metadata pages. Only check Network and Format
var reqAttrs = httpReq.GetAttributes();
var showToNetwork = CanShowToNetwork(operation.RestrictTo, reqAttrs);
return showToNetwork;
}
public bool IsVisible(IRequest httpReq, Type requestType)
{
if (HostContext.Config is { EnableAccessRestrictions: false })
return true;
var operation = HostContext.Metadata.GetOperation(requestType);
return operation == null || IsVisible(httpReq, operation);
}
public bool IsVisible(IRequest httpReq, Format format, string operationName)
{
if (HostContext.Config is { EnableAccessRestrictions: false })
return true;
OperationNamesMap.TryGetValue(operationName.ToLowerInvariant(), out var operation);
if (operation == null) return false;
if (operation.RequestType.ForceInclude())
return true;
if (operation.RequestType.ExcludesFeature(Feature.Metadata))
return false;
var canCall = HasImplementation(operation, format);
if (!canCall) return false;
var isVisible = IsVisible(httpReq, operation);
if (!isVisible) return false;
if (operation.RestrictTo == null) return true;
var allowsFormat = operation.RestrictTo.CanShowTo((RequestAttributes)(long)format);
return allowsFormat;
}
public bool CanAccess(IRequest httpReq, Format format, string operationName)
{
var reqAttrs = httpReq.GetAttributes();
return CanAccess(reqAttrs, format, operationName);
}
public bool CanAccess(RequestAttributes reqAttrs, Format format, string operationName)
{
if (HostContext.Config is { EnableAccessRestrictions: false })
return true;
OperationNamesMap.TryGetValue(operationName.ToLowerInvariant(), out var operation);
if (operation == null)
return false;
var canCall = HasImplementation(operation, format);
if (!canCall)
return false;
if (operation.RestrictTo == null || operation.RequestType.ForceInclude())
return true;
var allow = operation.RestrictTo.HasAccessTo(reqAttrs);
if (!allow)
return false;
var allowsFormat = operation.RestrictTo.HasAccessTo((RequestAttributes)(long)format);
return allowsFormat;
}
public bool CanAccess(Format format, string operationName)
{
if (HostContext.Config is { EnableAccessRestrictions: false })
return true;
OperationNamesMap.TryGetValue(operationName.ToLowerInvariant(), out var operation);
if (operation == null)
return false;
var canCall = HasImplementation(operation, format);
if (!canCall)
return false;
if (operation.RestrictTo == null || operation.RequestType.ForceInclude())
return true;
var allowsFormat = operation.RestrictTo.HasAccessTo((RequestAttributes)(long)format);
return allowsFormat;
}
public bool HasImplementation(Operation operation, Format format)
{
if (format == Format.Soap11 || format == Format.Soap12)
{
if (operation.Actions == null) return false;
return operation.Actions.Contains("POST")
|| operation.Actions.Contains(ActionContext.AnyAction);
}
return true;
}
private static bool CanShowToNetwork(RestrictAttribute restrictTo, RequestAttributes reqAttrs)
{
if (reqAttrs.IsLocalhost())
return restrictTo.CanShowTo(RequestAttributes.Localhost)
|| restrictTo.CanShowTo(RequestAttributes.LocalSubnet);
return restrictTo.CanShowTo(
reqAttrs.IsLocalSubnet()
? RequestAttributes.LocalSubnet
: RequestAttributes.External);
}
private HashSet<Type> allDtos;
public HashSet<Type> GetAllDtos()
{
if (allDtos != null)
return allDtos;
var to = new HashSet<Type>();
var ops = OperationsMap.Values;
foreach (var op in ops)
{
AddReferencedTypes(to, op.RequestType);
AddReferencedTypes(to, op.ResponseType);
}
return allDtos = to;
}
private Dictionary<string, Type> dtoTypesMap;
private HashSet<string> duplicateTypeNames;
public Type FindDtoType(string typeName)
{
var opType = GetOperationType(typeName ?? throw new ArgumentNullException(nameof(typeName)));
if (opType != null)
return opType;
if (dtoTypesMap == null)
{
var typesMap = new Dictionary<string, Type>();
duplicateTypeNames = new HashSet<string>();
foreach (var dto in GetAllDtos())
{
if (typesMap.ContainsKey(dto.Name))
{
duplicateTypeNames.Add(dto.Name);
continue;
}
typesMap[dto.Name] = dto;
}
dtoTypesMap = typesMap;
}
if (duplicateTypeNames.Contains(typeName))
throw new Exception($"There are multiple DTO Types named '{typeName}'");
dtoTypesMap.TryGetValue(typeName, out var dtoType);
return dtoType;
}
public RestPath FindRoute(string pathInfo, string method = HttpMethods.Get)
{
var route = RestHandler.FindMatchingRestPath(method, pathInfo, out _);
return (RestPath)route;
}
public object CreateRequestFromUrl(string relativeOrAbsoluteUrl, string method = HttpMethods.Get)
{
var relativeUrl = relativeOrAbsoluteUrl.StartsWith("http:")
|| relativeOrAbsoluteUrl.StartsWith("https:")
? relativeOrAbsoluteUrl.RightPart("://").RightPart("/")
: relativeOrAbsoluteUrl;
if (!relativeUrl.StartsWith("/"))
relativeUrl = "/" + relativeUrl;
var parts = relativeUrl.SplitOnFirst("?");
var pathInfo = parts[0];
var route = FindRoute(pathInfo, method);
if (route == null)
throw new ArgumentException($"No matching route found for path {method} '{pathInfo}'");
Dictionary<string, string> query = null;
if (parts.Length == 2)
{
query = new Dictionary<string, string>();
var qs = parts[1];
var qsParts = qs.Split('&');
foreach (var qsPart in qsParts)
{
var kvp = qsPart.SplitOnFirst("=");
if (kvp.Length == 1) continue;
query[kvp[0]] = kvp[1].UrlDecode();
}
}
var requestDto = route.CreateRequest(pathInfo, query, route.RequestType.CreateInstance());
return requestDto;
}
public static void AddReferencedTypes(HashSet<Type> to, Type type)
{
if (type == null || to.Contains(type) || !IsDtoType(type))
return;
to.Add(type);
var baseType = type.BaseType;
if (baseType != null && IsDtoType(baseType) && !to.Contains(baseType))
{
AddReferencedTypes(to, baseType);
var genericArgs = type.IsGenericType
? type.GetGenericArguments()
: Type.EmptyTypes;
foreach (var arg in genericArgs)
{
AddReferencedTypes(to, arg);
}
}
foreach (var iface in type.GetInterfaces())
{
if (iface.IsGenericType && !iface.IsGenericTypeDefinition)
{
foreach (var arg in iface.GetGenericArguments())
{
AddReferencedTypes(to, arg);
}
}
}
foreach (var pi in type.GetSerializableProperties())
{
if (to.Contains(pi.PropertyType))
continue;
if (IsDtoType(pi.PropertyType))
to.Add(pi.PropertyType);
var genericArgs = pi.PropertyType.IsGenericType
? pi.PropertyType.GetGenericArguments()
: Type.EmptyTypes;
if (genericArgs.Length > 0)
{
foreach (var arg in genericArgs)
{
AddReferencedTypes(to, arg);
}
}
else if (pi.PropertyType.IsArray)
{
var elType = pi.PropertyType.HasElementType ? pi.PropertyType.GetElementType() : null;
AddReferencedTypes(to, elType);
}
}
}
private static bool IsDtoType(Type type) => type != null &&
type.Namespace?.StartsWith("System") == false &&
type.IsClass && type != typeof(string) &&
!type.IsGenericType &&
!type.IsArray &&
!type.HasInterface(typeof(IService));
public List<MetadataType> GetMetadataTypesForOperation(IRequest httpReq, Operation op)
{
var typeMetadata = HostContext.TryResolve<INativeTypesMetadata>();
var typesConfig = HostContext.AppHost.GetTypesConfigForMetadata(httpReq);
if (HostContext.GetPlugin<MetadataFeature>().ShowResponseStatusInMetadataPages)
{
typesConfig.IgnoreTypes.Remove(typeof(ResponseStatus));
typesConfig.IgnoreTypes.Remove(typeof(ResponseError));
}
var metadataTypes = typeMetadata != null
? typeMetadata.GetMetadataTypes(httpReq, typesConfig)
: new MetadataTypesGenerator(this, typesConfig)
.GetMetadataTypes(httpReq);
var types = new List<MetadataType>();
var reqType = FindMetadataType(metadataTypes, op.RequestType);
if (reqType != null)
{
types.Add(reqType);
AddReferencedTypes(reqType, metadataTypes, types);
}
var resType = FindMetadataType(metadataTypes, op.ResponseType);
if (resType != null)
{
types.Add(resType);
AddReferencedTypes(resType, metadataTypes, types);
}
var generator = new CSharpGenerator(typesConfig);
types.Each(x =>
{
x.DisplayType ??= generator.Type(x.Name, x.GenericArgs);
x.Properties.Each(p =>
p.DisplayType ??= generator.Type(p.Type, p.GenericArgs));
});
return types;
}
private static void AddReferencedTypes(MetadataType metadataType, MetadataTypes metadataTypes, List<MetadataType> types)
{
if (metadataType.Inherits != null)
{
var type = FindMetadataType(metadataTypes, metadataType.Inherits.Name, metadataType.Inherits.Namespace);
if (type != null && !types.Contains(type))
{
types.Add(type);
AddReferencedTypes(type, metadataTypes, types);
}
if (!metadataType.Inherits.GenericArgs.IsEmpty())
{
foreach (var arg in metadataType.Inherits.GenericArgs)
{
type = FindMetadataType(metadataTypes, arg);
if (type != null && !types.Contains(type))
{
types.Add(type);
AddReferencedTypes(type, metadataTypes, types);
}
}
}
}
if (metadataType.Properties != null)
{
foreach (var p in metadataType.Properties)
{
var type = FindMetadataType(metadataTypes, p.Type, p.TypeNamespace);
if (type != null && !types.Contains(type))
{
types.Add(type);
AddReferencedTypes(type, metadataTypes, types);
}
if (!p.GenericArgs.IsEmpty())
{
foreach (var arg in p.GenericArgs)
{
type = FindMetadataType(metadataTypes, arg);
if (type != null && !types.Contains(type))
{
types.Add(type);
AddReferencedTypes(type, metadataTypes, types);
}
}
}
else if (p.IsArray())
{
var elType = p.Type.LeftPart('[');
type = FindMetadataType(metadataTypes, elType, p.TypeNamespace);
if (type != null && !types.Contains(type))
{
types.Add(type);
AddReferencedTypes(type, metadataTypes, types);
}
}
}
}
}
static MetadataType FindMetadataType(MetadataTypes metadataTypes, Type type)
{
return type == null ? null : FindMetadataType(metadataTypes, type.Name, type.Namespace);
}
static MetadataType FindMetadataType(MetadataTypes metadataTypes, string name, string @namespace = null)
{
if (@namespace != null
&& @namespace.StartsWith("System")
&& metadataTypes.Config.ExportTypes.All(x => x.Name != name))
return null;
var reqType = metadataTypes.Operations.FirstOrDefault(x => x.Request.Name == name);
if (reqType != null)
return reqType.Request;
var resType = metadataTypes.Operations
.FirstOrDefault(x => x.Response != null && x.Response.Name == name);
if (resType != null)
return resType.Response;
var type = metadataTypes.Types.FirstOrDefault(x => x.Name == name
&& (@namespace == null || x.Namespace == @namespace));
return type;
}
#if !NETCORE
public List<Type> GetAllSoapOperationTypes()
{
var operationTypes = GetAllOperationTypes();
var soapTypes = HostContext.AppHost.ExportSoapOperationTypes(operationTypes);
return soapTypes;
}
#endif
public List<string> GetAllRoles()
{
var to = new List<string> {
RoleNames.Admin
};
foreach (var op in OperationsMap.Values)
{
op.RequiredRoles.Each(x => to.AddIfNotExists(x));
op.RequiresAnyRole.Each(x => to.AddIfNotExists(x));
}
return to;
}
public List<string> GetAllPermissions()
{
var to = new List<string> {
};
foreach (var op in OperationsMap.Values)
{
op.RequiredPermissions.Each(x => to.AddIfNotExists(x));
op.RequiresAnyPermission.Each(x => to.AddIfNotExists(x));
}
return to;
}
}
public class Operation : ICloneable
{
public string Name => RequestType.GetOperationName();
public Type RequestType { get; set; }
public Type ServiceType { get; set; }
public Type ResponseType { get; set; }
public Type DataModelType => AutoCrudOperation.GetModelType(RequestType);
public Type ViewModelType => AutoCrudOperation.GetViewModelType(RequestType, ResponseType);
public RestrictAttribute RestrictTo { get; set; }
public List<string> Actions { get; set; }
public bool ReturnsVoid => ResponseType == null;
public bool IsOneWay => ResponseType == null;
public string Method { get; set; }
public List<RestPath> Routes { get; set; }
public List<IRequestFilterBase> RequestFilterAttributes { get; set; }
public List<IResponseFilterBase> ResponseFilterAttributes { get; set; }
public bool RequiresAuthentication { get; set; }
public List<string> RequiredRoles { get; set; }
public List<string> RequiresAnyRole { get; set; }
public List<string> RequiredPermissions { get; set; }
public List<string> RequiresAnyPermission { get; set; }
public List<TagAttribute> Tags { get; set; }
public List<List<InputInfo>> FormLayout { get; set; }
public List<ITypeValidator> RequestTypeValidationRules { get; private set; }
public List<IValidationRule> RequestPropertyValidationRules { get; private set; }
object ICloneable.Clone() => Clone();
public Operation Clone() => new() {
RequestType = RequestType,
ServiceType = ServiceType,
ResponseType = ResponseType,
RestrictTo = RestrictTo,
Actions = Actions?.ToList(),
Method = Method,
Routes = Routes?.ToList(),
RequestFilterAttributes = RequestFilterAttributes,
RequiresAuthentication = RequiresAuthentication,
RequiredRoles = RequiredRoles?.ToList(),
RequiresAnyRole = RequiresAnyRole?.ToList(),
RequiredPermissions = RequiredPermissions?.ToList(),
RequiresAnyPermission = RequiresAnyPermission?.ToList(),
Tags = Tags?.ToList(),
RequestTypeValidationRules = RequestTypeValidationRules?.ToList(),
RequestPropertyValidationRules = RequestPropertyValidationRules?.ToList(),
};
public void AddRequestTypeValidationRules(List<ITypeValidator> typeValidators)
{
if (typeValidators != null)
{
RequestTypeValidationRules ??= new List<ITypeValidator>();
RequestTypeValidationRules.AddRange(typeValidators);
var authValidators = typeValidators.OfType<IAuthTypeValidator>().ToList();
if (authValidators.Count > 0)
{
RequiresAuthentication = true;
var rolesValidators = authValidators.OfType<HasRolesValidator>();
foreach (var validator in rolesValidators)
{
RequiredRoles ??= new List<string>();
validator.Roles.Each(x => RequiredRoles.AddIfNotExists(x));
}
var permsValidators = authValidators.OfType<HasPermissionsValidator>();
foreach (var validator in permsValidators)
{
RequiredPermissions ??= new List<string>();
validator.Permissions.Each(x => RequiredPermissions.AddIfNotExists(x));
}
}
}
}
public void AddRequestPropertyValidationRules(List<IValidationRule> propertyValidators)
{
if (propertyValidators != null)
{
RequestPropertyValidationRules ??= new List<IValidationRule>();
RequestPropertyValidationRules.AddRange(propertyValidators);
}
}
public Operation AddRole(string role)
{
RequiredRoles.AddIfNotExists(role);
RequiresAuthentication = true;
return this;
}
public Operation AddPermission(string permission)
{
RequiredPermissions.AddIfNotExists(permission);
RequiresAuthentication = true;
return this;
}
}
public class OperationDto
{
public string Name { get; set; }
public string ResponseName { get; set; }
public string ServiceName { get; set; }
public List<string> RestrictTo { get; set; }
public List<string> VisibleTo { get; set; }
public List<string> Actions { get; set; }
public List<string> Routes { get; set; }
public List<string> Tags { get; set; }
}
public class XsdMetadata
{
public ServiceMetadata Metadata { get; set; }
public bool Flash { get; set; }
public XsdMetadata(ServiceMetadata metadata, bool flash = false)
{
Metadata = metadata;
Flash = flash;
}
public List<string> GetReplyOperationNames(Format format, HashSet<Type> soapTypes)
{
return Metadata.OperationsMap.Values
.Where(x => HostContext.Config != null
&& HostContext.MetadataPagesConfig.CanAccess(format, x.Name))
.Where(x => !x.ReturnsVoid)
.Where(x => soapTypes.Contains(x.RequestType))
.Select(x => x.RequestType.GetOperationName())
.ToList();
}
public List<string> GetOneWayOperationNames(Format format, HashSet<Type> soapTypes)
{
return Metadata.OperationsMap.Values
.Where(x => HostContext.Config != null
&& HostContext.MetadataPagesConfig.CanAccess(format, x.Name))
.Where(x => x.ReturnsVoid)
.Where(x => soapTypes.Contains(x.RequestType))
.Select(x => x.RequestType.GetOperationName())
.ToList();
}
/// <summary>
/// Gets the name of the base most type in the heirachy tree with the same.
///
/// We get an exception when trying to create a schema with multiple types of the same name
/// like when inheriting from a DataContract with the same name.
/// </summary>
/// <param name="type">The type.</param>
/// <returns></returns>
public static Type GetBaseTypeWithTheSameName(Type type)
{
var typesWithSameName = new Stack<Type>();
var baseType = type;
do
{
if (baseType.GetOperationName() == type.GetOperationName())
typesWithSameName.Push(baseType);
}
while ((baseType = baseType.BaseType) != null);
return typesWithSameName.Pop();
}
}
public static class ServiceMetadataExtensions
{
public static OperationDto ToOperationDto(this Operation operation)
{
var to = new OperationDto
{
Name = operation.Name,
ResponseName = operation.ReturnsVoid ? null : operation.ResponseType.GetOperationName(),
ServiceName = operation.ServiceType.GetOperationName(),
Actions = operation.Actions,
Routes = operation.Routes.Map(x => x.Path),
Tags = operation.Tags.Map(x => x.Name),
};
if (operation.RestrictTo != null)
{
to.RestrictTo = operation.RestrictTo.AccessibleToAny.ToList().ConvertAll(x => x.ToString());
to.VisibleTo = operation.RestrictTo.VisibleToAny.ToList().ConvertAll(x => x.ToString());
}
return to;
}
public static List<ApiMemberAttribute> GetApiMembers(this Type operationType)
{
var members = operationType.GetMembers(BindingFlags.Instance | BindingFlags.Public);
var attrs = new List<ApiMemberAttribute>();
foreach (var member in members)
{
var attr = member.AllAttributes<ApiMemberAttribute>()
.Select(x => { x.Name ??= member.Name; return x; });
attrs.AddRange(attr);
}
return attrs;
}
public static List<Assembly> GetAssemblies(this Operation operation)
{
var ret = new List<Assembly> { operation.RequestType.Assembly };
if (operation.ResponseType != null
&& operation.ResponseType.Assembly != operation.RequestType.Assembly)
{
ret.Add(operation.ResponseType.Assembly);
}
return ret;
}
}
public static class MetadataTypeExtensions
{
public static string GetParamType(this MetadataPropertyType prop, MetadataType type, Operation op)
{
if (prop.ParamType != null)
return prop.ParamType;
var isRequest = type.Name == op.RequestType.Name;
return !isRequest ? "form" : GetRequestParamType(op, prop.Name);
}
public static string GetParamType(this ApiMemberAttribute attr, Type type, string verb)
{
if (attr.ParameterType != null)
return attr.ParameterType;
var op = HostContext.Metadata.GetOperation(type);
var isRequestType = op != null;
var defaultType = verb == HttpMethods.Post || verb == HttpMethods.Put
? "form"