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
Original file line number Diff line number Diff line change
@@ -1,30 +1,156 @@
<h1 align="center" id="title">Shortify.NET (In-Progress)</h1>
<h1 align="center" id="title">Shortify.NET</h1>

<p align="center"><img src="https://github.com/ScriptSage001/Shortify.NET/blob/master/Assets/Images/Logo.png?raw=true" alt="logo"></p>

<p align="center"><img src="https://socialify.git.ci/ScriptSage001/Shortify.NET/image?description=1&amp;descriptionEditable=A%20powerful%20.NET%208%20URL%20shortener%20with%20JWT%20auth%2C%20analytics%2C%20and%20caching%2C%20designed%20for%20scalability%20and%20security.&amp;font=Raleway&amp;language=1&amp;name=1&amp;owner=1&amp;pattern=Plus&amp;theme=Dark" alt="project-image"></p>

<p id="description">A powerful .NET 8 URL shortener with JWT auth analytics and caching designed for scalability and security.</p>

<br>

<h3>Code Quality</h3>

[![Qodana](https://github.com/ScriptSage001/Shortify.NET/actions/workflows/qodana_code_quality.yml/badge.svg)](https://github.com/ScriptSage001/Shortify.NET/actions/workflows/qodana_code_quality.yml)

<h2>🚀 Swagger UI</h2>
<br>

<h2>✨ Why Use Shortify.NET?</h2>

- **Scalable and Secure:** Built with .NET 8, ensuring high performance and strong security measures.
- **JWT Authentication:** Secure user management and role-based access control.
- **Caching:** Accelerated redirection using Redis for optimal performance.
- **Ease of Use:** A simple API interface, designed to integrate seamlessly into any application.
- **Analytics:** Gain insights into URL usage patterns. (Coming Soon)

<br>

<h2>🧩 Features</h2>

[https://shortify-net.onrender.com/swagger/index.html](https://shortify-net.onrender.com/swagger/index.html)
- Generate short URLs quickly and efficiently.
- Secure endpoints with JWT authentication.
- Track detailed analytics for shortened URLs.
- Support for custom aliases.
- Scalable design for high availability.
- Dockerized for easy deployment.

<h2>🛠️ Installation Steps:</h2>
<br>

<p>1. docker pull</p>
<h2>🚀 Tech Stack</h2>

- **Backend:** .NET 8
- **Database:** PostgreSQL (Supabase-hosted)
- **Caching:** Redis
- **Containerization:** Docker
- **API Documentation:** Swagger
- **CI/CD:** GitHub Actions
- **Hosting Platform:** Render
- **Static Code Analysis:** Qodana

<br>

<h2>🛠️ Installation and Setup:</h2>
<h3>Using Docker</h3>

<p>1. Pull the Docker Image:</p>

```
docker pull thescriptsage/shortifynetapi
```
<br>

<p>2. Set Up Required Environment Variables:</p>
Ensure the following environment variables are set before running the container:

- **DB_CONNECTION:** Connection string for the PostgreSQL database (e.g., Host=localhost;Port=5432;Database=Shortify;Username=yourUsername;Password=yourPassword).
- **REDIS_CONNECTION:** Connection string for Redis (e.g., localhost:6379).
- **APP_SECRET:** A secret key for signing JWT tokens.
- **CLIENT_SECRET:** Client-specific secret for enhanced security.
- **SENDER_EMAIL:** Email address for sending OTPs or notifications.
- **SENDER_EMAIL_PASSWORD:** Password for the sender email.
- **ALLOWED_HOST:** A comma-separated list of allowed host URLs.

<br>

<p>3. Run the Docker Container:</p>

```
docker run -d -p 5000:80 \
-e DB_CONNECTION="Host=localhost;Port=5432;Database=Shortify;Username=yourUsername;Password=yourPassword" \
-e REDIS_CONNECTION="localhost:6379" \
-e APP_SECRET="yourAppSecret" \
-e CLIENT_SECRET="yourClientSecret" \
-e SENDER_EMAIL="yourEmail@gmail.com" \
-e SENDER_EMAIL_PASSWORD="yourEmailPassword" \
-e ALLOWED_HOST="http://localhost,http://example.com" \
thescriptsage/shortifynetapi
```
<br>

<p>2. docker run</p>
<p>3. Access the Swagger UI:</p>
Visit <a target="_blank" href="http://localhost:5000/swagger/index.html">http://localhost:5000/swagger/index.html</a> to explore the API.

<br><br>
<h3>Local Development</h3>

<p>1. Clone the Repository:</p>

```
docker run -d -p 5000:80 thescriptsage/shortifynetapi
git clone https://github.com/ScriptSage001/Shortify.NET.git
cd Shortify.NET
```
<br>

<p>2. Configure Environment Variables:</p>
Use an environment variable manager or .env file to configure the following values:

- **DB_CONNECTION:** Connection string for the PostgreSQL database (e.g., Host=localhost;Port=5432;Database=Shortify;Username=yourUsername;Password=yourPassword).
- **REDIS_CONNECTION:** Connection string for Redis (e.g., localhost:6379).
- **APP_SECRET:** A secret key for signing JWT tokens.
- **CLIENT_SECRET:** Client-specific secret for enhanced security.
- **SENDER_EMAIL:** Email address for sending OTPs or notifications.
- **SENDER_EMAIL_PASSWORD:** Password for the sender email.
- **ALLOWED_HOST:** A comma-separated list of allowed host URLs.
<br>
<h4>Example .env file:</h4>

```
DB_CONNECTION=Host=localhost;Port=5432;Database=Shortify;Username=yourUsername;Password=yourPassword
REDIS_CONNECTION=localhost:6379
APP_SECRET=yourAppSecret
CLIENT_SECRET=yourClientSecret
SENDER_EMAIL=yourEmail@gmail.com
SENDER_EMAIL_PASSWORD=yourEmailPassword
ALLOWED_HOST=http://localhost,http://example.com
```
<br>

<p>3. Install Dependencies:</p>
Ensure you have the .NET 8 SDK installed. Then, restore the NuGet packages:

```
dotnet restore
```
<br>

<p>4. Run the Application:</p>

```
dotnet run
```
<br>

<p>5. Access the Swagger UI:</p>
<p>Swagger UI will be available at <a target="_blank" href="http://localhost:5000/swagger/index.html">http://localhost:5000/swagger/index.html</a> or the port specified in the console logs.</p>

<br>

<h2>📚 API Documentation</h2>
The API is fully documented using Swagger. Access the live documentation here:

- <a target="_blank" href="https://shortify-net.onrender.com/swagger/index.html">Swagger UI</a>
- <a target="_blank" href="https://shortify-net.onrender.com/swagger/v1/swagger.json">Swagger JSON</a>

<br>

<h2>🍰 Contribution Guidelines:</h2>

Expand All @@ -38,21 +164,41 @@ docker run -d -p 5000:80 thescriptsage/shortifynetapi
```
git checkout -b feature/AmazingFeature
```
<br>

<p>3. Commit your Changes</p>

```
git commit -m &#39;Add some AmazingFeature&#39;
git commit -m 'Add some AmazingFeature'
```
<br>

<p>4. Push to the Branch</p>

```
git push origin feature/AmazingFeature
```
<br>

<p>5. Open a Pull Request</p>

<br>

<h2>📸 Screenshots</h2>

<h3>Swagger UI</h3>
<p align="center"><img src="https://github.com/ScriptSage001/Shortify.NET/blob/master/Assets/Images/Swagger%20UI%200.png?raw=true" alt="swagger-ui-01"></p>
<p align="center"><img src="https://github.com/ScriptSage001/Shortify.NET/blob/master/Assets/Images/Swagger%20UI%201.png?raw=true" alt="swagger-ui-02"></p>
<p align="center"><img src="https://github.com/ScriptSage001/Shortify.NET/blob/master/Assets/Images/Swagger%20UI%202.png?raw=true" alt="swagger-ui-03"></p>

<br>

<h2>🛡️ License:</h2>
<p>This project is licensed under the Apache License. See the <a href="https://github.com/ScriptSage001/Shortify.NET/blob/master/LICENSE.txt">LICENSE</a> file for details.</p>

<br>

<h2>🌟 Acknowledgments</h2>

This project is licensed under the Apache License
- Inspiration from modern URL shorteners like Bitly.
- Thanks to the .NET community for continuous support and tools.
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 All @@ -12,7 +13,7 @@
public abstract class BaseApiController(IApiService apiService)
: ControllerBase
{
protected readonly IApiService _apiService = apiService;

Check warning on line 16 in Shortify.NET.API/BaseApiController.cs

View workflow job for this annotation

GitHub Actions / Qodana Community for .NET

Inconsistent Naming

Name '_apiService' does not match rule 'Instance fields (not private)'. Suggested name is 'ApiService'.

Check warning on line 16 in Shortify.NET.API/BaseApiController.cs

View workflow job for this annotation

GitHub Actions / Qodana Community for .NET

Inconsistent Naming

Name '_apiService' does not match rule 'Instance fields (not private)'. Suggested name is 'ApiService'.

/// <summary>
/// Handles Failure Scenarios to Generate
Expand Down Expand Up @@ -113,5 +114,20 @@

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
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
<PackageReference Include="Asp.Versioning.Http" Version="8.1.0" />
<PackageReference Include="Asp.Versioning.Mvc.ApiExplorer" Version="8.1.0" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.5" />
<PackageReference Include="Microsoft.AspNetCore.RateLimiting" Version="7.0.0-rc.2.22476.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="8.0.5">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
Expand Down
Loading
Loading