Added restriction for the number of short links per month and added Global Rate Limiting by ScriptSage001 · Pull Request #35 · ScriptSage001/Shortify.NET · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file added Assets/Images/Logo.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added Assets/Images/Swagger UI 0.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added Assets/Images/Swagger UI 1.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added Assets/Images/Swagger UI 2.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
164 changes: 155 additions & 9 deletions README.md
18 changes: 17 additions & 1 deletion Shortify.NET.API/BaseApiController.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Shortify.NET.Common.FunctionalTypes;
using Shortify.NET.Common.Messaging.Abstractions;
Expand Down Expand Up @@ -113,5 +114,20 @@ protected string GetUser()

return userIdClaims is null ? string.Empty : userIdClaims.Value;
}

/// <summary>
/// Checks if the user is an Admin User
/// </summary>
/// <returns></returns>
protected bool IsUserAdmin()
{
var isUserAdmin = User
.Claims
.Any(c =>
c.Type.Equals(ClaimTypes.Role, StringComparison.OrdinalIgnoreCase) &&
c.Value == "Admin");

return isUserAdmin;
}
}
}
23 changes: 21 additions & 2 deletions Shortify.NET.API/Controllers/V1/ShortController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using Shortify.NET.API.Contracts;
using Shortify.NET.API.Mappers;
using Shortify.NET.Application.Url.Commands.DeleteUrl;
using Shortify.NET.Application.Url.Queries.CanCreateShortUrl;
using Shortify.NET.Application.Url.Queries.GetAllShortenedUrls;
using Shortify.NET.Application.Url.Queries.GetOriginalUrl;
using Shortify.NET.Application.Url.Queries.ShortenedUrl;
Expand Down Expand Up @@ -67,13 +68,31 @@ public async Task<IActionResult> ShortenUrl(
return HandleUnauthorizedRequest();
}

var canCreate = true;

if(!IsUserAdmin())
{
canCreate = (await _apiService
.RequestAsync(new CanCreateShortLinkQuery(userId), cancellationToken))
.Value;
}

if (!canCreate)
{
return HandleFailure(
Result.Failure(
Error.BadRequest(
"Error.LimitReached",
"Monthly limit of 10 short links reached.")));
}

var command = _mapper.ShortenUrlRequestToCommand(request, userId, HttpContext.Request);

var response = await _apiService.SendAsync(command, cancellationToken);

return response.IsFailure ?
HandleFailure(response) :
Created(nameof(ShortenUrl), response.Value.Value);
HandleFailure(response) :
Created(nameof(ShortenUrl), response.Value.Value);
}

/// <summary>
Expand Down
47 changes: 46 additions & 1 deletion Shortify.NET.API/DependencyInjection.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
using System.Reflection;
using System.Net;
using System.Reflection;
using System.Text;
using System.Threading.RateLimiting;
using Asp.Versioning;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using Shortify.NET.API.Helpers;
using Shortify.NET.API.SwaggerConfig;
using Swashbuckle.AspNetCore.SwaggerGen;

Expand All @@ -20,6 +23,7 @@ public static IServiceCollection AddApi(this IServiceCollection services, IConfi
services.AddEndpointsApiExplorer();
services.AddSwagger();
services.AddCorsPolicy(configuration);
services.AddRateLimiting(configuration);

return services;
}
Expand Down Expand Up @@ -124,5 +128,46 @@ private static void AddCorsPolicy(this IServiceCollection services, IConfigurati
});
});
}

private static void AddRateLimiting(this IServiceCollection services, IConfiguration configuration)
{
services.AddRateLimiter(options =>
{
options.OnRejected = (context, cancellationToken) =>
{
context.HttpContext.Response.StatusCode = StatusCodes.Status429TooManyRequests;
context.HttpContext.Response.WriteAsync("Too many requests. Please try again later.", cancellationToken);
return new ValueTask();
};

options.GlobalLimiter = PartitionedRateLimiter.Create<HttpContext, string>(context =>
{
var remoteIpAddress = context.Connection.RemoteIpAddress;

if (IPAddress.IsLoopback(remoteIpAddress!))
return RateLimitPartition.GetNoLimiter(IPAddress.Loopback.ToString());

var rateLimiterOptions = configuration
.GetSection("RateLimiterOptions")
.Get<RateLimiterOptions>();

if (rateLimiterOptions is not null)
{
return RateLimitPartition.GetSlidingWindowLimiter(
remoteIpAddress?.ToString()!,
_ =>
new SlidingWindowRateLimiterOptions
{
PermitLimit = rateLimiterOptions.PermitLimit,
Window = TimeSpan.FromSeconds(rateLimiterOptions.WindowInSeconds),
SegmentsPerWindow = rateLimiterOptions.SegmentsPerWindow,
QueueProcessingOrder = QueueProcessingOrder.OldestFirst,
QueueLimit = rateLimiterOptions.QueueLimit
});
}
return RateLimitPartition.GetNoLimiter(IPAddress.Loopback.ToString());
});
});
}
}
}
29 changes: 29 additions & 0 deletions Shortify.NET.API/Helpers/RateLimiterOptions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
namespace Shortify.NET.API.Helpers
{
/// <summary>
/// Defines the options to configure the rate limiter
/// </summary>
public class RateLimiterOptions
{
/// <summary>
/// Gets or Sets the number of request permitted per window
/// </summary>
public int PermitLimit { get; init; }

/// <summary>
/// Gets or Sets the timespan of one window in seconds
/// </summary>
public int WindowInSeconds { get; init; }

/// <summary>
/// Gets or Sets the number of segments the window is divided into
/// </summary>
public int SegmentsPerWindow { get; init; }

/// <summary>
/// Gets or Sets the number of requests permitted in the queue.
/// Pass 0 for no queue.
/// </summary>
public int QueueLimit { get; init; }
}
}
2 changes: 2 additions & 0 deletions Shortify.NET.API/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,8 @@

app.UseHttpsRedirection();

app.UseRateLimiter();

app.UseAuthentication();
app.UseAuthorization();

Expand Down
1 change: 1 addition & 0 deletions Shortify.NET.API/Shortify.NET.API.csproj
Loading