Harden API with rate limits, DeviceId isolation, and tighter CORS.
build-and-deploy / deploy (push) Successful in 3m27s
build-and-deploy / deploy (push) Successful in 3m27s
Limit auth/read/write JSON traffic per IP while leaving audio streams unrestricted; close JWT+deviceId IDOR and add path/input guards. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -3,6 +3,8 @@ kind: Namespace
|
|||||||
metadata:
|
metadata:
|
||||||
name: tafsirquran
|
name: tafsirquran
|
||||||
---
|
---
|
||||||
|
# SECURITY: Rotate MSSQL_SA_PASSWORD and Jwt__Key out-of-band; prefer sealed-secrets /
|
||||||
|
# external secret store. Do not commit newly rotated production credentials to git.
|
||||||
apiVersion: v1
|
apiVersion: v1
|
||||||
kind: Secret
|
kind: Secret
|
||||||
metadata:
|
metadata:
|
||||||
@@ -25,6 +27,7 @@ data:
|
|||||||
Jwt__Issuer: "TafsirQuran"
|
Jwt__Issuer: "TafsirQuran"
|
||||||
Jwt__Audience: "TafsirQuran"
|
Jwt__Audience: "TafsirQuran"
|
||||||
Jwt__ExpireMinutes: "43200"
|
Jwt__ExpireMinutes: "43200"
|
||||||
|
Cors__Origins__0: "https://quran.afrino.co"
|
||||||
---
|
---
|
||||||
apiVersion: v1
|
apiVersion: v1
|
||||||
kind: ConfigMap
|
kind: ConfigMap
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
using System.Security.Claims;
|
using System.Security.Claims;
|
||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
using TafsirQuran.Api.Auth;
|
using TafsirQuran.Api.Auth;
|
||||||
|
using TafsirQuran.Api.Security;
|
||||||
using TafsirQuran.Domain.Entities;
|
using TafsirQuran.Domain.Entities;
|
||||||
using TafsirQuran.Infrastructure.Persistence;
|
using TafsirQuran.Infrastructure.Persistence;
|
||||||
using TafsirQuran.Shared.Dtos;
|
using TafsirQuran.Shared.Dtos;
|
||||||
@@ -9,18 +10,24 @@ namespace TafsirQuran.Api.Endpoints;
|
|||||||
|
|
||||||
public static class AuthEndpoints
|
public static class AuthEndpoints
|
||||||
{
|
{
|
||||||
public static RouteGroupBuilder MapAuthEndpoints(this WebApplication app)
|
private const string GenericRegisterFailure = "ثبتنام ناموفق بود";
|
||||||
|
private const string GenericLoginFailure = "ایمیل یا رمز عبور نادرست است";
|
||||||
|
|
||||||
|
public static IEndpointRouteBuilder MapAuthEndpoints(this WebApplication app)
|
||||||
{
|
{
|
||||||
var group = app.MapGroup("/api/auth");
|
var group = app.MapGroup("/api/auth");
|
||||||
|
|
||||||
group.MapPost("/register", async (AuthRequest request, AppDbContext db, JwtTokenService jwt, CancellationToken ct) =>
|
group.MapPost("/register", async (AuthRequest request, AppDbContext db, JwtTokenService jwt, CancellationToken ct) =>
|
||||||
{
|
{
|
||||||
if (string.IsNullOrWhiteSpace(request.Email) || string.IsNullOrWhiteSpace(request.Password))
|
if (string.IsNullOrWhiteSpace(request.Email) || string.IsNullOrWhiteSpace(request.Password))
|
||||||
return Results.BadRequest("ایمیل و رمز عبور لازم است");
|
return Results.BadRequest(new { error = "invalid_request", message = GenericRegisterFailure });
|
||||||
|
|
||||||
|
if (request.Password.Length < EndpointSecurity.MinPasswordLength)
|
||||||
|
return Results.BadRequest(new { error = "invalid_request", message = GenericRegisterFailure });
|
||||||
|
|
||||||
var email = request.Email.Trim().ToLowerInvariant();
|
var email = request.Email.Trim().ToLowerInvariant();
|
||||||
if (await db.Users.AnyAsync(u => u.Email == email, ct))
|
if (await db.Users.AnyAsync(u => u.Email == email, ct))
|
||||||
return Results.Conflict("این ایمیل قبلاً ثبت شده است");
|
return Results.BadRequest(new { error = "invalid_request", message = GenericRegisterFailure });
|
||||||
|
|
||||||
var user = new AppUser
|
var user = new AppUser
|
||||||
{
|
{
|
||||||
@@ -33,20 +40,24 @@ public static class AuthEndpoints
|
|||||||
|
|
||||||
var token = jwt.CreateToken(user);
|
var token = jwt.CreateToken(user);
|
||||||
return Results.Ok(new AuthResponse(user.Id, user.Email, user.DisplayName, token));
|
return Results.Ok(new AuthResponse(user.Id, user.Email, user.DisplayName, token));
|
||||||
});
|
}).RequireRateLimiting("auth");
|
||||||
|
|
||||||
group.MapPost("/login", async (AuthRequest request, AppDbContext db, JwtTokenService jwt, CancellationToken ct) =>
|
group.MapPost("/login", async (AuthRequest request, AppDbContext db, JwtTokenService jwt, CancellationToken ct) =>
|
||||||
{
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(request.Email) || string.IsNullOrWhiteSpace(request.Password))
|
||||||
|
return Results.Json(new { error = "invalid_credentials", message = GenericLoginFailure }, statusCode: StatusCodes.Status401Unauthorized);
|
||||||
|
|
||||||
var email = request.Email.Trim().ToLowerInvariant();
|
var email = request.Email.Trim().ToLowerInvariant();
|
||||||
var user = await db.Users.FirstOrDefaultAsync(u => u.Email == email, ct);
|
var user = await db.Users.FirstOrDefaultAsync(u => u.Email == email, ct);
|
||||||
if (user is null || !BCrypt.Net.BCrypt.Verify(request.Password, user.PasswordHash))
|
if (user is null || !BCrypt.Net.BCrypt.Verify(request.Password, user.PasswordHash))
|
||||||
return Results.Unauthorized();
|
return Results.Json(new { error = "invalid_credentials", message = GenericLoginFailure }, statusCode: StatusCodes.Status401Unauthorized);
|
||||||
|
|
||||||
var token = jwt.CreateToken(user);
|
var token = jwt.CreateToken(user);
|
||||||
return Results.Ok(new AuthResponse(user.Id, user.Email, user.DisplayName, token));
|
return Results.Ok(new AuthResponse(user.Id, user.Email, user.DisplayName, token));
|
||||||
});
|
}).RequireRateLimiting("auth");
|
||||||
|
|
||||||
group.MapPost("/logout", () => Results.NoContent());
|
group.MapPost("/logout", () => Results.NoContent())
|
||||||
|
.RequireRateLimiting("global");
|
||||||
|
|
||||||
group.MapGet("/me", async (ClaimsPrincipal principal, AppDbContext db, CancellationToken ct) =>
|
group.MapGet("/me", async (ClaimsPrincipal principal, AppDbContext db, CancellationToken ct) =>
|
||||||
{
|
{
|
||||||
@@ -59,9 +70,8 @@ public static class AuthEndpoints
|
|||||||
return Results.Ok(new UserStatusDto(false, null, null, null));
|
return Results.Ok(new UserStatusDto(false, null, null, null));
|
||||||
|
|
||||||
return Results.Ok(new UserStatusDto(true, user.Id, user.Email, user.DisplayName));
|
return Results.Ok(new UserStatusDto(true, user.Id, user.Email, user.DisplayName));
|
||||||
}).RequireAuthorization();
|
}).RequireAuthorization().RequireRateLimiting("read");
|
||||||
|
|
||||||
// Allow anonymous me check without 401
|
|
||||||
group.MapGet("/status", async (ClaimsPrincipal principal, AppDbContext db, CancellationToken ct) =>
|
group.MapGet("/status", async (ClaimsPrincipal principal, AppDbContext db, CancellationToken ct) =>
|
||||||
{
|
{
|
||||||
var userId = JwtTokenService.GetUserId(principal);
|
var userId = JwtTokenService.GetUserId(principal);
|
||||||
@@ -73,8 +83,8 @@ public static class AuthEndpoints
|
|||||||
return Results.Ok(new UserStatusDto(false, null, null, null));
|
return Results.Ok(new UserStatusDto(false, null, null, null));
|
||||||
|
|
||||||
return Results.Ok(new UserStatusDto(true, user.Id, user.Email, user.DisplayName));
|
return Results.Ok(new UserStatusDto(true, user.Id, user.Email, user.DisplayName));
|
||||||
});
|
}).RequireRateLimiting("read");
|
||||||
|
|
||||||
return group;
|
return app;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
using System.Security.Claims;
|
using System.Security.Claims;
|
||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
using TafsirQuran.Api.Auth;
|
using TafsirQuran.Api.Security;
|
||||||
using TafsirQuran.Domain.Entities;
|
using TafsirQuran.Domain.Entities;
|
||||||
using TafsirQuran.Infrastructure.Persistence;
|
using TafsirQuran.Infrastructure.Persistence;
|
||||||
using TafsirQuran.Shared.Dtos;
|
using TafsirQuran.Shared.Dtos;
|
||||||
@@ -9,108 +9,158 @@ namespace TafsirQuran.Api.Endpoints;
|
|||||||
|
|
||||||
public static class BookmarkEndpoints
|
public static class BookmarkEndpoints
|
||||||
{
|
{
|
||||||
public static RouteGroupBuilder MapBookmarkEndpoints(this WebApplication app)
|
public static IEndpointRouteBuilder MapBookmarkEndpoints(this WebApplication app)
|
||||||
{
|
{
|
||||||
var surahGroup = app.MapGroup("/api/bookmarks/surahs");
|
var surahGroup = app.MapGroup("/api/bookmarks/surahs");
|
||||||
var ayahGroup = app.MapGroup("/api/bookmarks/ayahs");
|
var ayahGroup = app.MapGroup("/api/bookmarks/ayahs");
|
||||||
|
|
||||||
surahGroup.MapGet("/", async (string deviceId, ClaimsPrincipal user, AppDbContext db, CancellationToken ct) =>
|
surahGroup.MapGet("/", async (string? deviceId, ClaimsPrincipal user, AppDbContext db, CancellationToken ct) =>
|
||||||
{
|
{
|
||||||
var userId = JwtTokenService.GetUserId(user);
|
if (!EndpointSecurity.TryResolveOwner(user, deviceId, out var userId, out var deviceKey, out var error))
|
||||||
var items = await db.SurahBookmarks.AsNoTracking()
|
return error!;
|
||||||
.Include(b => b.Surah)
|
|
||||||
.Where(b => b.DeviceId == deviceId || (userId.HasValue && b.UserId == userId))
|
var query = db.SurahBookmarks.AsNoTracking().Include(b => b.Surah).AsQueryable();
|
||||||
.OrderByDescending(b => b.CreatedAt)
|
query = userId.HasValue
|
||||||
.ToListAsync(ct);
|
? query.Where(b => b.UserId == userId)
|
||||||
|
: query.Where(b => b.DeviceId == deviceKey);
|
||||||
|
|
||||||
|
var items = await query.OrderByDescending(b => b.CreatedAt).ToListAsync(ct);
|
||||||
|
|
||||||
return Results.Ok(items.Select(b => new SurahBookmarkDto(
|
return Results.Ok(items.Select(b => new SurahBookmarkDto(
|
||||||
b.Id, b.TafsirId, b.SurahId, b.Surah.NameFa, b.Note, b.CreatedAt)).ToList());
|
b.Id, b.TafsirId, b.SurahId, b.Surah.NameFa, b.Note, b.CreatedAt)).ToList());
|
||||||
});
|
}).RequireRateLimiting("read");
|
||||||
|
|
||||||
surahGroup.MapPost("/", async (ToggleSurahBookmarkRequest request, ClaimsPrincipal user, AppDbContext db, CancellationToken ct) =>
|
surahGroup.MapPost("/", async (ToggleSurahBookmarkRequest request, ClaimsPrincipal user, AppDbContext db, CancellationToken ct) =>
|
||||||
{
|
{
|
||||||
var userId = JwtTokenService.GetUserId(user);
|
if (!EndpointSecurity.TryResolveOwner(user, request.DeviceId, out var userId, out var deviceKey, out var error))
|
||||||
var exists = await db.SurahBookmarks.AnyAsync(b =>
|
return error!;
|
||||||
b.TafsirId == request.TafsirId &&
|
|
||||||
b.SurahId == request.SurahNumber &&
|
if (!EndpointSecurity.IsValidSurah(request.SurahNumber))
|
||||||
(b.DeviceId == request.DeviceId || (userId.HasValue && b.UserId == userId)), ct);
|
return Results.BadRequest(new { error = "invalid_surah" });
|
||||||
|
|
||||||
|
var note = EndpointSecurity.NormalizeNote(request.Note);
|
||||||
|
|
||||||
|
var exists = userId.HasValue
|
||||||
|
? await db.SurahBookmarks.AnyAsync(b =>
|
||||||
|
b.TafsirId == request.TafsirId && b.SurahId == request.SurahNumber && b.UserId == userId, ct)
|
||||||
|
: await db.SurahBookmarks.AnyAsync(b =>
|
||||||
|
b.TafsirId == request.TafsirId && b.SurahId == request.SurahNumber && b.DeviceId == deviceKey, ct);
|
||||||
|
|
||||||
if (exists) return Results.NoContent();
|
if (exists) return Results.NoContent();
|
||||||
|
|
||||||
db.SurahBookmarks.Add(new SurahBookmark
|
db.SurahBookmarks.Add(new SurahBookmark
|
||||||
{
|
{
|
||||||
DeviceId = request.DeviceId,
|
DeviceId = deviceKey ?? request.DeviceId.Trim(),
|
||||||
UserId = userId,
|
UserId = userId,
|
||||||
TafsirId = request.TafsirId,
|
TafsirId = request.TafsirId,
|
||||||
SurahId = request.SurahNumber,
|
SurahId = request.SurahNumber,
|
||||||
Note = request.Note
|
Note = note
|
||||||
});
|
});
|
||||||
await db.SaveChangesAsync(ct);
|
await db.SaveChangesAsync(ct);
|
||||||
return Results.Created($"/api/bookmarks/surahs/{request.SurahNumber}", null);
|
return Results.Created($"/api/bookmarks/surahs/{request.SurahNumber}", null);
|
||||||
});
|
}).RequireRateLimiting("write");
|
||||||
|
|
||||||
surahGroup.MapDelete("/{surahNumber:int}", async (
|
surahGroup.MapDelete("/{surahNumber:int}", async (
|
||||||
int surahNumber, Guid tafsirId, string deviceId, ClaimsPrincipal user, AppDbContext db, CancellationToken ct) =>
|
int surahNumber, Guid tafsirId, string? deviceId, ClaimsPrincipal user, AppDbContext db, CancellationToken ct) =>
|
||||||
{
|
{
|
||||||
var userId = JwtTokenService.GetUserId(user);
|
if (!EndpointSecurity.TryResolveOwner(user, deviceId, out var userId, out var deviceKey, out var error))
|
||||||
var items = await db.SurahBookmarks
|
return error!;
|
||||||
.Where(b => b.TafsirId == tafsirId && b.SurahId == surahNumber &&
|
|
||||||
(b.DeviceId == deviceId || (userId.HasValue && b.UserId == userId)))
|
if (!EndpointSecurity.IsValidSurah(surahNumber))
|
||||||
.ToListAsync(ct);
|
return Results.BadRequest(new { error = "invalid_surah" });
|
||||||
|
|
||||||
|
var items = userId.HasValue
|
||||||
|
? await db.SurahBookmarks
|
||||||
|
.Where(b => b.TafsirId == tafsirId && b.SurahId == surahNumber && b.UserId == userId)
|
||||||
|
.ToListAsync(ct)
|
||||||
|
: await db.SurahBookmarks
|
||||||
|
.Where(b => b.TafsirId == tafsirId && b.SurahId == surahNumber && b.DeviceId == deviceKey)
|
||||||
|
.ToListAsync(ct);
|
||||||
|
|
||||||
db.SurahBookmarks.RemoveRange(items);
|
db.SurahBookmarks.RemoveRange(items);
|
||||||
await db.SaveChangesAsync(ct);
|
await db.SaveChangesAsync(ct);
|
||||||
return Results.NoContent();
|
return Results.NoContent();
|
||||||
});
|
}).RequireRateLimiting("write");
|
||||||
|
|
||||||
ayahGroup.MapGet("/", async (string deviceId, ClaimsPrincipal user, AppDbContext db, CancellationToken ct) =>
|
ayahGroup.MapGet("/", async (string? deviceId, ClaimsPrincipal user, AppDbContext db, CancellationToken ct) =>
|
||||||
{
|
{
|
||||||
var userId = JwtTokenService.GetUserId(user);
|
if (!EndpointSecurity.TryResolveOwner(user, deviceId, out var userId, out var deviceKey, out var error))
|
||||||
var items = await db.AyahBookmarks.AsNoTracking()
|
return error!;
|
||||||
|
|
||||||
|
var query = db.AyahBookmarks.AsNoTracking()
|
||||||
.Include(b => b.Surah)
|
.Include(b => b.Surah)
|
||||||
.Include(b => b.Tafsir)
|
.Include(b => b.Tafsir)
|
||||||
.Where(b => b.DeviceId == deviceId || (userId.HasValue && b.UserId == userId))
|
.AsQueryable();
|
||||||
.OrderByDescending(b => b.CreatedAt)
|
|
||||||
.ToListAsync(ct);
|
query = userId.HasValue
|
||||||
|
? query.Where(b => b.UserId == userId)
|
||||||
|
: query.Where(b => b.DeviceId == deviceKey);
|
||||||
|
|
||||||
|
var items = await query.OrderByDescending(b => b.CreatedAt).ToListAsync(ct);
|
||||||
|
|
||||||
return Results.Ok(items.Select(b => new AyahBookmarkDto(
|
return Results.Ok(items.Select(b => new AyahBookmarkDto(
|
||||||
b.Id, b.TafsirId, b.Tafsir.Slug, b.SurahId, b.Surah.NameFa, b.AyahNumber, b.Note, b.CreatedAt)).ToList());
|
b.Id, b.TafsirId, b.Tafsir.Slug, b.SurahId, b.Surah.NameFa, b.AyahNumber, b.Note, b.CreatedAt)).ToList());
|
||||||
});
|
}).RequireRateLimiting("read");
|
||||||
|
|
||||||
ayahGroup.MapPost("/", async (ToggleAyahRequest request, ClaimsPrincipal user, AppDbContext db, CancellationToken ct) =>
|
ayahGroup.MapPost("/", async (ToggleAyahRequest request, ClaimsPrincipal user, AppDbContext db, CancellationToken ct) =>
|
||||||
{
|
{
|
||||||
var userId = JwtTokenService.GetUserId(user);
|
if (!EndpointSecurity.TryResolveOwner(user, request.DeviceId, out var userId, out var deviceKey, out var error))
|
||||||
var exists = await db.AyahBookmarks.AnyAsync(b =>
|
return error!;
|
||||||
b.TafsirId == request.TafsirId &&
|
|
||||||
b.SurahId == request.SurahNumber &&
|
if (!EndpointSecurity.IsValidSurahAyah(request.SurahNumber, request.AyahNumber))
|
||||||
b.AyahNumber == request.AyahNumber &&
|
return Results.BadRequest(new { error = "invalid_ayah" });
|
||||||
(b.DeviceId == request.DeviceId || (userId.HasValue && b.UserId == userId)), ct);
|
|
||||||
|
var note = EndpointSecurity.NormalizeNote(request.Note);
|
||||||
|
|
||||||
|
var exists = userId.HasValue
|
||||||
|
? await db.AyahBookmarks.AnyAsync(b =>
|
||||||
|
b.TafsirId == request.TafsirId &&
|
||||||
|
b.SurahId == request.SurahNumber &&
|
||||||
|
b.AyahNumber == request.AyahNumber &&
|
||||||
|
b.UserId == userId, ct)
|
||||||
|
: await db.AyahBookmarks.AnyAsync(b =>
|
||||||
|
b.TafsirId == request.TafsirId &&
|
||||||
|
b.SurahId == request.SurahNumber &&
|
||||||
|
b.AyahNumber == request.AyahNumber &&
|
||||||
|
b.DeviceId == deviceKey, ct);
|
||||||
|
|
||||||
if (exists) return Results.NoContent();
|
if (exists) return Results.NoContent();
|
||||||
|
|
||||||
db.AyahBookmarks.Add(new AyahBookmark
|
db.AyahBookmarks.Add(new AyahBookmark
|
||||||
{
|
{
|
||||||
DeviceId = request.DeviceId,
|
DeviceId = deviceKey ?? request.DeviceId.Trim(),
|
||||||
UserId = userId,
|
UserId = userId,
|
||||||
TafsirId = request.TafsirId,
|
TafsirId = request.TafsirId,
|
||||||
SurahId = request.SurahNumber,
|
SurahId = request.SurahNumber,
|
||||||
AyahNumber = request.AyahNumber,
|
AyahNumber = request.AyahNumber,
|
||||||
Note = request.Note
|
Note = note
|
||||||
});
|
});
|
||||||
await db.SaveChangesAsync(ct);
|
await db.SaveChangesAsync(ct);
|
||||||
return Results.Created($"/api/bookmarks/ayahs/{request.SurahNumber}/{request.AyahNumber}", null);
|
return Results.Created($"/api/bookmarks/ayahs/{request.SurahNumber}/{request.AyahNumber}", null);
|
||||||
});
|
}).RequireRateLimiting("write");
|
||||||
|
|
||||||
ayahGroup.MapDelete("/{surahNumber:int}/{ayahNumber:int}", async (
|
ayahGroup.MapDelete("/{surahNumber:int}/{ayahNumber:int}", async (
|
||||||
int surahNumber, int ayahNumber, Guid tafsirId, string deviceId, ClaimsPrincipal user, AppDbContext db, CancellationToken ct) =>
|
int surahNumber, int ayahNumber, Guid tafsirId, string? deviceId, ClaimsPrincipal user, AppDbContext db, CancellationToken ct) =>
|
||||||
{
|
{
|
||||||
var userId = JwtTokenService.GetUserId(user);
|
if (!EndpointSecurity.TryResolveOwner(user, deviceId, out var userId, out var deviceKey, out var error))
|
||||||
var items = await db.AyahBookmarks
|
return error!;
|
||||||
.Where(b => b.TafsirId == tafsirId && b.SurahId == surahNumber && b.AyahNumber == ayahNumber &&
|
|
||||||
(b.DeviceId == deviceId || (userId.HasValue && b.UserId == userId)))
|
if (!EndpointSecurity.IsValidSurahAyah(surahNumber, ayahNumber))
|
||||||
.ToListAsync(ct);
|
return Results.BadRequest(new { error = "invalid_ayah" });
|
||||||
|
|
||||||
|
var items = userId.HasValue
|
||||||
|
? await db.AyahBookmarks
|
||||||
|
.Where(b => b.TafsirId == tafsirId && b.SurahId == surahNumber && b.AyahNumber == ayahNumber && b.UserId == userId)
|
||||||
|
.ToListAsync(ct)
|
||||||
|
: await db.AyahBookmarks
|
||||||
|
.Where(b => b.TafsirId == tafsirId && b.SurahId == surahNumber && b.AyahNumber == ayahNumber && b.DeviceId == deviceKey)
|
||||||
|
.ToListAsync(ct);
|
||||||
|
|
||||||
db.AyahBookmarks.RemoveRange(items);
|
db.AyahBookmarks.RemoveRange(items);
|
||||||
await db.SaveChangesAsync(ct);
|
await db.SaveChangesAsync(ct);
|
||||||
return Results.NoContent();
|
return Results.NoContent();
|
||||||
});
|
}).RequireRateLimiting("write");
|
||||||
|
|
||||||
return surahGroup;
|
return app;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
using System.Security.Claims;
|
using System.Security.Claims;
|
||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
using TafsirQuran.Api.Auth;
|
using TafsirQuran.Api.Security;
|
||||||
using TafsirQuran.Domain.Entities;
|
using TafsirQuran.Domain.Entities;
|
||||||
using TafsirQuran.Infrastructure.Persistence;
|
using TafsirQuran.Infrastructure.Persistence;
|
||||||
using TafsirQuran.Shared.Dtos;
|
using TafsirQuran.Shared.Dtos;
|
||||||
@@ -9,37 +9,55 @@ namespace TafsirQuran.Api.Endpoints;
|
|||||||
|
|
||||||
public static class FavoriteEndpoints
|
public static class FavoriteEndpoints
|
||||||
{
|
{
|
||||||
public static RouteGroupBuilder MapFavoriteEndpoints(this WebApplication app)
|
public static IEndpointRouteBuilder MapFavoriteEndpoints(this WebApplication app)
|
||||||
{
|
{
|
||||||
var group = app.MapGroup("/api/favorites/ayahs");
|
var group = app.MapGroup("/api/favorites/ayahs");
|
||||||
|
|
||||||
group.MapGet("/", async (string deviceId, ClaimsPrincipal user, AppDbContext db, CancellationToken ct) =>
|
group.MapGet("/", async (string? deviceId, ClaimsPrincipal user, AppDbContext db, CancellationToken ct) =>
|
||||||
{
|
{
|
||||||
var userId = JwtTokenService.GetUserId(user);
|
if (!EndpointSecurity.TryResolveOwner(user, deviceId, out var userId, out var deviceKey, out var error))
|
||||||
var items = await db.AyahFavorites.AsNoTracking()
|
return error!;
|
||||||
|
|
||||||
|
var query = db.AyahFavorites.AsNoTracking()
|
||||||
.Include(f => f.Surah)
|
.Include(f => f.Surah)
|
||||||
.Include(f => f.Tafsir)
|
.Include(f => f.Tafsir)
|
||||||
.Where(f => f.DeviceId == deviceId || (userId.HasValue && f.UserId == userId))
|
.AsQueryable();
|
||||||
.OrderByDescending(f => f.CreatedAt)
|
|
||||||
.ToListAsync(ct);
|
query = userId.HasValue
|
||||||
|
? query.Where(f => f.UserId == userId)
|
||||||
|
: query.Where(f => f.DeviceId == deviceKey);
|
||||||
|
|
||||||
|
var items = await query.OrderByDescending(f => f.CreatedAt).ToListAsync(ct);
|
||||||
|
|
||||||
return Results.Ok(items.Select(f => new AyahFavoriteDto(
|
return Results.Ok(items.Select(f => new AyahFavoriteDto(
|
||||||
f.Id, f.TafsirId, f.Tafsir.Slug, f.SurahId, f.Surah.NameFa, f.AyahNumber, f.CreatedAt)).ToList());
|
f.Id, f.TafsirId, f.Tafsir.Slug, f.SurahId, f.Surah.NameFa, f.AyahNumber, f.CreatedAt)).ToList());
|
||||||
});
|
}).RequireRateLimiting("read");
|
||||||
|
|
||||||
group.MapPost("/", async (ToggleAyahRequest request, ClaimsPrincipal user, AppDbContext db, CancellationToken ct) =>
|
group.MapPost("/", async (ToggleAyahRequest request, ClaimsPrincipal user, AppDbContext db, CancellationToken ct) =>
|
||||||
{
|
{
|
||||||
var userId = JwtTokenService.GetUserId(user);
|
if (!EndpointSecurity.TryResolveOwner(user, request.DeviceId, out var userId, out var deviceKey, out var error))
|
||||||
var exists = await db.AyahFavorites.AnyAsync(f =>
|
return error!;
|
||||||
f.TafsirId == request.TafsirId &&
|
|
||||||
f.SurahId == request.SurahNumber &&
|
if (!EndpointSecurity.IsValidSurahAyah(request.SurahNumber, request.AyahNumber))
|
||||||
f.AyahNumber == request.AyahNumber &&
|
return Results.BadRequest(new { error = "invalid_ayah" });
|
||||||
(f.DeviceId == request.DeviceId || (userId.HasValue && f.UserId == userId)), ct);
|
|
||||||
|
var exists = userId.HasValue
|
||||||
|
? await db.AyahFavorites.AnyAsync(f =>
|
||||||
|
f.TafsirId == request.TafsirId &&
|
||||||
|
f.SurahId == request.SurahNumber &&
|
||||||
|
f.AyahNumber == request.AyahNumber &&
|
||||||
|
f.UserId == userId, ct)
|
||||||
|
: await db.AyahFavorites.AnyAsync(f =>
|
||||||
|
f.TafsirId == request.TafsirId &&
|
||||||
|
f.SurahId == request.SurahNumber &&
|
||||||
|
f.AyahNumber == request.AyahNumber &&
|
||||||
|
f.DeviceId == deviceKey, ct);
|
||||||
|
|
||||||
if (exists) return Results.NoContent();
|
if (exists) return Results.NoContent();
|
||||||
|
|
||||||
db.AyahFavorites.Add(new AyahFavorite
|
db.AyahFavorites.Add(new AyahFavorite
|
||||||
{
|
{
|
||||||
DeviceId = request.DeviceId,
|
DeviceId = deviceKey ?? request.DeviceId.Trim(),
|
||||||
UserId = userId,
|
UserId = userId,
|
||||||
TafsirId = request.TafsirId,
|
TafsirId = request.TafsirId,
|
||||||
SurahId = request.SurahNumber,
|
SurahId = request.SurahNumber,
|
||||||
@@ -47,21 +65,30 @@ public static class FavoriteEndpoints
|
|||||||
});
|
});
|
||||||
await db.SaveChangesAsync(ct);
|
await db.SaveChangesAsync(ct);
|
||||||
return Results.Created($"/api/favorites/ayahs/{request.SurahNumber}/{request.AyahNumber}", null);
|
return Results.Created($"/api/favorites/ayahs/{request.SurahNumber}/{request.AyahNumber}", null);
|
||||||
});
|
}).RequireRateLimiting("write");
|
||||||
|
|
||||||
group.MapDelete("/{surahNumber:int}/{ayahNumber:int}", async (
|
group.MapDelete("/{surahNumber:int}/{ayahNumber:int}", async (
|
||||||
int surahNumber, int ayahNumber, Guid tafsirId, string deviceId, ClaimsPrincipal user, AppDbContext db, CancellationToken ct) =>
|
int surahNumber, int ayahNumber, Guid tafsirId, string? deviceId, ClaimsPrincipal user, AppDbContext db, CancellationToken ct) =>
|
||||||
{
|
{
|
||||||
var userId = JwtTokenService.GetUserId(user);
|
if (!EndpointSecurity.TryResolveOwner(user, deviceId, out var userId, out var deviceKey, out var error))
|
||||||
var items = await db.AyahFavorites
|
return error!;
|
||||||
.Where(f => f.TafsirId == tafsirId && f.SurahId == surahNumber && f.AyahNumber == ayahNumber &&
|
|
||||||
(f.DeviceId == deviceId || (userId.HasValue && f.UserId == userId)))
|
if (!EndpointSecurity.IsValidSurahAyah(surahNumber, ayahNumber))
|
||||||
.ToListAsync(ct);
|
return Results.BadRequest(new { error = "invalid_ayah" });
|
||||||
|
|
||||||
|
var items = userId.HasValue
|
||||||
|
? await db.AyahFavorites
|
||||||
|
.Where(f => f.TafsirId == tafsirId && f.SurahId == surahNumber && f.AyahNumber == ayahNumber && f.UserId == userId)
|
||||||
|
.ToListAsync(ct)
|
||||||
|
: await db.AyahFavorites
|
||||||
|
.Where(f => f.TafsirId == tafsirId && f.SurahId == surahNumber && f.AyahNumber == ayahNumber && f.DeviceId == deviceKey)
|
||||||
|
.ToListAsync(ct);
|
||||||
|
|
||||||
db.AyahFavorites.RemoveRange(items);
|
db.AyahFavorites.RemoveRange(items);
|
||||||
await db.SaveChangesAsync(ct);
|
await db.SaveChangesAsync(ct);
|
||||||
return Results.NoContent();
|
return Results.NoContent();
|
||||||
});
|
}).RequireRateLimiting("write");
|
||||||
|
|
||||||
return group;
|
return app;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
using System.Security.Claims;
|
using System.Security.Claims;
|
||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
using TafsirQuran.Api.Auth;
|
using TafsirQuran.Api.Security;
|
||||||
using TafsirQuran.Domain.Entities;
|
using TafsirQuran.Domain.Entities;
|
||||||
using TafsirQuran.Infrastructure.Persistence;
|
using TafsirQuran.Infrastructure.Persistence;
|
||||||
using TafsirQuran.Shared.Dtos;
|
using TafsirQuran.Shared.Dtos;
|
||||||
@@ -9,19 +9,21 @@ namespace TafsirQuran.Api.Endpoints;
|
|||||||
|
|
||||||
public static class ProgressEndpoints
|
public static class ProgressEndpoints
|
||||||
{
|
{
|
||||||
public static RouteGroupBuilder MapProgressEndpoints(this WebApplication app)
|
public static IEndpointRouteBuilder MapProgressEndpoints(this WebApplication app)
|
||||||
{
|
{
|
||||||
var group = app.MapGroup("/api/progress");
|
var group = app.MapGroup("/api/progress");
|
||||||
|
|
||||||
group.MapGet("/", async (string deviceId, ClaimsPrincipal user, AppDbContext db, CancellationToken ct) =>
|
group.MapGet("/", async (string? deviceId, ClaimsPrincipal user, AppDbContext db, CancellationToken ct) =>
|
||||||
{
|
{
|
||||||
var userId = JwtTokenService.GetUserId(user);
|
if (!EndpointSecurity.TryResolveOwner(user, deviceId, out var userId, out var deviceKey, out var error))
|
||||||
var query = db.ListeningProgresses.AsNoTracking().Include(p => p.Surah).AsQueryable();
|
return error!;
|
||||||
|
|
||||||
ListeningProgress? progress = null;
|
var query = db.ListeningProgresses.AsNoTracking().Include(p => p.Surah).AsQueryable();
|
||||||
|
ListeningProgress? progress;
|
||||||
if (userId.HasValue)
|
if (userId.HasValue)
|
||||||
progress = await query.Where(p => p.UserId == userId).OrderByDescending(p => p.UpdatedAt).FirstOrDefaultAsync(ct);
|
progress = await query.Where(p => p.UserId == userId).OrderByDescending(p => p.UpdatedAt).FirstOrDefaultAsync(ct);
|
||||||
progress ??= await query.Where(p => p.DeviceId == deviceId).OrderByDescending(p => p.UpdatedAt).FirstOrDefaultAsync(ct);
|
else
|
||||||
|
progress = await query.Where(p => p.DeviceId == deviceKey).OrderByDescending(p => p.UpdatedAt).FirstOrDefaultAsync(ct);
|
||||||
|
|
||||||
if (progress is null) return Results.NoContent();
|
if (progress is null) return Results.NoContent();
|
||||||
|
|
||||||
@@ -32,24 +34,40 @@ public static class ProgressEndpoints
|
|||||||
progress.PositionSeconds,
|
progress.PositionSeconds,
|
||||||
progress.UpdatedAt,
|
progress.UpdatedAt,
|
||||||
progress.Surah.NameFa));
|
progress.Surah.NameFa));
|
||||||
});
|
}).RequireRateLimiting("read");
|
||||||
|
|
||||||
group.MapPut("/", async (UpsertProgressRequest request, ClaimsPrincipal user, AppDbContext db, CancellationToken ct) =>
|
group.MapPut("/", async (UpsertProgressRequest request, ClaimsPrincipal user, AppDbContext db, CancellationToken ct) =>
|
||||||
{
|
{
|
||||||
if (string.IsNullOrWhiteSpace(request.DeviceId))
|
if (!EndpointSecurity.TryResolveOwner(user, request.DeviceId, out var userId, out var deviceKey, out var error))
|
||||||
return Results.BadRequest("deviceId required");
|
return error!;
|
||||||
|
|
||||||
var userId = JwtTokenService.GetUserId(user);
|
if (request.PositionSeconds < 0)
|
||||||
var existing = await db.ListeningProgresses
|
return Results.BadRequest(new { error = "invalid_position" });
|
||||||
.Where(p => p.DeviceId == request.DeviceId || (userId.HasValue && p.UserId == userId))
|
|
||||||
.OrderByDescending(p => p.UpdatedAt)
|
if (!EndpointSecurity.IsValidSurahAyah(request.SurahNumber, request.AyahNumber))
|
||||||
.FirstOrDefaultAsync(ct);
|
return Results.BadRequest(new { error = "invalid_ayah" });
|
||||||
|
|
||||||
|
ListeningProgress? existing;
|
||||||
|
if (userId.HasValue)
|
||||||
|
{
|
||||||
|
existing = await db.ListeningProgresses
|
||||||
|
.Where(p => p.UserId == userId)
|
||||||
|
.OrderByDescending(p => p.UpdatedAt)
|
||||||
|
.FirstOrDefaultAsync(ct);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
existing = await db.ListeningProgresses
|
||||||
|
.Where(p => p.DeviceId == deviceKey)
|
||||||
|
.OrderByDescending(p => p.UpdatedAt)
|
||||||
|
.FirstOrDefaultAsync(ct);
|
||||||
|
}
|
||||||
|
|
||||||
if (existing is null)
|
if (existing is null)
|
||||||
{
|
{
|
||||||
existing = new ListeningProgress
|
existing = new ListeningProgress
|
||||||
{
|
{
|
||||||
DeviceId = request.DeviceId,
|
DeviceId = deviceKey ?? request.DeviceId.Trim(),
|
||||||
UserId = userId,
|
UserId = userId,
|
||||||
TafsirId = request.TafsirId,
|
TafsirId = request.TafsirId,
|
||||||
SurahId = request.SurahNumber,
|
SurahId = request.SurahNumber,
|
||||||
@@ -60,20 +78,30 @@ public static class ProgressEndpoints
|
|||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
existing.TafsirId = request.TafsirId;
|
var sameTrack = existing.TafsirId == request.TafsirId
|
||||||
existing.SurahId = request.SurahNumber;
|
&& existing.SurahId == request.SurahNumber
|
||||||
existing.AyahNumber = request.AyahNumber;
|
&& existing.AyahNumber == request.AyahNumber;
|
||||||
|
var recent = (DateTimeOffset.UtcNow - existing.UpdatedAt) < TimeSpan.FromSeconds(2);
|
||||||
|
|
||||||
existing.PositionSeconds = request.PositionSeconds;
|
existing.PositionSeconds = request.PositionSeconds;
|
||||||
existing.UpdatedAt = DateTimeOffset.UtcNow;
|
existing.UpdatedAt = DateTimeOffset.UtcNow;
|
||||||
existing.UserId ??= userId;
|
if (userId.HasValue)
|
||||||
if (string.IsNullOrWhiteSpace(existing.DeviceId))
|
existing.UserId = userId;
|
||||||
existing.DeviceId = request.DeviceId;
|
if (!string.IsNullOrWhiteSpace(deviceKey) && string.IsNullOrWhiteSpace(existing.DeviceId))
|
||||||
|
existing.DeviceId = deviceKey;
|
||||||
|
|
||||||
|
if (!sameTrack || !recent)
|
||||||
|
{
|
||||||
|
existing.TafsirId = request.TafsirId;
|
||||||
|
existing.SurahId = request.SurahNumber;
|
||||||
|
existing.AyahNumber = request.AyahNumber;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
await db.SaveChangesAsync(ct);
|
await db.SaveChangesAsync(ct);
|
||||||
return Results.NoContent();
|
return Results.NoContent();
|
||||||
});
|
}).RequireRateLimiting("write");
|
||||||
|
|
||||||
return group;
|
return app;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using TafsirQuran.Api.Security;
|
||||||
using TafsirQuran.Infrastructure.Persistence;
|
using TafsirQuran.Infrastructure.Persistence;
|
||||||
using TafsirQuran.Shared.Dtos;
|
using TafsirQuran.Shared.Dtos;
|
||||||
|
|
||||||
@@ -6,7 +7,7 @@ namespace TafsirQuran.Api.Endpoints;
|
|||||||
|
|
||||||
public static class TafsirEndpoints
|
public static class TafsirEndpoints
|
||||||
{
|
{
|
||||||
public static RouteGroupBuilder MapTafsirEndpoints(this WebApplication app)
|
public static IEndpointRouteBuilder MapTafsirEndpoints(this WebApplication app)
|
||||||
{
|
{
|
||||||
var group = app.MapGroup("/api");
|
var group = app.MapGroup("/api");
|
||||||
|
|
||||||
@@ -19,16 +20,17 @@ public static class TafsirEndpoints
|
|||||||
.Select(t => new TafsirDto(t.Id, t.Title, t.Author, t.Slug, t.CoverUrl))
|
.Select(t => new TafsirDto(t.Id, t.Title, t.Author, t.Slug, t.CoverUrl))
|
||||||
.ToListAsync(ct);
|
.ToListAsync(ct);
|
||||||
return Results.Ok(items);
|
return Results.Ok(items);
|
||||||
});
|
}).RequireRateLimiting("read");
|
||||||
|
|
||||||
group.MapGet("/surahs", async (AppDbContext db, string? deviceId, Guid? tafsirId, CancellationToken ct) =>
|
group.MapGet("/surahs", async (AppDbContext db, string? deviceId, Guid? tafsirId, CancellationToken ct) =>
|
||||||
{
|
{
|
||||||
var tid = tafsirId ?? DbSeeder.GhatrehChekaniId;
|
var tid = tafsirId ?? DbSeeder.GhatrehChekaniId;
|
||||||
var bookmarked = new HashSet<int>();
|
var bookmarked = new HashSet<int>();
|
||||||
if (!string.IsNullOrWhiteSpace(deviceId))
|
if (!string.IsNullOrWhiteSpace(deviceId) &&
|
||||||
|
EndpointSecurity.TryNormalizeDeviceId(deviceId, out var deviceKey, out _))
|
||||||
{
|
{
|
||||||
bookmarked = (await db.SurahBookmarks.AsNoTracking()
|
bookmarked = (await db.SurahBookmarks.AsNoTracking()
|
||||||
.Where(b => b.TafsirId == tid && b.DeviceId == deviceId)
|
.Where(b => b.TafsirId == tid && b.DeviceId == deviceKey)
|
||||||
.Select(b => b.SurahId)
|
.Select(b => b.SurahId)
|
||||||
.ToListAsync(ct))
|
.ToListAsync(ct))
|
||||||
.ToHashSet();
|
.ToHashSet();
|
||||||
@@ -39,7 +41,6 @@ public static class TafsirEndpoints
|
|||||||
.Select(g => new { SurahId = g.Key, Count = g.Count() })
|
.Select(g => new { SurahId = g.Key, Count = g.Count() })
|
||||||
.ToDictionaryAsync(x => x.SurahId, x => x.Count, ct);
|
.ToDictionaryAsync(x => x.SurahId, x => x.Count, ct);
|
||||||
|
|
||||||
// Fallback: content rows if ayahs not yet imported for a surah
|
|
||||||
var contentCounts = await db.TafsirAyahContents.AsNoTracking()
|
var contentCounts = await db.TafsirAyahContents.AsNoTracking()
|
||||||
.Where(c => c.TafsirId == tid)
|
.Where(c => c.TafsirId == tid)
|
||||||
.GroupBy(c => c.SurahId)
|
.GroupBy(c => c.SurahId)
|
||||||
@@ -55,11 +56,14 @@ public static class TafsirEndpoints
|
|||||||
}).ToList();
|
}).ToList();
|
||||||
|
|
||||||
return Results.Ok(result);
|
return Results.Ok(result);
|
||||||
});
|
}).RequireRateLimiting("read");
|
||||||
|
|
||||||
group.MapGet("/tafsirs/{slug}/surahs/{surahNumber:int}/ayahs", async (
|
group.MapGet("/tafsirs/{slug}/surahs/{surahNumber:int}/ayahs", async (
|
||||||
string slug, int surahNumber, string? deviceId, AppDbContext db, CancellationToken ct) =>
|
string slug, int surahNumber, string? deviceId, AppDbContext db, CancellationToken ct) =>
|
||||||
{
|
{
|
||||||
|
if (!EndpointSecurity.IsValidSurah(surahNumber))
|
||||||
|
return Results.BadRequest(new { error = "invalid_surah" });
|
||||||
|
|
||||||
var tafsir = await db.Tafsirs.AsNoTracking().FirstOrDefaultAsync(t => t.Slug == slug && t.IsPublished, ct);
|
var tafsir = await db.Tafsirs.AsNoTracking().FirstOrDefaultAsync(t => t.Slug == slug && t.IsPublished, ct);
|
||||||
if (tafsir is null) return Results.NotFound();
|
if (tafsir is null) return Results.NotFound();
|
||||||
|
|
||||||
@@ -68,13 +72,14 @@ public static class TafsirEndpoints
|
|||||||
|
|
||||||
var bookmarks = new HashSet<int>();
|
var bookmarks = new HashSet<int>();
|
||||||
var favorites = new HashSet<int>();
|
var favorites = new HashSet<int>();
|
||||||
if (!string.IsNullOrWhiteSpace(deviceId))
|
if (!string.IsNullOrWhiteSpace(deviceId) &&
|
||||||
|
EndpointSecurity.TryNormalizeDeviceId(deviceId, out var deviceKey, out _))
|
||||||
{
|
{
|
||||||
bookmarks = (await db.AyahBookmarks.AsNoTracking()
|
bookmarks = (await db.AyahBookmarks.AsNoTracking()
|
||||||
.Where(b => b.TafsirId == tafsir.Id && b.SurahId == surah.Id && b.DeviceId == deviceId)
|
.Where(b => b.TafsirId == tafsir.Id && b.SurahId == surah.Id && b.DeviceId == deviceKey)
|
||||||
.Select(b => b.AyahNumber).ToListAsync(ct)).ToHashSet();
|
.Select(b => b.AyahNumber).ToListAsync(ct)).ToHashSet();
|
||||||
favorites = (await db.AyahFavorites.AsNoTracking()
|
favorites = (await db.AyahFavorites.AsNoTracking()
|
||||||
.Where(f => f.TafsirId == tafsir.Id && f.SurahId == surah.Id && f.DeviceId == deviceId)
|
.Where(f => f.TafsirId == tafsir.Id && f.SurahId == surah.Id && f.DeviceId == deviceKey)
|
||||||
.Select(f => f.AyahNumber).ToListAsync(ct)).ToHashSet();
|
.Select(f => f.AyahNumber).ToListAsync(ct)).ToHashSet();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -97,11 +102,11 @@ public static class TafsirEndpoints
|
|||||||
}).ToList();
|
}).ToList();
|
||||||
}
|
}
|
||||||
|
|
||||||
var episodeAyahs = (await db.Episodes.AsNoTracking()
|
var episodeAyahs = (await db.Episodes.AsNoTracking()
|
||||||
.Where(e => e.TafsirId == tafsir.Id && e.SurahId == surah.Id)
|
.Where(e => e.TafsirId == tafsir.Id && e.SurahId == surah.Id)
|
||||||
.Select(e => e.AyahNumber)
|
.Select(e => e.AyahNumber)
|
||||||
.Distinct()
|
.Distinct()
|
||||||
.ToListAsync(ct)).ToHashSet();
|
.ToListAsync(ct)).ToHashSet();
|
||||||
|
|
||||||
var list = ayahs.Select(a =>
|
var list = ayahs.Select(a =>
|
||||||
{
|
{
|
||||||
@@ -122,11 +127,14 @@ public static class TafsirEndpoints
|
|||||||
}).ToList();
|
}).ToList();
|
||||||
|
|
||||||
return Results.Ok(list);
|
return Results.Ok(list);
|
||||||
});
|
}).RequireRateLimiting("read");
|
||||||
|
|
||||||
group.MapGet("/tafsirs/{slug}/surahs/{surahNumber:int}/ayahs/{ayahNumber:int}", async (
|
group.MapGet("/tafsirs/{slug}/surahs/{surahNumber:int}/ayahs/{ayahNumber:int}", async (
|
||||||
string slug, int surahNumber, int ayahNumber, AppDbContext db, CancellationToken ct) =>
|
string slug, int surahNumber, int ayahNumber, AppDbContext db, CancellationToken ct) =>
|
||||||
{
|
{
|
||||||
|
if (!EndpointSecurity.IsValidSurahAyah(surahNumber, ayahNumber))
|
||||||
|
return Results.BadRequest(new { error = "invalid_ayah" });
|
||||||
|
|
||||||
var tafsir = await db.Tafsirs.AsNoTracking().FirstOrDefaultAsync(t => t.Slug == slug && t.IsPublished, ct);
|
var tafsir = await db.Tafsirs.AsNoTracking().FirstOrDefaultAsync(t => t.Slug == slug && t.IsPublished, ct);
|
||||||
if (tafsir is null) return Results.NotFound();
|
if (tafsir is null) return Results.NotFound();
|
||||||
|
|
||||||
@@ -169,7 +177,6 @@ public static class TafsirEndpoints
|
|||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
// Fall back to existing Gooya episode audio already on PVC (best-effort ayah match).
|
|
||||||
var episode = await db.Episodes.AsNoTracking()
|
var episode = await db.Episodes.AsNoTracking()
|
||||||
.Where(e => e.TafsirId == tafsir.Id && e.SurahId == surah.Id && e.AyahNumber == ayahNumber)
|
.Where(e => e.TafsirId == tafsir.Id && e.SurahId == surah.Id && e.AyahNumber == ayahNumber)
|
||||||
.OrderBy(e => e.SortOrder)
|
.OrderBy(e => e.SortOrder)
|
||||||
@@ -200,11 +207,15 @@ public static class TafsirEndpoints
|
|||||||
next,
|
next,
|
||||||
prevSurah,
|
prevSurah,
|
||||||
nextSurah));
|
nextSurah));
|
||||||
});
|
}).RequireRateLimiting("read");
|
||||||
|
|
||||||
|
// Audio streaming — intentionally NO rate limiting (player range/seek traffic).
|
||||||
group.MapGet("/audio/ayah/{surahNumber:int}/{ayahNumber:int}", async (
|
group.MapGet("/audio/ayah/{surahNumber:int}/{ayahNumber:int}", async (
|
||||||
int surahNumber, int ayahNumber, Guid? tafsirId, AppDbContext db, IConfiguration config, CancellationToken ct) =>
|
int surahNumber, int ayahNumber, Guid? tafsirId, AppDbContext db, IConfiguration config, CancellationToken ct) =>
|
||||||
{
|
{
|
||||||
|
if (!EndpointSecurity.IsValidSurahAyah(surahNumber, ayahNumber))
|
||||||
|
return Results.NotFound();
|
||||||
|
|
||||||
var tid = tafsirId ?? DbSeeder.GhatrehChekaniId;
|
var tid = tafsirId ?? DbSeeder.GhatrehChekaniId;
|
||||||
var content = await db.TafsirAyahContents.AsNoTracking()
|
var content = await db.TafsirAyahContents.AsNoTracking()
|
||||||
.FirstOrDefaultAsync(c => c.TafsirId == tid && c.SurahId == surahNumber && c.AyahNumber == ayahNumber, ct);
|
.FirstOrDefaultAsync(c => c.TafsirId == tid && c.SurahId == surahNumber && c.AyahNumber == ayahNumber, ct);
|
||||||
@@ -212,15 +223,12 @@ public static class TafsirEndpoints
|
|||||||
return Results.NotFound();
|
return Results.NotFound();
|
||||||
|
|
||||||
var audioRoot = config["AudioRoot"] ?? "/data/audio";
|
var audioRoot = config["AudioRoot"] ?? "/data/audio";
|
||||||
var relative = content.AudioPath.TrimStart('/').Replace('\\', '/');
|
if (!EndpointSecurity.TryResolveUnderRoot(audioRoot, content.AudioPath, out var path))
|
||||||
var path = Path.Combine(audioRoot, relative);
|
|
||||||
if (!File.Exists(path))
|
|
||||||
return Results.NotFound();
|
return Results.NotFound();
|
||||||
|
|
||||||
return Results.File(path, "audio/mpeg", enableRangeProcessing: true);
|
return Results.File(path, "audio/mpeg", enableRangeProcessing: true);
|
||||||
});
|
});
|
||||||
|
|
||||||
// Legacy Gooya files already on PVC
|
|
||||||
group.MapGet("/audio/{episodeId:guid}", async (
|
group.MapGet("/audio/{episodeId:guid}", async (
|
||||||
Guid episodeId, AppDbContext db, IConfiguration config, IWebHostEnvironment env, CancellationToken ct) =>
|
Guid episodeId, AppDbContext db, IConfiguration config, IWebHostEnvironment env, CancellationToken ct) =>
|
||||||
{
|
{
|
||||||
@@ -229,22 +237,19 @@ public static class TafsirEndpoints
|
|||||||
|
|
||||||
var audioRoot = config["AudioRoot"] ?? "/data/audio";
|
var audioRoot = config["AudioRoot"] ?? "/data/audio";
|
||||||
var relative = episode.AudioUrl.TrimStart('/').Replace('\\', '/');
|
var relative = episode.AudioUrl.TrimStart('/').Replace('\\', '/');
|
||||||
var candidates = new[]
|
var wwwroot = Path.Combine(env.ContentRootPath, "wwwroot");
|
||||||
{
|
var wwwAudio = Path.Combine(wwwroot, "audio");
|
||||||
Path.Combine(audioRoot, relative),
|
|
||||||
Path.Combine(env.ContentRootPath, "wwwroot", relative),
|
|
||||||
Path.Combine(env.ContentRootPath, "wwwroot", "audio", Path.GetFileName(relative))
|
|
||||||
};
|
|
||||||
|
|
||||||
foreach (var path in candidates)
|
if (EndpointSecurity.TryResolveUnderRoot(audioRoot, relative, out var path) ||
|
||||||
|
EndpointSecurity.TryResolveUnderRoot(wwwroot, relative, out path) ||
|
||||||
|
EndpointSecurity.TryResolveUnderRoot(wwwAudio, Path.GetFileName(relative), out path))
|
||||||
{
|
{
|
||||||
if (File.Exists(path))
|
return Results.File(path, "audio/mpeg", enableRangeProcessing: true);
|
||||||
return Results.File(path, "audio/mpeg", enableRangeProcessing: true);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return Results.NotFound();
|
return Results.NotFound();
|
||||||
});
|
});
|
||||||
|
|
||||||
return group;
|
return app;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,8 +1,12 @@
|
|||||||
|
using System.Threading.RateLimiting;
|
||||||
using System.Text;
|
using System.Text;
|
||||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||||
|
using Microsoft.AspNetCore.HttpOverrides;
|
||||||
|
using Microsoft.AspNetCore.RateLimiting;
|
||||||
using Microsoft.IdentityModel.Tokens;
|
using Microsoft.IdentityModel.Tokens;
|
||||||
using TafsirQuran.Api.Auth;
|
using TafsirQuran.Api.Auth;
|
||||||
using TafsirQuran.Api.Endpoints;
|
using TafsirQuran.Api.Endpoints;
|
||||||
|
using TafsirQuran.Api.Security;
|
||||||
using TafsirQuran.Infrastructure;
|
using TafsirQuran.Infrastructure;
|
||||||
using TafsirQuran.Infrastructure.Persistence;
|
using TafsirQuran.Infrastructure.Persistence;
|
||||||
|
|
||||||
@@ -30,10 +34,84 @@ builder.Services
|
|||||||
});
|
});
|
||||||
builder.Services.AddAuthorization();
|
builder.Services.AddAuthorization();
|
||||||
|
|
||||||
|
builder.Services.Configure<ForwardedHeadersOptions>(options =>
|
||||||
|
{
|
||||||
|
options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
|
||||||
|
// Behind Arvan / ingress — trust forwarded headers from any proxy hop.
|
||||||
|
options.KnownNetworks.Clear();
|
||||||
|
options.KnownProxies.Clear();
|
||||||
|
});
|
||||||
|
|
||||||
|
var corsOrigins = builder.Configuration.GetSection("Cors:Origins").Get<string[]>()
|
||||||
|
?? ["https://quran.afrino.co"];
|
||||||
|
if (builder.Environment.IsDevelopment())
|
||||||
|
{
|
||||||
|
corsOrigins = corsOrigins
|
||||||
|
.Concat(["http://localhost:5081", "https://localhost:7150", "http://localhost:5173", "http://127.0.0.1:5081"])
|
||||||
|
.Distinct(StringComparer.OrdinalIgnoreCase)
|
||||||
|
.ToArray();
|
||||||
|
}
|
||||||
|
|
||||||
builder.Services.AddCors(options =>
|
builder.Services.AddCors(options =>
|
||||||
{
|
{
|
||||||
options.AddDefaultPolicy(policy =>
|
options.AddDefaultPolicy(policy =>
|
||||||
policy.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin());
|
policy.WithOrigins(corsOrigins)
|
||||||
|
.AllowAnyHeader()
|
||||||
|
.AllowAnyMethod());
|
||||||
|
});
|
||||||
|
|
||||||
|
builder.Services.AddRateLimiter(options =>
|
||||||
|
{
|
||||||
|
options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
|
||||||
|
options.OnRejected = async (context, token) =>
|
||||||
|
{
|
||||||
|
context.HttpContext.Response.Headers.RetryAfter = "60";
|
||||||
|
await context.HttpContext.Response.WriteAsJsonAsync(new { error = "rate_limited" }, token);
|
||||||
|
};
|
||||||
|
|
||||||
|
options.AddPolicy("auth", httpContext =>
|
||||||
|
RateLimitPartition.GetFixedWindowLimiter(
|
||||||
|
EndpointSecurity.GetClientIp(httpContext),
|
||||||
|
_ => new FixedWindowRateLimiterOptions
|
||||||
|
{
|
||||||
|
PermitLimit = 5,
|
||||||
|
Window = TimeSpan.FromMinutes(1),
|
||||||
|
QueueLimit = 0,
|
||||||
|
AutoReplenishment = true
|
||||||
|
}));
|
||||||
|
|
||||||
|
options.AddPolicy("write", httpContext =>
|
||||||
|
RateLimitPartition.GetFixedWindowLimiter(
|
||||||
|
EndpointSecurity.GetClientIp(httpContext),
|
||||||
|
_ => new FixedWindowRateLimiterOptions
|
||||||
|
{
|
||||||
|
PermitLimit = 30,
|
||||||
|
Window = TimeSpan.FromMinutes(1),
|
||||||
|
QueueLimit = 0,
|
||||||
|
AutoReplenishment = true
|
||||||
|
}));
|
||||||
|
|
||||||
|
options.AddPolicy("read", httpContext =>
|
||||||
|
RateLimitPartition.GetFixedWindowLimiter(
|
||||||
|
EndpointSecurity.GetClientIp(httpContext),
|
||||||
|
_ => new FixedWindowRateLimiterOptions
|
||||||
|
{
|
||||||
|
PermitLimit = 120,
|
||||||
|
Window = TimeSpan.FromMinutes(1),
|
||||||
|
QueueLimit = 2,
|
||||||
|
AutoReplenishment = true
|
||||||
|
}));
|
||||||
|
|
||||||
|
options.AddPolicy("global", httpContext =>
|
||||||
|
RateLimitPartition.GetFixedWindowLimiter(
|
||||||
|
EndpointSecurity.GetClientIp(httpContext),
|
||||||
|
_ => new FixedWindowRateLimiterOptions
|
||||||
|
{
|
||||||
|
PermitLimit = 180,
|
||||||
|
Window = TimeSpan.FromMinutes(1),
|
||||||
|
QueueLimit = 2,
|
||||||
|
AutoReplenishment = true
|
||||||
|
}));
|
||||||
});
|
});
|
||||||
|
|
||||||
builder.Services.AddOpenApi();
|
builder.Services.AddOpenApi();
|
||||||
@@ -46,7 +124,6 @@ var app = builder.Build();
|
|||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
// Fresh scope each attempt so a failed seed cannot leave tracked entities.
|
|
||||||
using var scope = app.Services.CreateScope();
|
using var scope = app.Services.CreateScope();
|
||||||
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
|
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
|
||||||
await DbSeeder.SeedAsync(db, audioRoot);
|
await DbSeeder.SeedAsync(db, audioRoot);
|
||||||
@@ -65,7 +142,20 @@ if (app.Environment.IsDevelopment())
|
|||||||
app.MapOpenApi();
|
app.MapOpenApi();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
app.UseForwardedHeaders();
|
||||||
|
app.Use(async (ctx, next) =>
|
||||||
|
{
|
||||||
|
ctx.Response.OnStarting(() =>
|
||||||
|
{
|
||||||
|
ctx.Response.Headers.TryAdd("X-Content-Type-Options", "nosniff");
|
||||||
|
ctx.Response.Headers.TryAdd("Referrer-Policy", "no-referrer");
|
||||||
|
ctx.Response.Headers.TryAdd("X-Frame-Options", "DENY");
|
||||||
|
return Task.CompletedTask;
|
||||||
|
});
|
||||||
|
await next();
|
||||||
|
});
|
||||||
app.UseCors();
|
app.UseCors();
|
||||||
|
app.UseRateLimiter();
|
||||||
app.UseDefaultFiles();
|
app.UseDefaultFiles();
|
||||||
app.UseStaticFiles();
|
app.UseStaticFiles();
|
||||||
app.UseAuthentication();
|
app.UseAuthentication();
|
||||||
@@ -77,6 +167,7 @@ app.MapFavoriteEndpoints();
|
|||||||
app.MapBookmarkEndpoints();
|
app.MapBookmarkEndpoints();
|
||||||
app.MapAuthEndpoints();
|
app.MapAuthEndpoints();
|
||||||
|
|
||||||
app.MapGet("/", () => Results.Ok(new { name = "TafsirQuran API", status = "ok" }));
|
app.MapGet("/", () => Results.Ok(new { name = "TafsirQuran API", status = "ok" }))
|
||||||
|
.RequireRateLimiting("global");
|
||||||
|
|
||||||
app.Run();
|
app.Run();
|
||||||
|
|||||||
@@ -0,0 +1,85 @@
|
|||||||
|
using System.Security.Claims;
|
||||||
|
using TafsirQuran.Api.Auth;
|
||||||
|
|
||||||
|
namespace TafsirQuran.Api.Security;
|
||||||
|
|
||||||
|
public static class EndpointSecurity
|
||||||
|
{
|
||||||
|
public const int MaxDeviceIdLength = 64;
|
||||||
|
public const int MaxNoteLength = 500;
|
||||||
|
public const int MinPasswordLength = 8;
|
||||||
|
|
||||||
|
public static string GetClientIp(HttpContext ctx)
|
||||||
|
{
|
||||||
|
var forwarded = ctx.Request.Headers["X-Forwarded-For"].FirstOrDefault();
|
||||||
|
if (!string.IsNullOrWhiteSpace(forwarded))
|
||||||
|
return forwarded.Split(',')[0].Trim();
|
||||||
|
return ctx.Connection.RemoteIpAddress?.ToString() ?? "unknown";
|
||||||
|
}
|
||||||
|
|
||||||
|
public static bool TryNormalizeDeviceId(string? deviceId, out string normalized, out IResult? error)
|
||||||
|
{
|
||||||
|
normalized = (deviceId ?? "").Trim();
|
||||||
|
if (normalized.Length is 0 or > MaxDeviceIdLength)
|
||||||
|
{
|
||||||
|
error = Results.BadRequest(new { error = "deviceId_required" });
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
error = null;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Authenticated: only UserId. Anonymous: only DeviceId (never OR across identities).
|
||||||
|
/// </summary>
|
||||||
|
public static bool TryResolveOwner(ClaimsPrincipal user, string? deviceId, out Guid? userId, out string? deviceKey, out IResult? error)
|
||||||
|
{
|
||||||
|
userId = JwtTokenService.GetUserId(user);
|
||||||
|
deviceKey = null;
|
||||||
|
error = null;
|
||||||
|
|
||||||
|
if (userId.HasValue)
|
||||||
|
return true;
|
||||||
|
|
||||||
|
if (!TryNormalizeDeviceId(deviceId, out var normalized, out error))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
deviceKey = normalized;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static bool IsValidSurahAyah(int surahNumber, int ayahNumber) =>
|
||||||
|
surahNumber is >= 1 and <= 114 && ayahNumber is >= 1 and <= 300;
|
||||||
|
|
||||||
|
public static bool IsValidSurah(int surahNumber) => surahNumber is >= 1 and <= 114;
|
||||||
|
|
||||||
|
public static string? NormalizeNote(string? note)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(note)) return null;
|
||||||
|
var trimmed = note.Trim();
|
||||||
|
return trimmed.Length <= MaxNoteLength ? trimmed : trimmed[..MaxNoteLength];
|
||||||
|
}
|
||||||
|
|
||||||
|
public static bool TryResolveUnderRoot(string rootDir, string relative, out string fullPath)
|
||||||
|
{
|
||||||
|
fullPath = "";
|
||||||
|
if (string.IsNullOrWhiteSpace(relative)) return false;
|
||||||
|
|
||||||
|
var root = Path.GetFullPath(rootDir);
|
||||||
|
if (!root.EndsWith(Path.DirectorySeparatorChar) && !root.EndsWith(Path.AltDirectorySeparatorChar))
|
||||||
|
root += Path.DirectorySeparatorChar;
|
||||||
|
|
||||||
|
var rel = relative.TrimStart('/', '\\').Replace('\\', Path.DirectorySeparatorChar);
|
||||||
|
var candidate = Path.GetFullPath(Path.Combine(root, rel));
|
||||||
|
|
||||||
|
if (!candidate.StartsWith(root, StringComparison.OrdinalIgnoreCase))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
if (!File.Exists(candidate))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
fullPath = candidate;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -9,6 +9,9 @@
|
|||||||
"Audience": "TafsirQuran",
|
"Audience": "TafsirQuran",
|
||||||
"ExpireMinutes": 43200
|
"ExpireMinutes": 43200
|
||||||
},
|
},
|
||||||
|
"Cors": {
|
||||||
|
"Origins": [ "https://quran.afrino.co" ]
|
||||||
|
},
|
||||||
"Logging": {
|
"Logging": {
|
||||||
"LogLevel": {
|
"LogLevel": {
|
||||||
"Default": "Information",
|
"Default": "Information",
|
||||||
|
|||||||
Reference in New Issue
Block a user