/
ValidateAttribute.cs
266 lines (233 loc) · 10.5 KB
/
ValidateAttribute.cs
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
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using ServiceStack.DataAnnotations;
namespace ServiceStack;
/// <summary>
/// Assert pre-conditions before DTO's Fluent Validation properties are evaluated
/// </summary>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)]
[Tag("PropertyOrder")]
public class ValidateRequestAttribute : AttributeBase, IValidateRule, IReflectAttributeConverter
{
public ValidateRequestAttribute() {}
public ValidateRequestAttribute(string validator) => Validator = validator;
/// <summary>
/// Script Expression to create an IPropertyValidator registered in Validators.Types
/// </summary>
public string Validator { get; set; }
/// <summary>
/// Boolean #Script Code Expression to Test
/// ARGS:
/// - Request: IRequest
/// - dto: Request DTO
/// - it: Request DTO
/// </summary>
public string Condition { get; set; }
/// <summary>
/// Combine multiple conditions
/// </summary>
[Ignore]
public string[] Conditions
{
get => new []{ Condition };
set => Condition = ValidateAttribute.Combine("&&", value);
}
/// <summary>
/// Custom ErrorCode to return
/// </summary>
public string ErrorCode { get; set; }
/// <summary>
/// Custom Error Message to return
/// - {PropertyName}
/// - {PropertyValue}
/// </summary>
public string Message { get; set; }
/// <summary>
/// Custom Status Code to return when invalid
/// </summary>
public int StatusCode { get; set; }
[Ignore]
public string[] AllConditions
{
get => throw new NotSupportedException(nameof(AllConditions));
set => Condition = ValidateAttribute.Combine("&&", value);
}
[Ignore]
public string[] AnyConditions
{
get => throw new NotSupportedException(nameof(AnyConditions));
set => Condition = ValidateAttribute.Combine("||", value);
}
public ReflectAttribute ToReflectAttribute()
{
var to = new ReflectAttribute {
Name = "ValidateRequest",
PropertyArgs = []
};
if (!string.IsNullOrEmpty(Validator))
to.PropertyArgs.Add(new KeyValuePair<PropertyInfo, object>(GetType().GetProperty(nameof(Validator)), Validator));
else if (!string.IsNullOrEmpty(Condition))
to.PropertyArgs.Add(new KeyValuePair<PropertyInfo, object>(GetType().GetProperty(nameof(Condition)), Condition));
if (!string.IsNullOrEmpty(ErrorCode))
to.PropertyArgs.Add(new KeyValuePair<PropertyInfo, object>(GetType().GetProperty(nameof(ErrorCode)), ErrorCode));
if (!string.IsNullOrEmpty(Message))
to.PropertyArgs.Add(new KeyValuePair<PropertyInfo, object>(GetType().GetProperty(nameof(Message)), Message));
if (StatusCode != default)
to.PropertyArgs.Add(new KeyValuePair<PropertyInfo, object>(GetType().GetProperty(nameof(StatusCode)), StatusCode));
return to;
}
}
public interface IRequireAuthentication {}
/* Default ITypeValidator defined in ValidateScripts */
public class ValidateIsAuthenticatedAttribute() : ValidateRequestAttribute("IsAuthenticated"), IRequireAuthentication;
public class ValidateIsAdminAttribute() : ValidateRequestAttribute("IsAdmin"), IRequireAuthentication;
public class ValidateHasRoleAttribute(string role) : ValidateRequestAttribute("HasRole(`" + role + "`)"), IRequireAuthentication
{
public string Role => role;
};
public class ValidateHasPermissionAttribute(string permission) : ValidateRequestAttribute("HasPermission(`" + permission + "`)"), IRequireAuthentication
{
public string Permission => permission;
}
public class ValidateHasClaimAttribute(string type, string value) : ValidateRequestAttribute("HasClaim(`" + type + "`,`" + value + "`)"), IRequireAuthentication
{
public string Type => type;
public string Value => value;
}
public class ValidateHasScopeAttribute(string scope) : ValidateRequestAttribute("HasScope(`" + scope + "`)"), IRequireAuthentication
{
public string Scope => scope;
}
/// <summary>
/// Validate property against registered Validator expression
/// </summary>
[AttributeUsage(AttributeTargets.Property, AllowMultiple = true, Inherited = true)]
public class ValidateAttribute : AttributeBase, IValidateRule, IReflectAttributeConverter
{
public ValidateAttribute() {}
public ValidateAttribute(string validator) => Validator = validator;
/// <summary>
/// Script Expression to create an IPropertyValidator registered in Validators.Types
/// </summary>
public string Validator { get; set; }
/// <summary>
/// Boolean #Script Code Expression to Test
/// ARGS:
/// - Request: IRequest
/// - dto: Request DTO
/// - field: Property Name
/// - it: Property Value
/// </summary>
public string Condition { get; set; }
[Ignore]
public string[] AllConditions
{
get => throw new NotSupportedException(nameof(AllConditions));
set => Condition = Combine("&&", value);
}
[Ignore]
public string[] AnyConditions
{
get => throw new NotSupportedException(nameof(AnyConditions));
set => Condition = Combine("||", value);
}
/// <summary>
/// Custom ErrorCode to return
/// </summary>
public string ErrorCode { get; set; }
/// <summary>
/// Refer to FluentValidation docs for Variable
/// - {PropertyName}
/// - {PropertyValue}
/// </summary>
public string Message { get; set; }
public static string Combine(string comperand, params string[] conditions)
{
var sb = new StringBuilder();
var joiner = ") " + comperand + " (";
foreach (var condition in conditions)
{
if (string.IsNullOrEmpty(condition))
continue;
if (sb.Length > 0)
sb.Append(joiner);
sb.Append(condition);
}
sb.Insert(0, '(');
sb.Append(')');
return sb.ToString();
}
public ReflectAttribute ToReflectAttribute()
{
var to = new ReflectAttribute {
Name = "Validate",
PropertyArgs = []
};
if (!string.IsNullOrEmpty(Validator))
to.PropertyArgs.Add(new KeyValuePair<PropertyInfo, object>(GetType().GetProperty(nameof(Validator)), Validator));
else if (!string.IsNullOrEmpty(Condition))
to.PropertyArgs.Add(new KeyValuePair<PropertyInfo, object>(GetType().GetProperty(nameof(Condition)), Condition));
if (!string.IsNullOrEmpty(ErrorCode))
to.PropertyArgs.Add(new KeyValuePair<PropertyInfo, object>(GetType().GetProperty(nameof(ErrorCode)), ErrorCode));
if (!string.IsNullOrEmpty(Message))
to.PropertyArgs.Add(new KeyValuePair<PropertyInfo, object>(GetType().GetProperty(nameof(Message)), Message));
return to;
}
}
/// <summary>
/// Override to allow a property to be reset back to their default values using partial updates.
/// By default properties with any validators cannot be reset
/// </summary>
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class AllowResetAttribute : AttributeBase {}
/// <summary>
/// Don't allow property to be reset
/// </summary>
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class DenyResetAttribute : AttributeBase {}
//Default IPropertyValidator defined in ValidateScripts
public class ValidateNullAttribute() : ValidateAttribute("Null");
public class ValidateEmptyAttribute() : ValidateAttribute("Empty");
public class ValidateEmailAttribute() : ValidateAttribute("Email");
public class ValidateNotNullAttribute() : ValidateAttribute("NotNull");
public class ValidateNotEmptyAttribute() : ValidateAttribute("NotEmpty");
/// <summary>
/// Validate property against Fluent Validation CreditCardValidator
/// </summary>
public class ValidateCreditCardAttribute() : ValidateAttribute("CreditCard");
public class ValidateLengthAttribute(int min, int max) : ValidateAttribute($"Length({min},{max})");
public class ValidateExactLengthAttribute(int length) : ValidateAttribute($"ExactLength({length})");
public class ValidateMaximumLengthAttribute(int max) : ValidateAttribute($"MaximumLength({max})");
public class ValidateMinimumLengthAttribute(int min) : ValidateAttribute($"MinimumLength({min})");
public class ValidateLessThanAttribute(int value) : ValidateAttribute($"LessThan({value})");
public class ValidateLessThanOrEqualAttribute(int value) : ValidateAttribute($"LessThanOrEqual({value})");
public class ValidateGreaterThanAttribute(int value) : ValidateAttribute($"GreaterThan({value})");
public class ValidateGreaterThanOrEqualAttribute(int value) : ValidateAttribute($"GreaterThanOrEqual({value})");
public class ValidateScalePrecisionAttribute(int scale, int precision) : ValidateAttribute($"ScalePrecision({scale},{precision})");
public class ValidateRegularExpressionAttribute(string pattern) : ValidateAttribute($"RegularExpression(`{pattern}`)");
public class ValidateEqualAttribute : ValidateAttribute
{
public ValidateEqualAttribute(string value) : base($"Equal(`{value}`)") { }
public ValidateEqualAttribute(int value) : base($"Equal({value})") { }
public ValidateEqualAttribute(bool value) : base($"Equal({value.ToString().ToLower()})") { }
}
public class ValidateNotEqualAttribute : ValidateAttribute
{
public ValidateNotEqualAttribute(string value) : base($"NotEqual(`{value}`)") { }
public ValidateNotEqualAttribute(int value) : base($"NotEqual({value})") { }
public ValidateNotEqualAttribute(bool value) : base($"NotEqual({value.ToString().ToLower()})") { }
}
public class ValidateInclusiveBetweenAttribute : ValidateAttribute
{
public ValidateInclusiveBetweenAttribute(string from, string to) : base($"InclusiveBetween(`{from}`,`{to}`)") { }
public ValidateInclusiveBetweenAttribute(char from, char to) : base($"InclusiveBetween(`{from}`,`{to}`)") { }
public ValidateInclusiveBetweenAttribute(int from, int to) : base($"InclusiveBetween({from},{to})") { }
}
public class ValidateExclusiveBetweenAttribute : ValidateAttribute
{
public ValidateExclusiveBetweenAttribute(string from, string to) : base($"ExclusiveBetween(`{from}`,`{to}`)") { }
public ValidateExclusiveBetweenAttribute(char from, char to) : base($"ExclusiveBetween(`{from}`,`{to}`)") { }
public ValidateExclusiveBetweenAttribute(int from, int to) : base($"ExclusiveBetween({from},{to})") { }
}