Compare commits
18
Commits
caeb6ae7f3
..
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d89acf612c | ||
|
|
2970815270 | ||
|
|
6757b2eaf6 | ||
|
|
e2de55e8ef | ||
|
|
d5da835b71 | ||
|
|
939366fbb4 | ||
|
|
d1f940c44b | ||
|
|
a9f92c751f | ||
|
|
61d8ad831e | ||
|
|
5e31f8f99a | ||
|
|
cba7637255 | ||
|
|
0a8f9692dd | ||
|
|
b9ba57dbfa | ||
|
|
8eb9ac1ca2 | ||
|
|
9c426f52ab | ||
|
|
6a55b4e814 | ||
|
|
526a1d295c | ||
|
|
6f6ba825d6 |
@@ -0,0 +1,117 @@
|
||||
using System;
|
||||
using xCommons.Models;
|
||||
using xCommons.Constants;
|
||||
using xCommons.Extensions;
|
||||
using xCommons.Interfaces;
|
||||
using xCommons.Configurations;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc.Filters;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace xCommons.Attributes
|
||||
{
|
||||
[AttributeUsage(
|
||||
AttributeTargets.Class | AttributeTargets.Method,
|
||||
AllowMultiple = false,
|
||||
Inherited = true
|
||||
)]
|
||||
public partial class XRateLimitAttribute : Attribute, IActionFilter, IOrderedFilter
|
||||
{
|
||||
public int Limit { get; set; } = 0;
|
||||
public int Order { get; set; } = -1000;
|
||||
public int PeriodSeconds { get; set; } = 0;
|
||||
public string KeyPrefix { get; set; } = null;
|
||||
public XRateLimitKeyMode KeyMode { get; set; } = XRateLimitKeyMode.Ip;
|
||||
|
||||
public void OnActionExecuting(ActionExecutingContext context)
|
||||
{
|
||||
//
|
||||
var provider = context.HttpContext.RequestServices
|
||||
.GetService<IXRateLimitProvider>();
|
||||
|
||||
var configuration = context.HttpContext.RequestServices
|
||||
.GetService<XRateLimitConfiguration>();
|
||||
|
||||
//
|
||||
if (provider.IsNull() ||
|
||||
configuration.IsNull() ||
|
||||
!provider.IsEnabled)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
//
|
||||
var limit = Limit > 0
|
||||
? Limit
|
||||
: configuration.DefaultLimit;
|
||||
|
||||
//
|
||||
var periodSeconds = PeriodSeconds > 0
|
||||
? PeriodSeconds
|
||||
: configuration.DefaultPeriodSeconds;
|
||||
|
||||
//
|
||||
var key = context.HttpContext.GetXRateLimitKey(KeyMode);
|
||||
if (!KeyPrefix.IsNullOrEmpty())
|
||||
{
|
||||
key = string.Format("{0}:{1}", KeyPrefix, key);
|
||||
}
|
||||
|
||||
//
|
||||
var result = provider.TryConsume(
|
||||
key: key,
|
||||
limit: limit,
|
||||
periodSeconds: periodSeconds
|
||||
);
|
||||
|
||||
//
|
||||
context.HttpContext.Items[XRateLimitConstants.AppliedItemKey] = true;
|
||||
WriteHeaders(context.HttpContext, result);
|
||||
|
||||
//
|
||||
if (!result.IsAllowed)
|
||||
{
|
||||
//
|
||||
context.Result = new ObjectResult(new
|
||||
{
|
||||
resetOn = result.ResetOn,
|
||||
retryAfter = result.RetryAfterSeconds,
|
||||
message = "Too many requests. Please try again later.",
|
||||
})
|
||||
{
|
||||
StatusCode = configuration.StatusCode
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
public void OnActionExecuted(ActionExecutedContext context)
|
||||
{ }
|
||||
|
||||
private static void WriteHeaders(
|
||||
HttpContext context,
|
||||
XRateLimitResult result
|
||||
)
|
||||
{
|
||||
//
|
||||
context.Response.Headers[XRateLimitConstants.LimitHeader] =
|
||||
result.Limit.ToString();
|
||||
|
||||
//
|
||||
context.Response.Headers[XRateLimitConstants.RemainingHeader] =
|
||||
result.Remaining.ToString();
|
||||
|
||||
//
|
||||
context.Response.Headers[XRateLimitConstants.ResetHeader] =
|
||||
result.ResetOn.ToUnixTimeSeconds().ToString();
|
||||
|
||||
//
|
||||
if (!result.IsAllowed)
|
||||
{
|
||||
//
|
||||
context.Response.Headers[XRateLimitConstants.RetryAfterHeader] =
|
||||
result.RetryAfterSeconds.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,20 +1,25 @@
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace xCommons.Configurations {
|
||||
namespace xCommons.Configurations
|
||||
{
|
||||
/// <summary>
|
||||
/// represent an xBackend Application
|
||||
/// </summary>
|
||||
public partial class XAppConfiguration {
|
||||
public partial class XAppConfiguration
|
||||
{
|
||||
public string Name { get; set; }
|
||||
public string Version { get; set; }
|
||||
public string Environment { get; set; }
|
||||
public string XPoweredValue { get; set; }
|
||||
public IEnumerable<string> AllowedOrigins { get; set; }
|
||||
public string WelcomeMessage { get; set; }
|
||||
public string DefaultLanguage { get; set; }
|
||||
public int DefaultCacheTtlMinutes { get; set; } = 15;
|
||||
public IEnumerable<string> AllowedOrigins { get; set; }
|
||||
public XMessageResourceTitles MessageResourceTitles { get; set; }
|
||||
}
|
||||
|
||||
public partial class XMessageResourceTitles {
|
||||
public partial class XMessageResourceTitles
|
||||
{
|
||||
public string Terms { get; set; }
|
||||
public string Invite { get; set; }
|
||||
public string RegistrationApprove { get; set; }
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
namespace xCommons.Configurations
|
||||
{
|
||||
/// <summary>
|
||||
/// Configuration options for XFileTypeDetector ...
|
||||
/// </summary>
|
||||
public sealed class XFileTypeDetectorConfiguration
|
||||
{
|
||||
/// <summary>
|
||||
/// When true, magic bytes are always read first ...
|
||||
/// </summary>
|
||||
public bool PreferMagicBytes { get; set; } = true;
|
||||
|
||||
/// <summary>
|
||||
/// Number of bytes read from the stream header ...
|
||||
/// </summary>
|
||||
public int HeaderSize { get; set; } = 32;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
using xCommons.Constants;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace xCommons.Configurations
|
||||
{
|
||||
public class XRateLimitConfiguration
|
||||
{
|
||||
public bool Enabled { get; set; } = false;
|
||||
public int StatusCode { get; set; } = 429;
|
||||
public int DefaultLimit { get; set; } = 60;
|
||||
public int DefaultPeriodSeconds { get; set; } = 60;
|
||||
public bool ApplyToAllRoutes { get; set; } = false;
|
||||
public ICollection<XRateLimitRule> Rules { get; set; } = [];
|
||||
public XRateLimitKeyMode DefaultKeyMode { get; set; } = XRateLimitKeyMode.Ip;
|
||||
}
|
||||
|
||||
public partial class XRateLimitRule
|
||||
{
|
||||
public int Limit { get; set; } = 60;
|
||||
public bool Enabled { get; set; } = true;
|
||||
public int PeriodSeconds { get; set; } = 60;
|
||||
public string PathPrefix { get; set; } = "/";
|
||||
public string Name { get; set; } = string.Empty;
|
||||
public XRateLimitKeyMode KeyMode { get; set; } = XRateLimitKeyMode.Ip;
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,8 @@ namespace xCommons.Constants {
|
||||
public partial struct ConfigurationNodeNames {
|
||||
public const string CERTIFICATES_NODE = "Certificates";
|
||||
public const string SWAGGER_NODE = "SwaggerConfiguration";
|
||||
public const string RATE_LIMIT_NODE = "RateLimitConfiguration";
|
||||
public const string FILE_TYPE_DETECTOR_NODE = "FileTypeDetectorConfiguration";
|
||||
public const string MESSAGE_RESOURCE_TITLES_NODE = "MessageResourceTitles";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
using xExceptions.Attributes;
|
||||
|
||||
namespace xCommons.Constants
|
||||
{
|
||||
/// <summary>
|
||||
/// File Extensions Enumerable ...
|
||||
///
|
||||
/// Document: 100–133
|
||||
/// Archive: 200–202
|
||||
/// Internal Supports: 300–302
|
||||
/// Video: 400–405
|
||||
/// Audio: 500–505
|
||||
/// Image: 600–609
|
||||
/// </summary>
|
||||
public enum XFileExtensions
|
||||
{
|
||||
//
|
||||
#region Document ...
|
||||
[StringValue(".txt")]
|
||||
TEXT = 100,
|
||||
|
||||
[StringValue(".pdf")]
|
||||
PDF = 101,
|
||||
|
||||
[StringValue(".ppt")]
|
||||
PPT = 102,
|
||||
|
||||
[StringValue(".pptx")]
|
||||
PPTX = 103,
|
||||
|
||||
[StringValue(".odp")]
|
||||
ODP = 104,
|
||||
|
||||
[StringValue(".pps")]
|
||||
PPS = 105,
|
||||
|
||||
[StringValue(".ods")]
|
||||
ODS = 106,
|
||||
|
||||
[StringValue(".xlr")]
|
||||
XLR = 107,
|
||||
|
||||
[StringValue(".xls")]
|
||||
XLS = 108,
|
||||
|
||||
[StringValue(".xlsx")]
|
||||
XLSX = 109,
|
||||
|
||||
[StringValue(".xml")]
|
||||
XML = 110,
|
||||
|
||||
[StringValue(".doc")]
|
||||
DOC = 111,
|
||||
|
||||
[StringValue(".docx")]
|
||||
DOCX = 112,
|
||||
|
||||
[StringValue(".odt")]
|
||||
ODT = 113,
|
||||
|
||||
[StringValue(".rtf")]
|
||||
RTF = 114,
|
||||
|
||||
[StringValue(".tex")]
|
||||
TEX = 115,
|
||||
|
||||
[StringValue(".wpd")]
|
||||
WPD = 116,
|
||||
|
||||
[StringValue(".md")]
|
||||
MD = 117,
|
||||
|
||||
[StringValue(".cs")]
|
||||
CSHARP = 118,
|
||||
|
||||
[StringValue(".py")]
|
||||
PYTHON = 119,
|
||||
|
||||
[StringValue(".js")]
|
||||
JAVASCRIPT = 120,
|
||||
|
||||
[StringValue(".ts")]
|
||||
TYPESCRIPT = 121,
|
||||
|
||||
[StringValue(".java")]
|
||||
JAVA = 122,
|
||||
|
||||
[StringValue(".go")]
|
||||
GO = 123,
|
||||
|
||||
[StringValue(".rs")]
|
||||
RUST = 124,
|
||||
|
||||
[StringValue(".rb")]
|
||||
RUBY = 125,
|
||||
|
||||
[StringValue(".php")]
|
||||
PHP = 126,
|
||||
|
||||
[StringValue(".csv")]
|
||||
CSV = 127,
|
||||
|
||||
[StringValue(".json")]
|
||||
JSON = 128,
|
||||
|
||||
[StringValue(".yml")]
|
||||
YML = 129,
|
||||
|
||||
[StringValue(".yaml")]
|
||||
YAML = 130,
|
||||
|
||||
[StringValue(".css")]
|
||||
CSS = 131,
|
||||
|
||||
[StringValue(".htm")]
|
||||
HTM = 132,
|
||||
|
||||
[StringValue(".html")]
|
||||
HTML = 133,
|
||||
#endregion
|
||||
|
||||
//
|
||||
#region Archive ...
|
||||
[StringValue(".zip")]
|
||||
ZIP = 200,
|
||||
|
||||
[StringValue(".rar")]
|
||||
RAR = 201,
|
||||
|
||||
[StringValue(".7z")]
|
||||
SEVENZIP = 202,
|
||||
#endregion
|
||||
|
||||
//
|
||||
#region Internal Supports ...
|
||||
[StringValue(".ttf")]
|
||||
TTF = 300,
|
||||
|
||||
[StringValue(".sdw")]
|
||||
SAHER_DASHBOARD_WIDGET = 301,
|
||||
|
||||
[StringValue(".sdwmanifest")]
|
||||
SAHER_DASHBOARD_WIDGET_MANIFEST = 302,
|
||||
#endregion
|
||||
|
||||
//
|
||||
#region Video ...
|
||||
[StringValue(".mp4")]
|
||||
MP4 = 400,
|
||||
|
||||
[StringValue(".avi")]
|
||||
AVI = 401,
|
||||
|
||||
[StringValue(".mpg")]
|
||||
MPG = 402,
|
||||
|
||||
[StringValue(".mpeg")]
|
||||
MPEG = 403,
|
||||
|
||||
[StringValue(".wmv")]
|
||||
WMV = 404,
|
||||
|
||||
[StringValue(".webm")]
|
||||
WEBM = 405,
|
||||
#endregion
|
||||
|
||||
//
|
||||
#region Audio ...
|
||||
[StringValue(".mp3")]
|
||||
MP3 = 500,
|
||||
|
||||
[StringValue(".ogg")]
|
||||
OGG = 501,
|
||||
|
||||
[StringValue(".wav")]
|
||||
WAV = 502,
|
||||
|
||||
[StringValue(".wma")]
|
||||
WMA = 503,
|
||||
|
||||
[StringValue(".aac")]
|
||||
AAC = 504,
|
||||
|
||||
[StringValue(".m4a")]
|
||||
M4A = 505,
|
||||
#endregion
|
||||
|
||||
//
|
||||
#region Image ...
|
||||
[StringValue(".png")]
|
||||
PNG = 600,
|
||||
|
||||
[StringValue(".jpeg")]
|
||||
JPEG = 601,
|
||||
|
||||
[StringValue(".jpg")]
|
||||
JPG = 602,
|
||||
|
||||
[StringValue(".ico")]
|
||||
ICON = 603,
|
||||
|
||||
[StringValue(".gif")]
|
||||
GIF = 604,
|
||||
|
||||
[StringValue(".bmp")]
|
||||
BITMAP = 605,
|
||||
|
||||
[StringValue(".webp")]
|
||||
WEBP = 606,
|
||||
|
||||
[StringValue(".tif")]
|
||||
TIF = 607,
|
||||
|
||||
[StringValue(".tiff")]
|
||||
TIFF = 608,
|
||||
|
||||
[StringValue(".svg")]
|
||||
SVG = 609,
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
using xExceptions.Attributes;
|
||||
|
||||
namespace xCommons.Constants
|
||||
{
|
||||
/// <summary>
|
||||
/// MIME Types mapped to XFileExtensions ...
|
||||
///
|
||||
/// Document: 100–133
|
||||
/// Archive: 200–202
|
||||
/// Internal Supports: 300–302
|
||||
/// Video: 400–405
|
||||
/// Audio: 500–505
|
||||
/// Image: 600–609
|
||||
/// </summary>
|
||||
public enum XFileMimeTypes
|
||||
{
|
||||
//
|
||||
#region Document ...
|
||||
[StringValue("text/plain")]
|
||||
TEXT = 100,
|
||||
|
||||
[StringValue("application/pdf")]
|
||||
PDF = 101,
|
||||
|
||||
[StringValue("application/vnd.ms-powerpoint")]
|
||||
PPT = 102,
|
||||
|
||||
[StringValue("application/vnd.openxmlformats-officedocument.presentationml.presentation")]
|
||||
PPTX = 103,
|
||||
|
||||
[StringValue("application/vnd.oasis.opendocument.presentation")]
|
||||
ODP = 104,
|
||||
|
||||
[StringValue("application/vnd.ms-powerpoint")]
|
||||
PPS = 105,
|
||||
|
||||
[StringValue("application/vnd.oasis.opendocument.spreadsheet")]
|
||||
ODS = 106,
|
||||
|
||||
[StringValue("application/vnd.ms-excel")]
|
||||
XLR = 107,
|
||||
|
||||
[StringValue("application/vnd.ms-excel")]
|
||||
XLS = 108,
|
||||
|
||||
[StringValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")]
|
||||
XLSX = 109,
|
||||
|
||||
[StringValue("text/xml")]
|
||||
XML = 110,
|
||||
|
||||
[StringValue("application/msword")]
|
||||
DOC = 111,
|
||||
|
||||
[StringValue("application/vnd.openxmlformats-officedocument.wordprocessingml.document")]
|
||||
DOCX = 112,
|
||||
|
||||
[StringValue("application/vnd.oasis.opendocument.text")]
|
||||
ODT = 113,
|
||||
|
||||
[StringValue("application/rtf")]
|
||||
RTF = 114,
|
||||
|
||||
[StringValue("application/x-tex")]
|
||||
TEX = 115,
|
||||
|
||||
[StringValue("application/vnd.wordperfect")]
|
||||
WPD = 116,
|
||||
|
||||
[StringValue("text/markdown")]
|
||||
MD = 117,
|
||||
|
||||
[StringValue("text/x-csharp")]
|
||||
CSHARP = 118,
|
||||
|
||||
[StringValue("text/x-python")]
|
||||
PYTHON = 119,
|
||||
|
||||
[StringValue("application/javascript")]
|
||||
JAVASCRIPT = 120,
|
||||
|
||||
[StringValue("application/typescript")]
|
||||
TYPESCRIPT = 121,
|
||||
|
||||
[StringValue("text/x-java")]
|
||||
JAVA = 122,
|
||||
|
||||
[StringValue("text/x-go")]
|
||||
GO = 123,
|
||||
|
||||
[StringValue("text/x-rust")]
|
||||
RUST = 124,
|
||||
|
||||
[StringValue("text/x-ruby")]
|
||||
RUBY = 125,
|
||||
|
||||
[StringValue("text/x-php")]
|
||||
PHP = 126,
|
||||
|
||||
[StringValue("text/csv")]
|
||||
CSV = 127,
|
||||
|
||||
[StringValue("application/json")]
|
||||
JSON = 128,
|
||||
|
||||
[StringValue("application/x-yaml")]
|
||||
YML = 129,
|
||||
|
||||
[StringValue("application/x-yaml")]
|
||||
YAML = 130,
|
||||
|
||||
[StringValue("text/css")]
|
||||
CSS = 131,
|
||||
|
||||
[StringValue("text/html")]
|
||||
HTM = 132,
|
||||
|
||||
[StringValue("text/html")]
|
||||
HTML = 133,
|
||||
#endregion
|
||||
|
||||
//
|
||||
#region Archive ...
|
||||
[StringValue("application/zip")]
|
||||
ZIP = 200,
|
||||
|
||||
[StringValue("application/x-rar-compressed")]
|
||||
RAR = 201,
|
||||
|
||||
[StringValue("application/x-7z-compressed")]
|
||||
SEVENZIP = 202,
|
||||
#endregion
|
||||
|
||||
//
|
||||
#region Internal Supports ...
|
||||
[StringValue("font/ttf")]
|
||||
TTF = 300,
|
||||
|
||||
[StringValue("application/x-sdw")]
|
||||
SAHER_DASHBOARD_WIDGET = 301,
|
||||
|
||||
[StringValue("application/x-sdwmanifest")]
|
||||
SAHER_DASHBOARD_WIDGET_MANIFEST = 302,
|
||||
#endregion
|
||||
|
||||
//
|
||||
#region Video ...
|
||||
[StringValue("video/mp4")]
|
||||
MP4 = 400,
|
||||
|
||||
[StringValue("video/x-msvideo")]
|
||||
AVI = 401,
|
||||
|
||||
[StringValue("video/mpeg")]
|
||||
MPG = 402,
|
||||
|
||||
[StringValue("video/mpeg")]
|
||||
MPEG = 403,
|
||||
|
||||
[StringValue("video/x-ms-wmv")]
|
||||
WMV = 404,
|
||||
|
||||
[StringValue("video/webm")]
|
||||
WEBM = 405,
|
||||
#endregion
|
||||
|
||||
//
|
||||
#region Audio ...
|
||||
[StringValue("audio/mpeg")]
|
||||
MP3 = 500,
|
||||
|
||||
[StringValue("audio/ogg")]
|
||||
OGG = 501,
|
||||
|
||||
[StringValue("audio/wav")]
|
||||
WAV = 502,
|
||||
|
||||
[StringValue("audio/x-ms-wma")]
|
||||
WMA = 503,
|
||||
|
||||
[StringValue("audio/aac")]
|
||||
AAC = 504,
|
||||
|
||||
[StringValue("audio/mp4")]
|
||||
M4A = 505,
|
||||
#endregion
|
||||
|
||||
//
|
||||
#region Image ...
|
||||
[StringValue("image/png")]
|
||||
PNG = 600,
|
||||
|
||||
[StringValue("image/jpeg")]
|
||||
JPEG = 601,
|
||||
|
||||
[StringValue("image/jpeg")]
|
||||
JPG = 602,
|
||||
|
||||
[StringValue("image/x-icon")]
|
||||
ICON = 603,
|
||||
|
||||
[StringValue("image/gif")]
|
||||
GIF = 604,
|
||||
|
||||
[StringValue("image/bmp")]
|
||||
BITMAP = 605,
|
||||
|
||||
[StringValue("image/webp")]
|
||||
WEBP = 606,
|
||||
|
||||
[StringValue("image/tiff")]
|
||||
TIF = 607,
|
||||
|
||||
[StringValue("image/tiff")]
|
||||
TIFF = 608,
|
||||
|
||||
[StringValue("image/svg+xml")]
|
||||
SVG = 609,
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
+27
-2
@@ -1,5 +1,9 @@
|
||||
namespace xCommons.Constants {
|
||||
public enum XFileType {
|
||||
using xExceptions.Attributes;
|
||||
|
||||
namespace xCommons.Constants
|
||||
{
|
||||
public enum XFileType
|
||||
{
|
||||
Image,
|
||||
ProfileImasge,
|
||||
CoverImage,
|
||||
@@ -7,4 +11,25 @@ namespace xCommons.Constants {
|
||||
Video,
|
||||
Document
|
||||
}
|
||||
|
||||
public enum XFileCategory
|
||||
{
|
||||
[StringValue("Document")]
|
||||
Document = 100,
|
||||
|
||||
[StringValue("Archive")]
|
||||
Archive = 200,
|
||||
|
||||
[StringValue("Internal")]
|
||||
Internal = 300,
|
||||
|
||||
[StringValue("Video")]
|
||||
Video = 400,
|
||||
|
||||
[StringValue("Audio")]
|
||||
Audio = 500,
|
||||
|
||||
[StringValue("Image")]
|
||||
Image = 600
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
using xExceptions.Attributes;
|
||||
|
||||
namespace xCommons.Constants
|
||||
{
|
||||
/// <summary>
|
||||
/// File Type Detection Source ...
|
||||
/// </summary>
|
||||
public enum XFileTypeDetectionSource
|
||||
{
|
||||
[StringValue("None")]
|
||||
None = 0,
|
||||
|
||||
[StringValue("MagicBytes")]
|
||||
MagicBytes = 1,
|
||||
|
||||
[StringValue("Extension")]
|
||||
Extension = 2,
|
||||
|
||||
[StringValue("ProvidedMime")]
|
||||
ProvidedMime = 3,
|
||||
|
||||
[StringValue("Fallback")]
|
||||
Fallback = 4
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
namespace xCommons.Constants
|
||||
{
|
||||
/// <summary>
|
||||
/// RateLimit Implementation Constants ...
|
||||
/// </summary>
|
||||
public partial struct XRateLimitConstants
|
||||
{
|
||||
public const string CacheKeyPrefix = "xratelimit";
|
||||
public const string ClientIdHeader = "X-ClientId";
|
||||
public const string RetryAfterHeader = "Retry-After";
|
||||
public const string LimitHeader = "X-RateLimit-Limit";
|
||||
public const string ResetHeader = "X-RateLimit-Reset";
|
||||
public const string AppliedItemKey = "X-RateLimit-Applied";
|
||||
public const string RemainingHeader = "X-RateLimit-Remaining";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
using xExceptions.Attributes;
|
||||
|
||||
namespace xCommons.Constants
|
||||
{
|
||||
/// <summary>
|
||||
/// RateLimiting Modes ...
|
||||
/// </summary>
|
||||
public enum XRateLimitKeyMode
|
||||
{
|
||||
[StringValue("Ip")]
|
||||
Ip = 0,
|
||||
|
||||
[StringValue("ClientId")]
|
||||
ClientId = 1,
|
||||
|
||||
[StringValue("User")]
|
||||
User = 2,
|
||||
|
||||
[StringValue("Route")]
|
||||
Route = 3,
|
||||
|
||||
[StringValue("Custom")]
|
||||
Custom = 4
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,31 @@
|
||||
using xCommons.Providers;
|
||||
using xCommons.Extensions;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
public static partial class XDIHelperExtension {
|
||||
public static partial class XDIHelperExtension
|
||||
{
|
||||
/// <summary>
|
||||
/// Register XCommons Module Services
|
||||
/// </summary>
|
||||
/// <param name="services"></param>
|
||||
public static void AddXCommons (this IServiceCollection services) {
|
||||
services.AddSingleton<XValidationProvider> ();
|
||||
public static void AddXCommons(this IServiceCollection services)
|
||||
{
|
||||
services.AddSingleton<XValidationProvider>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Register XCommons Module Service ...
|
||||
/// </summary>
|
||||
/// <param name="services"></param>
|
||||
/// <param name="configuration"></param>
|
||||
public static void AddXCommons(
|
||||
this IServiceCollection services,
|
||||
IConfiguration configuration
|
||||
)
|
||||
{
|
||||
//
|
||||
services.AddXCommons();
|
||||
services.AddXFileTypeDetector(configuration);
|
||||
}
|
||||
}
|
||||
@@ -21,6 +21,7 @@ using System.Security.Cryptography;
|
||||
using Newtonsoft.Json.Serialization;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Text.RegularExpressions;
|
||||
using xCommons.Configurations;
|
||||
|
||||
namespace xCommons.Extensions
|
||||
{
|
||||
@@ -974,7 +975,7 @@ namespace xCommons.Extensions
|
||||
result.Add(updateWith);
|
||||
|
||||
//
|
||||
return source;
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -1012,7 +1013,7 @@ namespace xCommons.Extensions
|
||||
result.Add(updateWith);
|
||||
|
||||
//
|
||||
return source;
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -1050,7 +1051,27 @@ namespace xCommons.Extensions
|
||||
result.Add(updateWith);
|
||||
|
||||
//
|
||||
return source;
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Converts an Enumerable to HashSet ...
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <param name="source"></param>
|
||||
/// <returns></returns>
|
||||
public static HashSet<T> ToHashSet<T>(this IEnumerable<T> source)
|
||||
{
|
||||
//
|
||||
var result = new HashSet<T>();
|
||||
if (source.IsNull())
|
||||
{
|
||||
return result;
|
||||
}
|
||||
|
||||
//
|
||||
result = [.. source];
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -1628,6 +1649,26 @@ namespace xCommons.Extensions
|
||||
return time.IsExPired();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Check Specified Time is Expired or not ...
|
||||
/// </summary>
|
||||
/// <param name="source"></param>
|
||||
/// <param name="ttlSeconds"></param>
|
||||
/// <returns></returns>
|
||||
public static bool IsExpiredTTL(
|
||||
this DateTime source,
|
||||
int ttlSeconds
|
||||
)
|
||||
{
|
||||
//
|
||||
var now = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
|
||||
var result = now < new DateTimeOffset(source)
|
||||
.ToUnixTimeSeconds() + ttlSeconds;
|
||||
|
||||
//
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines a File Type is Image Kind or not
|
||||
/// </summary>
|
||||
@@ -1800,6 +1841,65 @@ namespace xCommons.Extensions
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Extract RateLimit Rule based on given Path ...
|
||||
/// </summary>
|
||||
/// <param name="source"></param>
|
||||
/// <param name="path"></param>
|
||||
/// <returns></returns>
|
||||
public static XRateLimitRule GetMatchingRule(
|
||||
this XRateLimitConfiguration source,
|
||||
string path
|
||||
)
|
||||
{
|
||||
//
|
||||
if (!source.Enabled)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
//
|
||||
var normalizedPath = path.IsNullOrEmpty()
|
||||
? "/"
|
||||
: path.ToNormalString();
|
||||
|
||||
//
|
||||
var rule = source.Rules.IsNull()
|
||||
? null
|
||||
: source.Rules
|
||||
.Where(r =>
|
||||
!r.IsNull() &&
|
||||
r.Enabled &&
|
||||
!r.PathPrefix.IsNullOrEmpty() &&
|
||||
normalizedPath.StartsWith(r.PathPrefix.ToNormalString()))
|
||||
.OrderByDescending(r => r.PathPrefix.Length)
|
||||
.FirstOrDefault();
|
||||
|
||||
//
|
||||
if (!rule.IsNull())
|
||||
{
|
||||
return rule;
|
||||
}
|
||||
|
||||
//
|
||||
if (source.ApplyToAllRoutes)
|
||||
{
|
||||
//
|
||||
return new XRateLimitRule
|
||||
{
|
||||
Enabled = true,
|
||||
Name = "Default",
|
||||
PathPrefix = "/",
|
||||
Limit = source.DefaultLimit,
|
||||
KeyMode = source.DefaultKeyMode,
|
||||
PeriodSeconds = source.DefaultPeriodSeconds,
|
||||
};
|
||||
}
|
||||
|
||||
//
|
||||
return null;
|
||||
}
|
||||
|
||||
//
|
||||
#region Int Id Extensions ...
|
||||
public static bool IsValidIntId(this int source)
|
||||
@@ -1817,6 +1917,60 @@ namespace xCommons.Extensions
|
||||
}
|
||||
#endregion
|
||||
|
||||
//
|
||||
#region Dictionary Extensions ...
|
||||
/// <summary>
|
||||
/// Converts to Meta Data Representation ...
|
||||
/// </summary>
|
||||
/// <param name="source"></param>
|
||||
/// <returns></returns>
|
||||
public static Dictionary<string, string> AsMetadat(this string source)
|
||||
{
|
||||
//
|
||||
// Validate ...
|
||||
if (source.IsNullOrEmpty())
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
//
|
||||
// JSON is expected to be like: [0.12, 0.34, ...] ...
|
||||
var result = source.FromJSON<Dictionary<string, string>>();
|
||||
if (!result.HasChild())
|
||||
{
|
||||
result = [];
|
||||
}
|
||||
|
||||
//
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Safe Metadata Reader ...
|
||||
/// </summary>
|
||||
/// <param name="source"></param>
|
||||
/// <param name="key"></param>
|
||||
/// <returns></returns>
|
||||
public static string GetMetadata(
|
||||
this IDictionary<string, string> source,
|
||||
string key
|
||||
)
|
||||
{
|
||||
//
|
||||
var result = string.Empty;
|
||||
|
||||
//
|
||||
if (!source.IsNullOrDefault() &&
|
||||
source.TryGetValue(key, out result))
|
||||
{
|
||||
return result;
|
||||
}
|
||||
|
||||
//
|
||||
return result;
|
||||
}
|
||||
#endregion
|
||||
|
||||
//
|
||||
#region StringExtensions for Identity Server ...
|
||||
public static string EnsureTrailingSlash(this string input)
|
||||
@@ -1851,6 +2005,39 @@ namespace xCommons.Extensions
|
||||
return Convert.ToBase64String(hash);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Apply Templates on provided String ...
|
||||
/// </summary>
|
||||
/// <param name="source"></param>
|
||||
/// <param name="templates"></param>
|
||||
/// <returns></returns>
|
||||
public static string ApplyTemplates(
|
||||
this string source,
|
||||
IDictionary<string, string> templates = null
|
||||
)
|
||||
{
|
||||
//
|
||||
// Validate ...
|
||||
if (source.IsNullOrEmpty() ||
|
||||
!templates.HasChild())
|
||||
{
|
||||
return source;
|
||||
}
|
||||
|
||||
//
|
||||
var existsTemplates = templates.Where(
|
||||
x => source.Contains(x.Key)
|
||||
);
|
||||
var result = source;
|
||||
foreach (var template in existsTemplates)
|
||||
{
|
||||
result = result.Replace(template.Key, template.Value);
|
||||
}
|
||||
|
||||
//
|
||||
return result;
|
||||
}
|
||||
#endregion
|
||||
|
||||
//
|
||||
|
||||
+186
-8
@@ -3,6 +3,9 @@ using System.IO;
|
||||
using System.Linq;
|
||||
using xCommons.Filters;
|
||||
using xCommons.Constants;
|
||||
using xCommons.Providers;
|
||||
using xCommons.Interfaces;
|
||||
using xExceptions.Constants;
|
||||
using xCommons.Configurations;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.OpenApi.Models;
|
||||
@@ -17,7 +20,6 @@ namespace xCommons.Extensions
|
||||
{
|
||||
public static partial class DIExtensions
|
||||
{
|
||||
|
||||
/// <summary>
|
||||
/// Inject Specific Registered Service from IServiceCollection
|
||||
/// </summary>
|
||||
@@ -31,16 +33,132 @@ namespace xCommons.Extensions
|
||||
return serviceProvider.GetService<T>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Inject Specific Registered Services from IServiceCollection
|
||||
/// </summary>
|
||||
/// <param name="source"></param>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <returns></returns>
|
||||
public static IEnumerable<T> GetRegisteredServices<T>(this IServiceCollection source)
|
||||
{
|
||||
//
|
||||
var serviceProvider = source.BuildServiceProvider();
|
||||
return serviceProvider.GetServices<T>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Register App Configuration as a Service
|
||||
/// </summary>
|
||||
/// <param name="services"></param>
|
||||
/// <param name="configuration"></param>
|
||||
public static void AddXAppConfiguration(this IServiceCollection services, IConfiguration configuration)
|
||||
/// <param name="environment"></param>
|
||||
public static void AddXAppConfiguration(
|
||||
this IServiceCollection services,
|
||||
IConfiguration configuration,
|
||||
string environment = null
|
||||
)
|
||||
{
|
||||
//
|
||||
var appConfiguration = configuration.GetXAppConfiguration();
|
||||
services.AddSingleton<XAppConfiguration>(appConfiguration);
|
||||
appConfiguration.Environment = environment;
|
||||
|
||||
//
|
||||
services.AddSingleton(appConfiguration);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Retrieve Rate Limit Configurations and Register it ...
|
||||
/// </summary>
|
||||
/// <param name="source"></param>
|
||||
/// <param name="configuration"></param>
|
||||
public static void AddXRateLimitConfiguration(
|
||||
this IServiceCollection source,
|
||||
IConfiguration configuration
|
||||
)
|
||||
{
|
||||
//
|
||||
var config = configuration.GetXRateLimitConfiguration();
|
||||
source.AddXRateLimitConfiguration(config);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Register Rate Limit Configuration ...
|
||||
/// </summary>
|
||||
/// <param name="source"></param>
|
||||
/// <param name="configuration"></param>
|
||||
public static void AddXRateLimitConfiguration(
|
||||
this IServiceCollection source,
|
||||
XRateLimitConfiguration configuration
|
||||
)
|
||||
{
|
||||
//
|
||||
if (source.IsNull())
|
||||
{
|
||||
XException.InvalidConfiguration.Throw();
|
||||
}
|
||||
|
||||
//
|
||||
source.AddSingleton(configuration);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Add Environment name to XAppConfiguration ...
|
||||
/// </summary>
|
||||
/// <param name="app"></param>
|
||||
/// <param name="environmentName"></param>
|
||||
public static void AddEnvironmentToXAppConfiguration(
|
||||
this IApplicationBuilder app,
|
||||
string environmentName
|
||||
)
|
||||
{
|
||||
//
|
||||
// Setting Environment in App Confiuration ...
|
||||
using (var scope = app.ApplicationServices.CreateScope())
|
||||
{
|
||||
//
|
||||
// Inject AppConfiguration ...
|
||||
var appConfiguration = scope.ServiceProvider
|
||||
.GetRequiredService<XAppConfiguration>();
|
||||
if (!appConfiguration.IsNull())
|
||||
{
|
||||
appConfiguration.Environment = environmentName;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Retrieve and Register File Type Detector Configuration ...
|
||||
/// </summary>
|
||||
/// <param name="source"></param>
|
||||
/// <param name="configuration"></param>
|
||||
public static void AddXFileTypeDetectorConfiguration(
|
||||
this IServiceCollection source,
|
||||
IConfiguration configuration
|
||||
)
|
||||
{
|
||||
//
|
||||
var config = configuration.GetXFileTypeDetectorConfiguration();
|
||||
source.AddXFileTypeDetectorConfiguration(config);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Register File Type Detector Configuration ...
|
||||
/// </summary>
|
||||
/// <param name="source"></param>
|
||||
/// <param name="configuration"></param>
|
||||
public static void AddXFileTypeDetectorConfiguration(
|
||||
this IServiceCollection source,
|
||||
XFileTypeDetectorConfiguration configuration
|
||||
)
|
||||
{
|
||||
//
|
||||
if (configuration.IsNull())
|
||||
{
|
||||
configuration = new();
|
||||
}
|
||||
|
||||
//
|
||||
source.AddSingleton(configuration);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -170,9 +288,9 @@ namespace xCommons.Extensions
|
||||
source.AddSecurityDefinition(nameof(XAuthorization.RefreshToken), new OpenApiSecurityScheme
|
||||
{
|
||||
In = ParameterLocation.Header,
|
||||
Description = "refresh token",
|
||||
Description = "Refresh Token",
|
||||
Type = SecuritySchemeType.ApiKey,
|
||||
Name = nameof(XAuthorization.RefreshToken)
|
||||
Name = XAuthorization.RefreshToken
|
||||
});
|
||||
|
||||
//
|
||||
@@ -180,7 +298,7 @@ namespace xCommons.Extensions
|
||||
{
|
||||
new OpenApiSecurityScheme {
|
||||
Reference = new OpenApiReference {
|
||||
Id = nameof (XAuthorization.RefreshToken),
|
||||
Id = nameof(XAuthorization.RefreshToken),
|
||||
Type = ReferenceType.SecurityScheme
|
||||
}
|
||||
}, Array.Empty<string> ()
|
||||
@@ -193,10 +311,10 @@ namespace xCommons.Extensions
|
||||
//
|
||||
source.AddSecurityDefinition(nameof(XAuthorization.ExpiresAt), new OpenApiSecurityScheme
|
||||
{
|
||||
Description = "Expires at",
|
||||
In = ParameterLocation.Header,
|
||||
Description = "expires at",
|
||||
Type = SecuritySchemeType.ApiKey,
|
||||
Name = nameof(XAuthorization.ExpiresAt)
|
||||
Name = XAuthorization.ExpiresAt
|
||||
});
|
||||
|
||||
//
|
||||
@@ -440,6 +558,66 @@ namespace xCommons.Extensions
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Register RateLimit Service ...
|
||||
/// </summary>
|
||||
/// <param name="source"></param>
|
||||
public static void AddXRateLimit(
|
||||
this IServiceCollection source
|
||||
)
|
||||
{
|
||||
//
|
||||
source.AddMemoryCache();
|
||||
source.AddSingleton<IXRateLimitProvider, XRateLimitProvider>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Register RateLimit Service ...
|
||||
/// Configs Retrieved from AppSettings ...
|
||||
/// </summary>
|
||||
/// <param name="source"></param>
|
||||
/// <param name="configuration"></param>
|
||||
public static void AddXRateLimit(
|
||||
this IServiceCollection source,
|
||||
IConfiguration configuration
|
||||
)
|
||||
{
|
||||
//
|
||||
var config = configuration.GetXRateLimitConfiguration();
|
||||
source.AddXRateLimit(config);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Register RateLimit Service ...
|
||||
/// </summary>
|
||||
/// <param name="source"></param>
|
||||
/// <param name="configuration"></param>
|
||||
public static void AddXRateLimit(
|
||||
this IServiceCollection source,
|
||||
XRateLimitConfiguration configuration
|
||||
)
|
||||
{
|
||||
//
|
||||
if (configuration.IsNull())
|
||||
{
|
||||
XException.InvalidConfiguration.Throw();
|
||||
}
|
||||
|
||||
//
|
||||
source.AddXRateLimitConfiguration(configuration);
|
||||
source.AddXRateLimit();
|
||||
}
|
||||
|
||||
public static void AddXFileTypeDetector(
|
||||
this IServiceCollection source,
|
||||
IConfiguration configuration
|
||||
)
|
||||
{
|
||||
//
|
||||
source.AddXFileTypeDetectorConfiguration(configuration);
|
||||
source.AddSingleton<IXFileTypeDetector, XFileTypeDetector>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Use X Registered Cross Origin Resource Sharings
|
||||
/// </summary>
|
||||
|
||||
@@ -63,6 +63,9 @@ namespace xCommons.Extensions {
|
||||
//
|
||||
var idContainer = parts[0];
|
||||
var messageContainer = parts[1];
|
||||
|
||||
//
|
||||
// TODO: Fix this ...
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
@@ -19,9 +19,14 @@ namespace xCommons.Extensions
|
||||
var xMessageResourceTitlesConfigSection = source
|
||||
.GetSection(ConfigurationNodeNames.MESSAGE_RESOURCE_TITLES_NODE);
|
||||
|
||||
//
|
||||
// Read TTL ...
|
||||
int.TryParse(source[nameof(XAppConfiguration.DefaultCacheTtlMinutes)], out int defTTL);
|
||||
|
||||
//
|
||||
var result = new XAppConfiguration
|
||||
{
|
||||
DefaultCacheTtlMinutes = defTTL,
|
||||
Name = source[nameof(XAppConfiguration.Name)],
|
||||
Version = source[nameof(XAppConfiguration.Version)],
|
||||
XPoweredValue = source[nameof(XAppConfiguration.XPoweredValue)],
|
||||
@@ -50,7 +55,45 @@ namespace xCommons.Extensions
|
||||
.GetSection(ConfigurationNodeNames.SWAGGER_NODE);
|
||||
return xSwaggerConfigSection.Get<XSwaggerConfiguration>();
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Retrieve RateLimit Configurations ...
|
||||
/// </summary>
|
||||
/// <param name="source"></param>
|
||||
/// <returns></returns>
|
||||
public static XRateLimitConfiguration GetXRateLimitConfiguration(this IConfiguration source)
|
||||
{
|
||||
//
|
||||
var section = source
|
||||
.GetSection(ConfigurationNodeNames.RATE_LIMIT_NODE);
|
||||
|
||||
//
|
||||
var result = section.Get<XRateLimitConfiguration>();
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Retrieve File Type Detector Configuration ...
|
||||
/// </summary>
|
||||
/// <param name="source"></param>
|
||||
/// <returns></returns>
|
||||
public static XFileTypeDetectorConfiguration GetXFileTypeDetectorConfiguration(this IConfiguration source)
|
||||
{
|
||||
//
|
||||
var section = source
|
||||
.GetSection(ConfigurationNodeNames.FILE_TYPE_DETECTOR_NODE);
|
||||
|
||||
//
|
||||
var result = section.Get<XFileTypeDetectorConfiguration>();
|
||||
if (result.IsNull())
|
||||
{
|
||||
result = new();
|
||||
}
|
||||
|
||||
//
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Converts a ConfigurationSection to object Representation ...
|
||||
/// </summary>
|
||||
@@ -174,6 +217,6 @@ namespace xCommons.Extensions
|
||||
|
||||
//
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,22 +1,105 @@
|
||||
using System.IO;
|
||||
using xCommons.Constants;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
|
||||
namespace xCommons.Extensions {
|
||||
public static partial class XHttpContextExtensions {
|
||||
namespace xCommons.Extensions
|
||||
{
|
||||
public static partial class XHttpContextExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Convert IFormFile to Bytes Array
|
||||
/// </summary>
|
||||
/// <param name="source"></param>
|
||||
/// <returns></returns>
|
||||
public static byte[] ToByteArray (this IFormFile source) {
|
||||
public static byte[] ToByteArray(this IFormFile source)
|
||||
{
|
||||
//
|
||||
byte[] data;
|
||||
using (var br = new BinaryReader (source.OpenReadStream ())) {
|
||||
data = br.ReadBytes ((int) source.OpenReadStream ().Length);
|
||||
using (var br = new BinaryReader(source.OpenReadStream()))
|
||||
{
|
||||
data = br.ReadBytes((int)source.OpenReadStream().Length);
|
||||
}
|
||||
|
||||
//
|
||||
return data;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Extract Rate Limit Key ...
|
||||
/// </summary>
|
||||
/// <param name="source"></param>
|
||||
/// <param name="keyMode"></param>
|
||||
/// <returns></returns>
|
||||
public static string GetXRateLimitKey(
|
||||
this HttpContext source,
|
||||
XRateLimitKeyMode keyMode
|
||||
)
|
||||
{
|
||||
//
|
||||
if (source.IsNull())
|
||||
{
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
//
|
||||
switch (keyMode)
|
||||
{
|
||||
//
|
||||
case XRateLimitKeyMode.ClientId:
|
||||
{
|
||||
//
|
||||
var clientId = source.Request.Headers[XRateLimitConstants.ClientIdHeader].ToString();
|
||||
return clientId.IsNullOrEmpty()
|
||||
? "anonymous"
|
||||
: clientId.ToNormalString();
|
||||
}
|
||||
|
||||
//
|
||||
case XRateLimitKeyMode.User:
|
||||
{
|
||||
//
|
||||
var userId = source.User?.FindFirst(XCustomClaims.UserId)?.Value;
|
||||
if (userId.IsNullOrEmpty())
|
||||
{
|
||||
userId = source.User?.Identity?.Name;
|
||||
}
|
||||
|
||||
//
|
||||
return userId.IsNullOrEmpty()
|
||||
? "anonymous"
|
||||
: userId.ToNormalString();
|
||||
}
|
||||
|
||||
//
|
||||
case XRateLimitKeyMode.Route:
|
||||
{
|
||||
//
|
||||
return string.Format(
|
||||
"{0}:{1}",
|
||||
source.Request.Method,
|
||||
source.Request.Path
|
||||
).ToNormalString();
|
||||
}
|
||||
|
||||
//
|
||||
case XRateLimitKeyMode.Custom:
|
||||
{
|
||||
return "custom";
|
||||
}
|
||||
|
||||
//
|
||||
case XRateLimitKeyMode.Ip:
|
||||
default:
|
||||
{
|
||||
//
|
||||
return source.Connection.RemoteIpAddress
|
||||
.IsNull()
|
||||
? "unknown"
|
||||
: source.Connection.RemoteIpAddress
|
||||
.ToString()
|
||||
.ToNormalString();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,284 @@
|
||||
using System;
|
||||
using System.Net;
|
||||
using System.Linq;
|
||||
using System.Net.Http;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using System.Collections.Generic;
|
||||
using Microsoft.AspNetCore.Hosting.Server;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.AspNetCore.Hosting.Server.Features;
|
||||
|
||||
namespace xCommons.Extensions
|
||||
{
|
||||
/// <summary>
|
||||
/// All Extensions around Http ...
|
||||
/// </summary>
|
||||
public static class XHttpExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Write Response as JSON ...
|
||||
/// </summary>
|
||||
/// <param name="source"></param>
|
||||
/// <param name="status"></param>
|
||||
/// <param name="data"></param>
|
||||
/// <returns></returns>
|
||||
public static async Task WriteResponseAsJsonAsync(
|
||||
this HttpContext source,
|
||||
HttpStatusCode status,
|
||||
object data
|
||||
)
|
||||
{
|
||||
//
|
||||
await source.Response.WriteJsonAsync(
|
||||
data: data,
|
||||
status: status
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Write JSON ...
|
||||
/// </summary>
|
||||
/// <param name="source"></param>
|
||||
/// <param name="status"></param>
|
||||
/// <param name="data"></param>
|
||||
/// <returns></returns>
|
||||
public static async Task WriteJsonAsync(
|
||||
this HttpResponse source,
|
||||
HttpStatusCode status,
|
||||
object data
|
||||
)
|
||||
{
|
||||
//
|
||||
source.StatusCode = (int)status;
|
||||
source.ContentType = "application/json; charset=utf-8";
|
||||
var json = data.ToJSON();
|
||||
|
||||
//
|
||||
await source.WriteAsync(json);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Copy Request Headers ...
|
||||
/// </summary>
|
||||
/// <param name="source"></param>
|
||||
/// <param name="dest"></param>
|
||||
/// <param name="exceptions"></param>
|
||||
public static void CopyRequestHeaders(
|
||||
this HttpContext source,
|
||||
HttpContent dest,
|
||||
string[] exceptions = null
|
||||
)
|
||||
{
|
||||
//
|
||||
if (dest.IsNull() || source.IsNull())
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
//
|
||||
source.Request.CopyHeaders(
|
||||
dest: dest,
|
||||
exceptions: exceptions
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Copy Request Headers ...
|
||||
/// </summary>
|
||||
/// <param name="source"></param>
|
||||
/// <param name="dest"></param>
|
||||
/// <param name="exceptions"></param>
|
||||
public static void CopyRequestHeaders(
|
||||
this HttpContext source,
|
||||
HttpRequestMessage dest,
|
||||
string[] exceptions = null
|
||||
)
|
||||
{
|
||||
//
|
||||
if (dest.IsNull() || source.IsNull())
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
//
|
||||
source.Request.CopyHeaders(
|
||||
dest: dest,
|
||||
exceptions: exceptions
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Copy Headers ...
|
||||
/// </summary>
|
||||
/// <param name="source"></param>
|
||||
/// <param name="dest"></param>
|
||||
/// <param name="exceptions"></param>
|
||||
public static void CopyHeaders(
|
||||
this HttpRequest source,
|
||||
HttpContent dest,
|
||||
string[] exceptions = null
|
||||
)
|
||||
{
|
||||
//
|
||||
if (dest.IsNull() || source.IsNull())
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
//
|
||||
foreach (var header in source.Headers)
|
||||
{
|
||||
//
|
||||
if (
|
||||
exceptions.HasChild() &&
|
||||
exceptions.Any(xh => xh.Equals(header.Key, StringComparison.InvariantCultureIgnoreCase))
|
||||
)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
//
|
||||
dest.Headers.TryAddWithoutValidation(
|
||||
name: header.Key,
|
||||
values: [.. header.Value]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Copy Headers ...
|
||||
/// </summary>
|
||||
/// <param name="source"></param>
|
||||
/// <param name="dest"></param>
|
||||
/// <param name="exceptions"></param>
|
||||
public static void CopyHeaders(
|
||||
this HttpRequest source,
|
||||
HttpRequestMessage dest,
|
||||
string[] exceptions = null
|
||||
)
|
||||
{
|
||||
//
|
||||
if (dest.IsNull() || source.IsNull())
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
//
|
||||
foreach (var header in source.Headers)
|
||||
{
|
||||
//
|
||||
if (
|
||||
exceptions.HasChild() &&
|
||||
exceptions.Any(xh => xh.Equals(header.Key, StringComparison.InvariantCultureIgnoreCase))
|
||||
)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
//
|
||||
dest.Headers.TryAddWithoutValidation(
|
||||
name: header.Key,
|
||||
values: [.. header.Value]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Copy Headers ...
|
||||
/// </summary>
|
||||
/// <param name="source"></param>
|
||||
/// <param name="context"></param>
|
||||
/// <param name="exceptions"></param>
|
||||
public static void CopyHeaders(
|
||||
this HttpResponseMessage source,
|
||||
HttpContext context,
|
||||
string[] exceptions = null
|
||||
)
|
||||
{
|
||||
//
|
||||
// Validate ...
|
||||
if (source.IsNull() || context.IsNull())
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
//
|
||||
source.CopyHeaders(
|
||||
exceptions: exceptions,
|
||||
response: context.Response
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Copy Headers ...
|
||||
/// </summary>
|
||||
/// <param name="source"></param>
|
||||
/// <param name="response"></param>
|
||||
/// <param name="exceptions"></param>
|
||||
public static void CopyHeaders(
|
||||
this HttpResponseMessage source,
|
||||
HttpResponse response,
|
||||
string[] exceptions = null
|
||||
)
|
||||
{
|
||||
//
|
||||
// Validate ...
|
||||
if (source.IsNull() || response.IsNull())
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
//
|
||||
foreach (var header in source.Headers)
|
||||
{
|
||||
//
|
||||
if (
|
||||
exceptions.HasChild() &&
|
||||
exceptions.Any(xh => xh.Equals(header.Key, StringComparison.InvariantCultureIgnoreCase))
|
||||
)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
//
|
||||
response.Headers[header.Key] = header.Value.ToArray();
|
||||
}
|
||||
|
||||
//
|
||||
foreach (var header in source.Content.Headers)
|
||||
{
|
||||
//
|
||||
if (
|
||||
exceptions.HasChild() &&
|
||||
exceptions.Any(xh => xh.Equals(header.Key, StringComparison.InvariantCultureIgnoreCase))
|
||||
)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
//
|
||||
response.Headers[header.Key] = header.Value.ToArray();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Extract Application Urls ...
|
||||
/// </summary>
|
||||
/// <param name="services"></param>
|
||||
/// <returns></returns>
|
||||
public static ICollection<string> GetApplicationUrls(
|
||||
this IServiceProvider services
|
||||
)
|
||||
{
|
||||
//
|
||||
var server = services.GetService<IServer>();
|
||||
var addresses = server?.Features.Get<IServerAddressesFeature>();
|
||||
var result = addresses?.Addresses ?? Array.Empty<string>();
|
||||
|
||||
//
|
||||
return result;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -3,14 +3,18 @@ using Microsoft.AspNetCore.Builder;
|
||||
|
||||
namespace xCommons.Extensions
|
||||
{
|
||||
public static class XMiddlewareExtensions
|
||||
public static partial class XMiddlewareExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Use XRequestLogger Middleware for log Requests ...
|
||||
/// Use XRateLimit Middleware ...
|
||||
/// </summary>
|
||||
/// <param name="app"></param>
|
||||
public static void UseXRequestLogger(this IApplicationBuilder app) {
|
||||
app.UseMiddleware<XRequestLogger>();
|
||||
/// <param name="source"></param>
|
||||
/// <returns></returns>
|
||||
public static IApplicationBuilder UseXRateLimit(
|
||||
this IApplicationBuilder source
|
||||
)
|
||||
{
|
||||
return source.UseMiddleware<XRateLimitMiddleware>();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,13 +0,0 @@
|
||||
using System;
|
||||
|
||||
namespace xCommons.Helpers {
|
||||
public partial class XDateHelper {
|
||||
/// <summary>
|
||||
/// retrieve utc now timestam unix like representation ...
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public static long UtcNowTimespan () {
|
||||
return DateTimeOffset.UtcNow.ToUnixTimeMilliseconds ();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,420 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using xCommons.Models;
|
||||
using System.Reflection;
|
||||
using xCommons.Constants;
|
||||
using xCommons.Extensions;
|
||||
using xExceptions.Attributes;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace xCommons.Helpers
|
||||
{
|
||||
/// <summary>
|
||||
/// File Helper ...
|
||||
/// </summary>
|
||||
public static class XFileHelper
|
||||
{
|
||||
/// <summary>
|
||||
/// Cache Data ...
|
||||
/// </summary>
|
||||
private static readonly Lazy<IReadOnlyList<XFileTypeInfo>> _cache =
|
||||
new(Build, isThreadSafe: true);
|
||||
|
||||
/// <summary>
|
||||
/// Retrieve List ...
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public static IReadOnlyList<XFileTypeInfo> GetAll() => _cache.Value;
|
||||
|
||||
/// <summary>
|
||||
/// Normalize File Extension ...
|
||||
/// </summary>
|
||||
/// <param name="extension"></param>
|
||||
/// <returns></returns>
|
||||
public static string NormalizeExtension(string extension)
|
||||
{
|
||||
//
|
||||
var result = extension;
|
||||
|
||||
//
|
||||
if (result.IsNullOrEmpty())
|
||||
{
|
||||
return result;
|
||||
}
|
||||
|
||||
//
|
||||
result = result.Trim();
|
||||
if (result.IsNullOrEmpty())
|
||||
{
|
||||
return result;
|
||||
}
|
||||
|
||||
//
|
||||
if (result == ".")
|
||||
{
|
||||
//
|
||||
result = string.Empty;
|
||||
return result;
|
||||
}
|
||||
|
||||
//
|
||||
result = result.StartsWith(".")
|
||||
? result.ToLowerInvariant()
|
||||
: "." + result.ToLowerInvariant();
|
||||
|
||||
//
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Check a File Extension is Supported or not ...
|
||||
/// </summary>
|
||||
/// <param name="extension"></param>
|
||||
/// <returns></returns>
|
||||
public static bool IsSupported(string extension)
|
||||
{
|
||||
//
|
||||
var info = GetByExtension(extension);
|
||||
var result = !info.IsNull();
|
||||
|
||||
//
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Detect File Info based On Extension ...
|
||||
/// </summary>
|
||||
/// <param name="extension"></param>
|
||||
/// <returns></returns>
|
||||
public static XFileTypeInfo GetByExtension(string extension)
|
||||
{
|
||||
//
|
||||
XFileTypeInfo result = null;
|
||||
|
||||
//
|
||||
// Validate ...
|
||||
if (extension.IsNullOrEmpty())
|
||||
{
|
||||
return result;
|
||||
}
|
||||
|
||||
//
|
||||
var normalized = NormalizeExtension(extension);
|
||||
|
||||
//
|
||||
// Detect Item ...
|
||||
result = GetAll()
|
||||
.FirstOrDefault(x =>
|
||||
x.Extension.Equals(
|
||||
normalized,
|
||||
StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
//
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Detect File Info based on Mime Type ...
|
||||
/// </summary>
|
||||
/// <param name="mimeType"></param>
|
||||
/// <returns></returns>
|
||||
public static XFileTypeInfo GetByMimeType(string mimeType)
|
||||
{
|
||||
//
|
||||
XFileTypeInfo result = null;
|
||||
|
||||
//
|
||||
// Validate ...
|
||||
if (mimeType.IsNullOrEmpty())
|
||||
{
|
||||
return result;
|
||||
}
|
||||
|
||||
//
|
||||
result = GetAll()
|
||||
.FirstOrDefault(x =>
|
||||
x.MimeType.Equals(
|
||||
mimeType.Trim(),
|
||||
StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
//
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Detect File Info based on Enum Member Name ...
|
||||
/// </summary>
|
||||
/// <param name="name"></param>
|
||||
/// <returns></returns>
|
||||
public static XFileTypeInfo GetByName(string name)
|
||||
{
|
||||
//
|
||||
XFileTypeInfo result = null;
|
||||
|
||||
//
|
||||
// Validate ...
|
||||
if (name.IsNullOrEmpty())
|
||||
{
|
||||
return result;
|
||||
}
|
||||
|
||||
//
|
||||
result = GetAll()
|
||||
.FirstOrDefault(x =>
|
||||
x.Name.Equals(
|
||||
name.Trim(),
|
||||
StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
//
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Detect File Info based on Enum Member Value ...
|
||||
/// </summary>
|
||||
/// <param name="value"></param>
|
||||
/// <returns></returns>
|
||||
public static XFileTypeInfo GetByValue(int value)
|
||||
{
|
||||
//
|
||||
var result = GetAll()
|
||||
.FirstOrDefault(x => x.Value == value);
|
||||
|
||||
//
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Try Get File Info By Extension ...
|
||||
/// </summary>
|
||||
/// <param name="extension"></param>
|
||||
/// <param name="result"></param>
|
||||
/// <returns></returns>
|
||||
public static bool TryGetByExtension(
|
||||
string extension,
|
||||
out XFileTypeInfo result
|
||||
)
|
||||
{
|
||||
result = GetByExtension(extension);
|
||||
return result != null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Try Get File Info By Mime Type ...
|
||||
/// </summary>
|
||||
/// <param name="mimeType"></param>
|
||||
/// <param name="result"></param>
|
||||
/// <returns></returns>
|
||||
public static bool TryGetByMimeType(
|
||||
string mimeType,
|
||||
out XFileTypeInfo result
|
||||
)
|
||||
{
|
||||
result = GetByMimeType(mimeType);
|
||||
return result != null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get Mime Type based on Extension ...
|
||||
/// </summary>
|
||||
/// <param name="extension"></param>
|
||||
/// <returns></returns>
|
||||
public static string GetMimeType(string extension)
|
||||
{
|
||||
//
|
||||
var result = string.Empty;
|
||||
var info = GetByExtension(extension);
|
||||
if (!info.IsNull())
|
||||
{
|
||||
result = info.MimeType;
|
||||
}
|
||||
|
||||
//
|
||||
return result;
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get Extension based on Mime Type ...
|
||||
/// </summary>
|
||||
/// <param name="mimeType"></param>
|
||||
/// <returns></returns>
|
||||
public static string GetExtension(string mimeType)
|
||||
{
|
||||
//
|
||||
var result = string.Empty;
|
||||
var info = GetByMimeType(mimeType);
|
||||
if (!info.IsNull())
|
||||
{
|
||||
result = info.Extension;
|
||||
}
|
||||
|
||||
//
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get File Category based on Value ...
|
||||
/// </summary>
|
||||
/// <param name="value"></param>
|
||||
/// <returns></returns>
|
||||
public static XFileCategory? GetCategory(int value)
|
||||
{
|
||||
//
|
||||
if (value >= 100 && value < 200) return XFileCategory.Document;
|
||||
if (value >= 200 && value < 300) return XFileCategory.Archive;
|
||||
if (value >= 300 && value < 400) return XFileCategory.Internal;
|
||||
if (value >= 400 && value < 500) return XFileCategory.Video;
|
||||
if (value >= 500 && value < 600) return XFileCategory.Audio;
|
||||
if (value >= 600 && value < 700) return XFileCategory.Image;
|
||||
|
||||
//
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get File Category based on Extension ...
|
||||
/// </summary>
|
||||
/// <param name="extension"></param>
|
||||
/// <returns></returns>
|
||||
public static XFileCategory? GetCategory(string extension)
|
||||
{
|
||||
//
|
||||
var info = GetByExtension(extension);
|
||||
var result = !info.IsNull()
|
||||
? GetCategory(info.Value)
|
||||
: null;
|
||||
|
||||
//
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get all Specified Category File Type Info ...
|
||||
/// </summary>
|
||||
/// <param name="category"></param>
|
||||
/// <returns></returns>
|
||||
public static IReadOnlyList<XFileTypeInfo> GetByCategory(XFileCategory category)
|
||||
{
|
||||
//
|
||||
var min = (int)category;
|
||||
var max = min + 100;
|
||||
|
||||
//
|
||||
var result = GetAll()
|
||||
.Where(x => x.Value >= min && x.Value < max)
|
||||
.ToList()
|
||||
.AsReadOnly();
|
||||
|
||||
//
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get All Supported Extensions ...
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public static IReadOnlyList<string> GetExtensions()
|
||||
{
|
||||
//
|
||||
var result = GetAll()
|
||||
.Select(x => x.Extension)
|
||||
.ToList()
|
||||
.AsReadOnly();
|
||||
|
||||
//
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get All Supported Mime Types ...
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public static IReadOnlyList<string> GetMimeTypes()
|
||||
{
|
||||
//
|
||||
var result = GetAll()
|
||||
.Select(x => x.MimeType)
|
||||
.Where(m => !string.IsNullOrWhiteSpace(m))
|
||||
.Distinct(StringComparer.OrdinalIgnoreCase)
|
||||
.ToList()
|
||||
.AsReadOnly();
|
||||
|
||||
//
|
||||
return result;
|
||||
}
|
||||
|
||||
//
|
||||
#region Private ...
|
||||
/// <summary>
|
||||
/// Build List ...
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
private static IReadOnlyList<XFileTypeInfo> Build()
|
||||
{
|
||||
//
|
||||
var extensions = ReadEnum<XFileExtensions>();
|
||||
var mimeTypes = ReadEnum<XFileMimeTypes>();
|
||||
|
||||
//
|
||||
var list = new List<XFileTypeInfo>(extensions.Count);
|
||||
foreach (var ext in extensions.Values.OrderBy(e => e.Value))
|
||||
{
|
||||
//
|
||||
mimeTypes.TryGetValue(ext.Value, out var mime);
|
||||
list.Add(new XFileTypeInfo
|
||||
{
|
||||
Name = ext.Name,
|
||||
Value = ext.Value,
|
||||
Extension = ext.StringValue,
|
||||
MimeType = mime.StringValue ?? string.Empty
|
||||
});
|
||||
}
|
||||
|
||||
//
|
||||
var result = list.AsReadOnly();
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Read Enum ...
|
||||
/// </summary>
|
||||
/// <typeparam name="TEnum"></typeparam>
|
||||
/// <returns></returns>
|
||||
private static Dictionary<int, EnumEntry> ReadEnum<TEnum>()
|
||||
where TEnum : struct, Enum
|
||||
{
|
||||
//
|
||||
var map = new Dictionary<int, EnumEntry>();
|
||||
foreach (var field in typeof(TEnum).GetFields(BindingFlags.Public | BindingFlags.Static))
|
||||
{
|
||||
//
|
||||
var attr = field.GetCustomAttribute<StringValueAttribute>();
|
||||
if (attr == null) continue;
|
||||
var value = Convert.ToInt32(field.GetValue(null));
|
||||
|
||||
//
|
||||
map[value] = new EnumEntry
|
||||
{
|
||||
Value = value,
|
||||
Name = field.Name,
|
||||
StringValue = attr.StringValue
|
||||
};
|
||||
}
|
||||
|
||||
//
|
||||
return map;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Enum Entries for Read ...
|
||||
/// </summary>
|
||||
private struct EnumEntry
|
||||
{
|
||||
public int Value { get; set; }
|
||||
public string Name { get; set; }
|
||||
public string StringValue { get; set; }
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
using System.IO;
|
||||
using xCommons.Models;
|
||||
using System.Threading;
|
||||
using xCommons.Constants;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace xCommons.Interfaces
|
||||
{
|
||||
public interface IXFileTypeDetector
|
||||
{
|
||||
/// <summary>
|
||||
/// Detect MIME Type based on File Name ...
|
||||
/// </summary>
|
||||
/// <param name="fileName"></param>
|
||||
/// <returns></returns>
|
||||
string DetectFromExtension(string fileName);
|
||||
|
||||
/// <summary>
|
||||
/// Detect XFileExtensions based on File Name ...
|
||||
/// </summary>
|
||||
/// <param name="fileName"></param>
|
||||
/// <returns></returns>
|
||||
XFileExtensions? DetectExtension(string fileName);
|
||||
|
||||
/// <summary>
|
||||
/// Detect Type based on File's Magic Byte ...
|
||||
/// </summary>
|
||||
/// <param name="stream"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
Task<string> DetectFromMagicBytesAsync(
|
||||
Stream stream,
|
||||
CancellationToken cancellationToken = default
|
||||
);
|
||||
|
||||
/// <summary>
|
||||
/// Complexity Detect Type ...
|
||||
/// </summary>
|
||||
/// <param name="fileName"></param>
|
||||
/// <param name="providedMimeType"></param>
|
||||
/// <param name="stream"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
Task<XFileTypeDetectionResult> DetectAsync(
|
||||
string fileName,
|
||||
string providedMimeType,
|
||||
Stream stream,
|
||||
CancellationToken cancellationToken = default
|
||||
);
|
||||
|
||||
/// <summary>
|
||||
/// Check a File Extension is Known or not ...
|
||||
/// </summary>
|
||||
/// <param name="fileName"></param>
|
||||
/// <returns></returns>
|
||||
bool IsKnownExtension(string fileName);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
using xCommons.Models;
|
||||
using xCommons.Configurations;
|
||||
|
||||
namespace xCommons.Interfaces
|
||||
{
|
||||
public interface IXRateLimitProvider
|
||||
{
|
||||
bool IsEnabled { get; }
|
||||
|
||||
XRateLimitResult TryConsume(
|
||||
string key,
|
||||
int limit,
|
||||
int periodSeconds
|
||||
);
|
||||
|
||||
XRateLimitResult TryConsume(
|
||||
string key,
|
||||
XRateLimitRule rule
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
using System.Net;
|
||||
using xCommons.Models;
|
||||
using xCommons.Constants;
|
||||
using xCommons.Attributes;
|
||||
using xCommons.Extensions;
|
||||
using xCommons.Interfaces;
|
||||
using System.Threading.Tasks;
|
||||
using xCommons.Configurations;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Http.Features;
|
||||
|
||||
namespace xCommons.Middlewares
|
||||
{
|
||||
public class XRateLimitMiddleware
|
||||
{
|
||||
//
|
||||
private readonly RequestDelegate next;
|
||||
private readonly IXRateLimitProvider provider;
|
||||
private readonly XRateLimitConfiguration configuration;
|
||||
|
||||
public XRateLimitMiddleware(
|
||||
RequestDelegate next,
|
||||
IXRateLimitProvider provider,
|
||||
XRateLimitConfiguration configuration
|
||||
)
|
||||
{
|
||||
//
|
||||
this.next = next;
|
||||
this.provider = provider;
|
||||
this.configuration = configuration;
|
||||
}
|
||||
|
||||
public async Task InvokeAsync(HttpContext context)
|
||||
{
|
||||
//
|
||||
if (!provider.IsEnabled)
|
||||
{
|
||||
await next(context);
|
||||
return;
|
||||
}
|
||||
|
||||
//
|
||||
var endpoint = context.Features.Get<IEndpointFeature>()?.Endpoint;
|
||||
if (!endpoint.IsNull() &&
|
||||
!endpoint.Metadata
|
||||
.GetMetadata<XRateLimitAttribute>()
|
||||
.IsNull()
|
||||
)
|
||||
{
|
||||
//
|
||||
await next(context);
|
||||
return;
|
||||
}
|
||||
|
||||
//
|
||||
var rule = configuration.GetMatchingRule(context.Request.Path);
|
||||
if (rule.IsNull())
|
||||
{
|
||||
await next(context);
|
||||
return;
|
||||
}
|
||||
|
||||
//
|
||||
var key = context.GetXRateLimitKey(rule.KeyMode);
|
||||
var result = provider.TryConsume(key, rule);
|
||||
|
||||
//
|
||||
WriteHeaders(context, result);
|
||||
|
||||
//
|
||||
if (!result.IsAllowed)
|
||||
{
|
||||
//
|
||||
await context.WriteResponseAsJsonAsync(
|
||||
status: (HttpStatusCode)configuration.StatusCode,
|
||||
data: new
|
||||
{
|
||||
message = "Too many requests. Please try again later.",
|
||||
retryAfter = result.RetryAfterSeconds,
|
||||
resetOn = result.ResetOn
|
||||
}
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
//
|
||||
await next(context);
|
||||
}
|
||||
|
||||
private static void WriteHeaders(
|
||||
HttpContext context,
|
||||
XRateLimitResult result
|
||||
)
|
||||
{
|
||||
//
|
||||
context.Response.Headers[XRateLimitConstants.LimitHeader] =
|
||||
result.Limit.ToString();
|
||||
|
||||
//
|
||||
context.Response.Headers[XRateLimitConstants.RemainingHeader] =
|
||||
result.Remaining.ToString();
|
||||
|
||||
//
|
||||
context.Response.Headers[XRateLimitConstants.ResetHeader] =
|
||||
result.ResetOn.ToUnixTimeSeconds().ToString();
|
||||
|
||||
//
|
||||
if (!result.IsAllowed)
|
||||
{
|
||||
context.Response.Headers[XRateLimitConstants.RetryAfterHeader] =
|
||||
result.RetryAfterSeconds.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,144 +0,0 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using xCommons.Models;
|
||||
using xCommons.Extensions;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace xCommons.Middlewares {
|
||||
public partial class XRequestLogger {
|
||||
|
||||
private readonly ILogger logger;
|
||||
private readonly RequestDelegate next;
|
||||
|
||||
public XRequestLogger (
|
||||
RequestDelegate next,
|
||||
ILoggerFactory loggerFactory
|
||||
) {
|
||||
//
|
||||
this.next = next;
|
||||
this.logger = loggerFactory
|
||||
.CreateLogger<XRequestLogger> ();
|
||||
}
|
||||
|
||||
public async Task InvokeAsync (HttpContext context) {
|
||||
//
|
||||
var logModel = new XLoggerModel ();
|
||||
|
||||
//
|
||||
logModel.Path = context.Request.Path;
|
||||
logModel.Schema = context.Request.Scheme;
|
||||
logModel.Method = context.Request.Method;
|
||||
logModel.Headers = context.Request.Headers;
|
||||
logModel.Host = context.Request.Host.ToString ();
|
||||
logModel.QueryString = context.Request.QueryString.ToString ();
|
||||
logModel.UserID = context.User.Identity.IsAuthenticated ? context.User.Identity.Name : "Not Authenticated";
|
||||
|
||||
//
|
||||
logModel.Connection = new XLoggerHttpConnection {
|
||||
Id = context.Connection.Id,
|
||||
RemoteIpAddress = context.Connection.RemoteIpAddress.ToString (),
|
||||
RemotePort = context.Connection.RemotePort.ToString (),
|
||||
LocalIpAddress = context.Connection.LocalIpAddress.ToString (),
|
||||
LocalPort = context.Connection.LocalPort.ToString (),
|
||||
};
|
||||
|
||||
//
|
||||
// Check if a request is a Post Call so read data from Body ...
|
||||
if (context.Request.Method.ToNormalString () == "post") {
|
||||
//
|
||||
context.Request.EnableBuffering ();
|
||||
var request = await new StreamReader (context.Request.Body)
|
||||
.ReadToEndAsync ();
|
||||
|
||||
//
|
||||
context.Request.Body.Position = 0;
|
||||
logModel.Request = request;
|
||||
}
|
||||
|
||||
//
|
||||
logModel.RequestedOn = DateTime.UtcNow;
|
||||
|
||||
//
|
||||
// Do Request ...
|
||||
await next.Invoke (context);
|
||||
|
||||
//
|
||||
using (Stream originalRequest = context.Response.Body) {
|
||||
try {
|
||||
using (var memStream = new MemoryStream ()) {
|
||||
//
|
||||
context.Response.Body = memStream;
|
||||
|
||||
//
|
||||
// All the Request processing as described above
|
||||
// happens from here.
|
||||
// Response handling starts from here
|
||||
// set the pointer to the beginning of the
|
||||
// memory stream to read
|
||||
memStream.Position = 0;
|
||||
|
||||
//
|
||||
// read the memory stream till the end
|
||||
var response = await new StreamReader (memStream)
|
||||
.ReadToEndAsync ();
|
||||
|
||||
//
|
||||
logModel.Response = response;
|
||||
logModel.RespondedOn = DateTime.UtcNow;
|
||||
logModel.StatusCode = context.Response.StatusCode;
|
||||
logModel.IsSucceed = context.Response.StatusCode >= 200 && context.Response.StatusCode <= 299;
|
||||
|
||||
//
|
||||
// since we have read till the end of the stream,
|
||||
// reset it onto the first position
|
||||
memStream.Position = 0;
|
||||
|
||||
//
|
||||
// now copy the content of the temporary memory
|
||||
// stream we have passed to the actual response body
|
||||
// which will carry the response out.
|
||||
await memStream.CopyToAsync (originalRequest);
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
//
|
||||
// Log Exception ...
|
||||
logger.LogError ($"Error on Logging Request/Response ... {ex.ToJSON()}");
|
||||
} finally {
|
||||
//
|
||||
// assign the response body to the actual context
|
||||
context.Response.Body = originalRequest;
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
// Log Response ...
|
||||
logger.LogCritical ($"Http Response/Response Information:{Environment.NewLine}" +
|
||||
$"Schema:{logModel.Schema} " + Environment.NewLine +
|
||||
$"Host: {logModel.Host} " + Environment.NewLine +
|
||||
$"Path: {logModel.Path} " + Environment.NewLine +
|
||||
$"Method: {logModel.Method} " + Environment.NewLine +
|
||||
$"UserID: {logModel.UserID} " + Environment.NewLine +
|
||||
$"QueryString: {context.Request.QueryString} " + Environment.NewLine +
|
||||
$"Headers: {logModel.Headers.ToJSON()}" + Environment.NewLine +
|
||||
$"" + Environment.NewLine +
|
||||
$"Http Connection: " + Environment.NewLine +
|
||||
$"Id: {logModel.Connection.Id}" + Environment.NewLine +
|
||||
$"RemoteIpAddress: {logModel.Connection.RemoteIpAddress}" + Environment.NewLine +
|
||||
$"RemotePort: {logModel.Connection.RemotePort}" + Environment.NewLine +
|
||||
$"LocalIpAddress: {logModel.Connection.LocalIpAddress}" + Environment.NewLine +
|
||||
$"LocalPort: {logModel.Connection.LocalPort}" + Environment.NewLine +
|
||||
$"" + Environment.NewLine +
|
||||
$"Request Body: {logModel.Request}" + Environment.NewLine +
|
||||
$"RequestedOn: {logModel.RequestedOn}" + Environment.NewLine +
|
||||
$"" + Environment.NewLine +
|
||||
$"IsSucceed: {logModel.IsSucceed}" + Environment.NewLine +
|
||||
$"StatucCode: {logModel.StatusCode}" + Environment.NewLine +
|
||||
$"Response Body: {logModel.Response}" + Environment.NewLine +
|
||||
$"RespondedOn: {logModel.RespondedOn}" + Environment.NewLine +
|
||||
$"" + Environment.NewLine
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
using xCommons.Constants;
|
||||
|
||||
namespace xCommons.Models
|
||||
{
|
||||
public class XFileTypeDetectionResult
|
||||
{
|
||||
/// <summary>
|
||||
/// File Mime Type ...
|
||||
/// </summary>
|
||||
public string MimeType { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// File Extension ...
|
||||
/// </summary>
|
||||
public string Extension { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Type Detection Source ...
|
||||
/// </summary>
|
||||
public XFileTypeDetectionSource Source { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
namespace xCommons.Models
|
||||
{
|
||||
public class XFileTypeInfo
|
||||
{
|
||||
/// <summary>
|
||||
/// Enum Value ...
|
||||
/// </summary>
|
||||
public int Value { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Enum Item Name as String ...
|
||||
/// </summary>
|
||||
public string Name { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Extension as String ...
|
||||
/// </summary>
|
||||
public string Extension { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Mime Type as String ...
|
||||
/// </summary>
|
||||
public string MimeType { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Override To String ...
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public override string ToString()
|
||||
{
|
||||
//
|
||||
var result = $"{Name} ({Extension}) -> {MimeType} [{Value}]";
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,19 +3,20 @@ using Microsoft.AspNetCore.Http;
|
||||
|
||||
namespace xCommons.Models {
|
||||
public class XLoggerModel {
|
||||
public string Schema { get; set; }
|
||||
public string Host { get; set; }
|
||||
public string Path { get; set; }
|
||||
public string Schema { get; set; }
|
||||
public string Method { get; set; }
|
||||
public string UserID { get; set; }
|
||||
public string QueryString { get; set; }
|
||||
public IHeaderDictionary Headers { get; set; }
|
||||
public string Request { get; set; }
|
||||
public int StatusCode { get; set; }
|
||||
public bool IsSucceed { get; set; }
|
||||
public string Response { get; set; }
|
||||
public string QueryString { get; set; }
|
||||
public DateTime RequestedOn { get; set; }
|
||||
public DateTime RespondedOn { get; set; }
|
||||
public IHeaderDictionary Headers { get; set; }
|
||||
public Exception Exception { get; set; } = null;
|
||||
public XLoggerHttpConnection Connection { get; set; }
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
using System;
|
||||
|
||||
namespace xCommons.Models
|
||||
{
|
||||
public class XRateLimitCounter
|
||||
{
|
||||
public int Count { get; set; }
|
||||
public int Limit { get; set; }
|
||||
public DateTimeOffset ResetOn { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
using System;
|
||||
|
||||
namespace xCommons.Models
|
||||
{
|
||||
public class XRateLimitResult
|
||||
{
|
||||
public int Limit { get; set; }
|
||||
public string Key { get; set; }
|
||||
public int Remaining { get; set; }
|
||||
public bool IsAllowed { get; set; }
|
||||
public int RetryAfterSeconds { get; set; }
|
||||
public DateTimeOffset ResetOn { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,289 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using xCommons.Models;
|
||||
using xCommons.Helpers;
|
||||
using System.Threading;
|
||||
using xCommons.Constants;
|
||||
using xCommons.Interfaces;
|
||||
using xCommons.Extensions;
|
||||
using System.Threading.Tasks;
|
||||
using xCommons.Configurations;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace xCommons.Providers
|
||||
{
|
||||
public class XFileTypeDetector : IXFileTypeDetector
|
||||
{
|
||||
private readonly XFileTypeDetectorConfiguration configuration;
|
||||
|
||||
private readonly Dictionary<string, byte[]> MagicSignatures =
|
||||
new(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
["image/png"] = new byte[] { 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A },
|
||||
["image/jpeg"] = new byte[] { 0xFF, 0xD8, 0xFF },
|
||||
["image/gif"] = new byte[] { 0x47, 0x49, 0x46, 0x38 },
|
||||
["image/bmp"] = new byte[] { 0x42, 0x4D },
|
||||
["image/x-icon"] = new byte[] { 0x00, 0x00, 0x01, 0x00 },
|
||||
["application/pdf"] = new byte[] { 0x25, 0x50, 0x44, 0x46 },
|
||||
["application/zip"] = new byte[] { 0x50, 0x4B, 0x03, 0x04 },
|
||||
["application/x-rar-compressed"] = new byte[] { 0x52, 0x61, 0x72, 0x21, 0x1A, 0x07 },
|
||||
["application/x-7z-compressed"] = new byte[] { 0x37, 0x7A, 0xBC, 0xAF, 0x27, 0x1C },
|
||||
["audio/mpeg"] = new byte[] { 0xFF, 0xFB },
|
||||
["audio/ogg"] = new byte[] { 0x4F, 0x67, 0x67, 0x53 },
|
||||
["font/ttf"] = new byte[] { 0x00, 0x01, 0x00, 0x00 }
|
||||
};
|
||||
|
||||
public XFileTypeDetector(
|
||||
XFileTypeDetectorConfiguration configuration
|
||||
)
|
||||
{
|
||||
this.configuration = configuration;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Detect Type based on File Name ...
|
||||
/// </summary>
|
||||
/// <param name="fileName"></param>
|
||||
/// <returns></returns>
|
||||
public string DetectFromExtension(string fileName)
|
||||
{
|
||||
//
|
||||
var result = string.Empty;
|
||||
|
||||
//
|
||||
// Validate ...
|
||||
if (fileName.IsNullOrEmpty())
|
||||
{
|
||||
return result;
|
||||
}
|
||||
|
||||
//
|
||||
var extension = Path.GetExtension(fileName);
|
||||
if (extension.IsNullOrEmpty())
|
||||
{
|
||||
return result;
|
||||
}
|
||||
|
||||
//
|
||||
result = XFileHelper.GetMimeType(extension);
|
||||
|
||||
//
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Detect XFileExtensions based on File Name ...
|
||||
/// </summary>
|
||||
/// <param name="fileName"></param>
|
||||
/// <returns></returns>
|
||||
public XFileExtensions? DetectExtension(string fileName)
|
||||
{
|
||||
//
|
||||
XFileExtensions? result = null;
|
||||
if (fileName.IsNullOrEmpty())
|
||||
{
|
||||
return result;
|
||||
}
|
||||
|
||||
//
|
||||
var extension = Path.GetExtension(fileName);
|
||||
var info = XFileHelper.GetByExtension(extension);
|
||||
if (info.IsNull())
|
||||
{
|
||||
return result;
|
||||
}
|
||||
|
||||
//
|
||||
result = (XFileExtensions)info.Value;
|
||||
|
||||
//
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Check a File Extension is Known or not ...
|
||||
/// </summary>
|
||||
/// <param name="fileName"></param>
|
||||
/// <returns></returns>
|
||||
public bool IsKnownExtension(string fileName)
|
||||
{
|
||||
//
|
||||
var result = !fileName.IsNullOrEmpty();
|
||||
if (!result)
|
||||
{
|
||||
return result;
|
||||
}
|
||||
|
||||
//
|
||||
var extension = Path.GetExtension(fileName);
|
||||
result = XFileHelper.IsSupported(extension);
|
||||
|
||||
//
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Detect Type based on File's Magic Byte ...
|
||||
/// </summary>
|
||||
/// <param name="stream"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
public async Task<string> DetectFromMagicBytesAsync(
|
||||
Stream stream,
|
||||
CancellationToken cancellationToken = default
|
||||
)
|
||||
{
|
||||
//
|
||||
var result = string.Empty;
|
||||
|
||||
//
|
||||
// Validate ...
|
||||
if (stream == null || !stream.CanRead)
|
||||
{
|
||||
return result;
|
||||
}
|
||||
|
||||
//
|
||||
var originalPosition = stream.CanSeek ? stream.Position : 0L;
|
||||
try
|
||||
{
|
||||
//
|
||||
var header = new byte[configuration.HeaderSize];
|
||||
var read = await ReadHeaderAsync(stream, header, cancellationToken);
|
||||
if (read < 2)
|
||||
{
|
||||
return result;
|
||||
}
|
||||
|
||||
//
|
||||
foreach (var signature in MagicSignatures)
|
||||
{
|
||||
//
|
||||
if (MatchesSignature(header, read, signature.Value))
|
||||
{
|
||||
//
|
||||
result = signature.Key;
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
return result;
|
||||
}
|
||||
finally
|
||||
{
|
||||
//
|
||||
if (stream.CanSeek)
|
||||
{
|
||||
stream.Position = originalPosition;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Complexity Detect Type ...
|
||||
/// </summary>
|
||||
/// <param name="fileName"></param>
|
||||
/// <param name="providedMimeType"></param>
|
||||
/// <param name="stream"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
public async Task<XFileTypeDetectionResult> DetectAsync(
|
||||
string fileName,
|
||||
string providedMimeType,
|
||||
Stream stream,
|
||||
CancellationToken cancellationToken = default
|
||||
)
|
||||
{
|
||||
//
|
||||
var result = new XFileTypeDetectionResult
|
||||
{
|
||||
Source = XFileTypeDetectionSource.None
|
||||
};
|
||||
|
||||
//
|
||||
if (configuration.PreferMagicBytes)
|
||||
{
|
||||
//
|
||||
var magicMime = await DetectFromMagicBytesAsync(stream, cancellationToken);
|
||||
if (!magicMime.IsNullOrEmpty())
|
||||
{
|
||||
//
|
||||
result.MimeType = magicMime;
|
||||
result.Extension = XFileHelper.GetExtension(magicMime);
|
||||
result.Source = XFileTypeDetectionSource.MagicBytes;
|
||||
|
||||
//
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
var extensionMime = DetectFromExtension(fileName);
|
||||
if (!extensionMime.IsNullOrEmpty())
|
||||
{
|
||||
//
|
||||
result.MimeType = extensionMime;
|
||||
result.Extension = Path.GetExtension(fileName)?.ToLowerInvariant();
|
||||
result.Source = XFileTypeDetectionSource.Extension;
|
||||
|
||||
//
|
||||
return result;
|
||||
}
|
||||
|
||||
//
|
||||
if (!string.IsNullOrWhiteSpace(providedMimeType))
|
||||
{
|
||||
//
|
||||
var info = XFileHelper.GetByMimeType(providedMimeType);
|
||||
if (info != null)
|
||||
{
|
||||
//
|
||||
result.MimeType = info.MimeType;
|
||||
result.Extension = info.Extension;
|
||||
result.Source = XFileTypeDetectionSource.ProvidedMime;
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
return result;
|
||||
}
|
||||
|
||||
//
|
||||
#region Private ...
|
||||
private static async Task<int> ReadHeaderAsync(
|
||||
Stream stream, byte[] buffer,
|
||||
CancellationToken ct = default
|
||||
)
|
||||
{
|
||||
//
|
||||
var totalRead = 0;
|
||||
while (totalRead < buffer.Length)
|
||||
{
|
||||
//
|
||||
var read = await stream.ReadAsync(
|
||||
buffer, totalRead, buffer.Length - totalRead, ct);
|
||||
|
||||
if (read == 0) break;
|
||||
totalRead += read;
|
||||
}
|
||||
|
||||
//
|
||||
return totalRead;
|
||||
}
|
||||
|
||||
private static bool MatchesSignature(byte[] header, int length, byte[] signature)
|
||||
{
|
||||
//
|
||||
if (length < signature.Length) return false;
|
||||
for (var i = 0; i < signature.Length; i++)
|
||||
{
|
||||
if (header[i] != signature[i]) return false;
|
||||
}
|
||||
|
||||
//
|
||||
return true;
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
using System;
|
||||
using xCommons.Models;
|
||||
using xCommons.Constants;
|
||||
using xCommons.Extensions;
|
||||
using xCommons.Interfaces;
|
||||
using xExceptions.Constants;
|
||||
using xCommons.Configurations;
|
||||
using System.Collections.Concurrent;
|
||||
using Microsoft.Extensions.Caching.Memory;
|
||||
|
||||
namespace xCommons.Providers
|
||||
{
|
||||
public class XRateLimitProvider : IXRateLimitProvider
|
||||
{
|
||||
//
|
||||
private readonly IMemoryCache cache;
|
||||
private readonly XRateLimitConfiguration configuration;
|
||||
private readonly ConcurrentDictionary<string, object> syncRoots = new();
|
||||
|
||||
public XRateLimitProvider(
|
||||
IMemoryCache cache,
|
||||
XRateLimitConfiguration configuration
|
||||
)
|
||||
{
|
||||
//
|
||||
this.cache = cache;
|
||||
this.configuration = configuration;
|
||||
}
|
||||
|
||||
public bool IsEnabled
|
||||
{
|
||||
get
|
||||
{
|
||||
return !configuration.IsNull() && configuration.Enabled;
|
||||
}
|
||||
}
|
||||
|
||||
public XRateLimitResult TryConsume(
|
||||
string key,
|
||||
XRateLimitRule rule
|
||||
)
|
||||
{
|
||||
//
|
||||
if (rule.IsNull())
|
||||
{
|
||||
XException.InvalidArgs.Throw();
|
||||
}
|
||||
|
||||
//
|
||||
return TryConsume(
|
||||
key: key,
|
||||
limit: rule.Limit,
|
||||
periodSeconds: rule.PeriodSeconds
|
||||
);
|
||||
}
|
||||
|
||||
public XRateLimitResult TryConsume(
|
||||
string key,
|
||||
int limit,
|
||||
int periodSeconds
|
||||
)
|
||||
{
|
||||
//
|
||||
if (limit <= 0 || periodSeconds <= 0)
|
||||
{
|
||||
XException.InvalidArgs.Throw();
|
||||
}
|
||||
|
||||
//
|
||||
var normalizedKey = BuildCacheKey(key);
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
|
||||
//
|
||||
if (!IsEnabled)
|
||||
{
|
||||
//
|
||||
return new XRateLimitResult
|
||||
{
|
||||
Limit = limit,
|
||||
IsAllowed = true,
|
||||
Remaining = limit,
|
||||
Key = normalizedKey,
|
||||
RetryAfterSeconds = 0,
|
||||
ResetOn = now.AddSeconds(periodSeconds)
|
||||
};
|
||||
}
|
||||
|
||||
//
|
||||
var syncRoot = syncRoots.GetOrAdd(
|
||||
key: normalizedKey,
|
||||
valueFactory: _ => new object()
|
||||
);
|
||||
|
||||
//
|
||||
lock (syncRoot)
|
||||
{
|
||||
//
|
||||
var counter = cache.Get<XRateLimitCounter>(normalizedKey);
|
||||
if (counter.IsNull() || counter.ResetOn <= now)
|
||||
{
|
||||
//
|
||||
counter = new XRateLimitCounter
|
||||
{
|
||||
Count = 0,
|
||||
Limit = limit,
|
||||
ResetOn = now.AddSeconds(periodSeconds)
|
||||
};
|
||||
}
|
||||
|
||||
//
|
||||
counter.Count++;
|
||||
counter.Limit = limit;
|
||||
|
||||
//
|
||||
var remaining = Math.Max(0, limit - counter.Count);
|
||||
var isAllowed = counter.Count <= limit;
|
||||
var retryAfter = isAllowed
|
||||
? 0
|
||||
: (int)Math.Ceiling((counter.ResetOn - now).TotalSeconds);
|
||||
|
||||
//
|
||||
var options = new MemoryCacheEntryOptions
|
||||
{
|
||||
AbsoluteExpiration = counter.ResetOn
|
||||
};
|
||||
|
||||
//
|
||||
options.RegisterPostEvictionCallback((cacheKey, value, reason, state) =>
|
||||
{
|
||||
syncRoots.TryRemove(cacheKey.ToString(), out _);
|
||||
});
|
||||
|
||||
//
|
||||
cache.Set(normalizedKey, counter, options);
|
||||
|
||||
//
|
||||
return new XRateLimitResult
|
||||
{
|
||||
Limit = limit,
|
||||
Key = normalizedKey,
|
||||
IsAllowed = isAllowed,
|
||||
Remaining = remaining,
|
||||
ResetOn = counter.ResetOn,
|
||||
RetryAfterSeconds = retryAfter,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
private static string BuildCacheKey(string key)
|
||||
{
|
||||
//
|
||||
var normalized = key.IsNullOrEmpty()
|
||||
? "anonymous"
|
||||
: key.ToNormalString();
|
||||
|
||||
//
|
||||
return string.Format(
|
||||
"{0}:{1}",
|
||||
XRateLimitConstants.CacheKeyPrefix,
|
||||
normalized
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -47,6 +47,7 @@
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration" Version="5.0.0" />
|
||||
<PackageReference Include="Microsoft.IO.RecyclableMemoryStream" Version="1.4.0" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Mvc.Versioning" Version="4.1.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="3.1.32" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Mvc.Abstractions" Version="2.2.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="5.0.1" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Authorization.Policy" Version="2.2.0" />
|
||||
|
||||
Reference in New Issue
Block a user