Skip to content

Commit 432c7c0

Browse files
Bold Create AgentVinothSF5015
andcommitted
Limit each user to one document upload per 24 hours
Co-authored-by: VinothSF5015 <197725877+VinothSF5015@users.noreply.github.com>
1 parent 4b2e959 commit 432c7c0

4 files changed

Lines changed: 183 additions & 3 deletions

File tree

‎Document_Chunking1_New/AgentRAGWithAzure 1/AgentRAGWithAzure/Endpoints/RagEndpointExtensions.cs‎

Lines changed: 52 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,11 +42,33 @@ public static IEndpointRouteBuilder MapRagEndpoints(this IEndpointRouteBuilder e
4242
// Upload and index documents
4343
// ------------------------------------------------------------
4444

45+
endpoints.MapGet(
46+
"/api/upload-quota/{userCode}",
47+
async (string userCode, UploadQuotaService quota) =>
48+
{
49+
if (!UploadQuotaService.IsValidUserCode(userCode))
50+
{
51+
return Results.BadRequest(new UploadErrorResponse { Error = "Invalid user." });
52+
}
53+
54+
DateTime? resetAt = await quota.GetBlockedUntilAsync(userCode);
55+
return Results.Ok(new
56+
{
57+
limitReached = resetAt.HasValue,
58+
resetAtUtc = resetAt,
59+
message = resetAt.HasValue
60+
? "You can upload only one document per day. You can upload again after " +
61+
resetAt.Value.ToString("u") + "."
62+
: null
63+
});
64+
});
65+
4566
endpoints.MapPost(
4667
"/api/upload",
4768
async (
4869
HttpRequest request,
49-
RagService ragService) =>
70+
RagService ragService,
71+
UploadQuotaService quota) =>
5072
{
5173
if (!request.HasFormContentType)
5274
{
@@ -73,6 +95,34 @@ public static IEndpointRouteBuilder MapRagEndpoints(this IEndpointRouteBuilder e
7395
});
7496
}
7597

98+
string? userCode = form["userCode"].ToString();
99+
if (!UploadQuotaService.IsValidUserCode(userCode))
100+
{
101+
return Results.BadRequest(new UploadErrorResponse { Error = "Invalid user." });
102+
}
103+
104+
DateTime? resetAt = await quota.GetBlockedUntilAsync(userCode);
105+
if (resetAt.HasValue)
106+
{
107+
return Results.Json(
108+
new
109+
{
110+
error = "You can upload only one document per day. You can upload again after " +
111+
resetAt.Value.ToString("u") + ".",
112+
resetAtUtc = resetAt
113+
},
114+
statusCode: StatusCodes.Status429TooManyRequests);
115+
}
116+
117+
if (files.Count > 1)
118+
{
119+
return Results.BadRequest(
120+
new UploadErrorResponse
121+
{
122+
Error = "Only one document can be uploaded per day. Please select a single file."
123+
});
124+
}
125+
76126
var uploadedFiles =
77127
new List<string>();
78128

@@ -102,6 +152,7 @@ await ragService.IndexUploadedFileAsync(
102152
statusCode: StatusCodes.Status500InternalServerError);
103153
}
104154

155+
await quota.RecordUploadAsync(userCode);
105156
uploadedFiles.Add(safeFileName);
106157
}
107158

‎Document_Chunking1_New/AgentRAGWithAzure 1/AgentRAGWithAzure/Program.cs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@
2929
});
3030

3131
builder.Services.AddSingleton<RagService>();
32+
builder.Services.AddSingleton<UploadQuotaService>();
3233
builder.Services.AddMemoryCache();
3334
builder.Services.AddControllers();
3435

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
#nullable enable
2+
3+
using System.Text.Json;
4+
using System.Text.RegularExpressions;
5+
6+
namespace AgentRAGWithAzure.Services;
7+
8+
/// <summary>
9+
/// Limits each user to one document upload per 24 hours.
10+
/// The allowance resets 24 hours after the last successful upload.
11+
/// </summary>
12+
public sealed partial class UploadQuotaService
13+
{
14+
private static readonly TimeSpan ResetPeriod = TimeSpan.FromHours(24);
15+
16+
private readonly string _filePath;
17+
private readonly SemaphoreSlim _lock = new(1, 1);
18+
19+
public UploadQuotaService(IWebHostEnvironment environment)
20+
{
21+
string folder = Path.Combine(environment.ContentRootPath, "App_Data");
22+
Directory.CreateDirectory(folder);
23+
_filePath = Path.Combine(folder, "upload_quota.json");
24+
}
25+
26+
[GeneratedRegex("^[A-Za-z0-9_-]{4,64}$")]
27+
private static partial Regex UserCodePattern();
28+
29+
public static bool IsValidUserCode(string? userCode) =>
30+
!string.IsNullOrEmpty(userCode) && UserCodePattern().IsMatch(userCode);
31+
32+
/// <summary>Returns null when the user may upload, otherwise the reset time (UTC).</summary>
33+
public async Task<DateTime?> GetBlockedUntilAsync(string userCode)
34+
{
35+
await _lock.WaitAsync();
36+
try
37+
{
38+
var data = await ReadAsync();
39+
if (data.TryGetValue(userCode, out DateTime lastUpload))
40+
{
41+
DateTime resetAt = lastUpload + ResetPeriod;
42+
if (DateTime.UtcNow < resetAt)
43+
{
44+
return resetAt;
45+
}
46+
}
47+
return null;
48+
}
49+
finally
50+
{
51+
_lock.Release();
52+
}
53+
}
54+
55+
public async Task RecordUploadAsync(string userCode)
56+
{
57+
await _lock.WaitAsync();
58+
try
59+
{
60+
var data = await ReadAsync();
61+
data[userCode] = DateTime.UtcNow;
62+
await File.WriteAllTextAsync(_filePath, JsonSerializer.Serialize(data));
63+
}
64+
finally
65+
{
66+
_lock.Release();
67+
}
68+
}
69+
70+
private async Task<Dictionary<string, DateTime>> ReadAsync()
71+
{
72+
if (!File.Exists(_filePath))
73+
{
74+
return new Dictionary<string, DateTime>();
75+
}
76+
77+
try
78+
{
79+
string json = await File.ReadAllTextAsync(_filePath);
80+
return JsonSerializer.Deserialize<Dictionary<string, DateTime>>(json)
81+
?? new Dictionary<string, DateTime>();
82+
}
83+
catch (JsonException)
84+
{
85+
return new Dictionary<string, DateTime>();
86+
}
87+
}
88+
}

‎Document_Chunking1_New/AgentRAGWithAzure 1/AgentRAGWithAzure/wwwroot/js/workspace.js‎

Lines changed: 42 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -184,7 +184,7 @@ function renderSelected(files) {
184184
li.append(info, status, remove);
185185
list.appendChild(li);
186186
});
187-
upload.disabled = accepted.length === 0;
187+
upload.disabled = uploadLimitReached || accepted.length === 0;
188188
}
189189

190190
async function refreshReadyState() {
@@ -219,6 +219,37 @@ function assignFiles(fileList) {
219219
}
220220
}
221221

222+
function getUserCode() {
223+
const parts = [
224+
navigator.userAgent, navigator.language, screen.width + "x" + screen.height,
225+
screen.colorDepth, new Date().getTimezoneOffset(), navigator.hardwareConcurrency || 0
226+
].join("|");
227+
let hash = 0;
228+
for (let i = 0; i < parts.length; i++) { hash = ((hash << 5) - hash + parts.charCodeAt(i)) | 0; }
229+
return "u" + Math.abs(hash).toString(36) + "-" + parts.length;
230+
}
231+
function applyUploadLimit(data) {
232+
const uploadButton = document.getElementById("uploadButton");
233+
const input = document.getElementById("fileInput");
234+
const status = document.getElementById("uploadStatus");
235+
uploadLimitReached = !!(data && data.limitReached);
236+
if (uploadLimitReached) {
237+
const when = data.resetAtUtc ? new Date(data.resetAtUtc).toLocaleString() : "";
238+
setLive(status, "You can upload only one document per day. You can upload again after " + when + ".", "error");
239+
if (uploadButton) uploadButton.disabled = true;
240+
if (input) input.disabled = true;
241+
} else if (input) {
242+
input.disabled = false;
243+
}
244+
}
245+
async function checkUploadLimit() {
246+
try {
247+
const res = await fetch("/api/upload-quota/" + encodeURIComponent(getUserCode()));
248+
if (res.ok) applyUploadLimit(await res.json());
249+
} catch (e) { /* quota check is best-effort; the server enforces it */ }
250+
}
251+
let uploadLimitReached = false;
252+
222253
async function uploadFiles() {
223254
const input = document.getElementById("fileInput");
224255
const uploadButton = document.getElementById("uploadButton");
@@ -235,7 +266,13 @@ async function uploadFiles() {
235266
setLive(status, rejected.map(function (f) { return f.name + " is not supported. Use PDF, Word, or Excel."; }).join(" "), "error");
236267
return;
237268
}
269+
if (uploadLimitReached) return;
270+
if (accepted.length > 1) {
271+
setLive(status, "Only one document can be uploaded per day. Please select a single file.", "error");
272+
return;
273+
}
238274
const formData = new FormData();
275+
formData.append("userCode", getUserCode());
239276
accepted.forEach(function (file) { formData.append("files", file); });
240277
uploadButton.disabled = true;
241278
progress.classList.add("is-active");
@@ -247,6 +284,7 @@ async function uploadFiles() {
247284
const err = new Error("upload");
248285
err.status = response.status;
249286
err.detail = payload && payload.error;
287+
if (response.status === 429) applyUploadLimit({ limitReached: true, resetAtUtc: payload.resetAtUtc });
250288
throw err;
251289
}
252290
const added = payload.files || accepted.map(function (f) { return f.name; });
@@ -258,10 +296,11 @@ async function uploadFiles() {
258296
input.value = "";
259297
renderSelected([]);
260298
await refreshReadyState();
299+
await checkUploadLimit();
261300
} catch (error) {
262301
const fallback = friendlyError(error, "Could not prepare these documents. Try adding them again.");
263302
setLive(status, error && error.detail ? fallback + " " + error.detail : fallback, "error");
264-
uploadButton.disabled = accepted.length === 0;
303+
uploadButton.disabled = uploadLimitReached || accepted.length === 0;
265304
} finally {
266305
progress.classList.remove("is-active");
267306
}
@@ -1480,6 +1519,7 @@ document.addEventListener("click", function (event) {
14801519
});
14811520
document.addEventListener("DOMContentLoaded", function () {
14821521
refreshReadyState();
1522+
checkUploadLimit();
14831523
const input = document.getElementById("fileInput");
14841524
const drop = document.getElementById("dropZone");
14851525
if (input) input.addEventListener("change", function () { assignFiles(input.files); });

0 commit comments

Comments
 (0)