7 Commits

Author SHA1 Message Date
ceb1829eb9 fix: load images for randomly drawn quotes 2025-07-23 09:58:28 +02:00
a1086b94f1 feat: bring back categories endpoint with no pagination
now it requires authorization
2025-07-23 09:44:56 +02:00
ba162c34cc chore: nitpicky details 2025-07-22 14:08:37 +02:00
197918e526 fix: keep API path names consistent 2025-07-22 14:01:32 +02:00
ac80061437 feat: paginate categories 2025-07-22 13:28:27 +02:00
e7cebc32a4 feat: naive sanity check for image URLs 2025-07-22 13:09:13 +02:00
9e1e9c86d3 feat: sort the quotes from newest first by default 2025-07-22 12:43:35 +02:00
3 changed files with 111 additions and 20 deletions

View File

@@ -27,20 +27,72 @@ public class CategoryController : ControllerBase
guhf = GUHF;
}
// GET /api/v1/categories
// GET /api/v1/categories/page/1
/// <summary>
/// Get every category
/// Get a category page
/// </summary>
/// <remarks>
/// Can (and will) return an empty list if no categories are found in DB. <br/>
/// Has CORS set.
/// </remarks>
/// <param name="page_no">The page number</param>
/// <response code="200">Returned on valid request</response>
/// <response code="404">Returned when requested page is invalid (page_no &lt;= 0)</response>
[HttpGet("page/{page_no}")]
[EnableCors]
[ProducesResponseType(typeof(List<CategoryShortDTO>), 200)]
[ProducesResponseType(typeof(ErrorDTO), 404)]
public async Task<IActionResult> GetCategoryPage(int page_no = 1)
{
// The following seems to be a bad idea, so I leave it as is. ~eee4
//
// int totalCategories = await _db.Categories.CountAsync();
//
// if (totalCategories <= 0)
// {
// return NoContent(new ErrorDTO { Status = "error", Error_msg = "No categories to list" });
// }
const int PageSize = 10;
if (page_no <= 0)
{
return NotFound(new ErrorDTO { Status = "error", Error_msg = "Numer strony musi być większy niż 0" });
}
// Get all the categories
//List<Category> categories = await _db.Categories
// .ToListAsync();
List<Category> categories = await _db.Categories
.Skip((page_no - 1) * PageSize)
.Take(PageSize)
.ToListAsync();
// Convert them to a list of DTO
List<CategoryShortDTO> result = categories
.Select(c => c.ToCategoryShortDTO())
.ToList();
// Return to user
return Ok(result);
}
// GET /api/v1/categories
/// <summary>
/// [AUTHED] Get every category
/// </summary>
/// <remarks>
/// Can (and will) return an empty list if no categories are found in DB. <br/>
/// Unlike GET /api/v1/categories/page/..., requires authorization with a JWT.
/// Has CORS set.
/// </remarks>
/// <response code="200">Returned on valid request</response>
// /// <response code="404">Returned when there are no categories to list</response>
[HttpGet]
[Authorize]
[EnableCors]
[ProducesResponseType(typeof(CategoryShortDTO), 200)]
// [ProducesResponseType(typeof(ErrorDTO), 404)]
[ProducesResponseType(typeof(List<CategoryShortDTO>), 200)]
public async Task<IActionResult> GetQuotePage()
{
// The following seems to be a bad idea, so I leave it as is. ~eee4
@@ -66,6 +118,7 @@ public class CategoryController : ControllerBase
}
// POST /api/v1/categories
/// <summary>
/// [AUTHED] Create a new category

View File

@@ -1,14 +1,11 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Authorization.Infrastructure;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Update.Internal;
using QuotifyBE.Data;
using QuotifyBE.DTOs;
using QuotifyBE.Entities;
using QuotifyBE.Mapping;
using System.Reflection.Metadata.Ecma335;
using System.Security.Claims;
namespace QuotifyBE.Controllers;
@@ -41,6 +38,7 @@ public class QuotesController : ControllerBase
/// Has CORS set, unlike e.g. GET /api/v1/quote/{id} or GET /api/v1/quote/random.
/// </remarks>
/// <param name="page_no">The page number</param>
/// <param name="sort">How to sort the results (desc/asc)</param>
/// <param name="category_id">(Optional) Standalone category id or comma separated ids (e.g. "1" or "1,2,3")</param>
/// <returns>A page (&lt;= 10 quotes)</returns>
/// <response code="200">Returned on valid request</response>
@@ -49,7 +47,7 @@ public class QuotesController : ControllerBase
[EnableCors]
[ProducesResponseType(typeof(List<QuoteShortDTO>), 200)]
[ProducesResponseType(typeof(ErrorDTO), 404)]
public async Task<IActionResult> GetQuotePage(int page_no, [FromQuery] string? category_id = null)
public async Task<IActionResult> GetQuotePage(int page_no = 1, string? sort = "desc", [FromQuery] string? category_id = null)
{
var totalQuotes = await _db.Quotes.CountAsync();
const int PageSize = 10;
@@ -80,8 +78,15 @@ public class QuotesController : ControllerBase
.Include(q => q.QuoteCategories!)
.ThenInclude(qc => qc.Category)
.Include(q => q.User)
.Include(q => q.Image)
.OrderBy(q => q.Id);
.Include(q => q.Image);
// Sort the results in ascending/descending order by id
IOrderedQueryable<Quote>? orderedQuery;
if (sort != null && sort.Equals("asc"))
orderedQuery = baseQuery.OrderBy(q => q.Id);
else
// Sort in descending order by default
orderedQuery = baseQuery.OrderByDescending(q => q.Id);
// Botched solution
List<Quote> pageQuotes;
@@ -89,7 +94,7 @@ public class QuotesController : ControllerBase
// Filtrowanie przed pobraniem strony
if (categories != null)
{
pageQuotes = await baseQuery
pageQuotes = await orderedQuery
.Where(q => q.QuoteCategories!
.Any(qc => categories.Contains(qc.CategoryId))
//.Any(qc => qc.CategoryId == category_id.Value)
@@ -100,7 +105,7 @@ public class QuotesController : ControllerBase
}
else
{
pageQuotes = await baseQuery
pageQuotes = await orderedQuery
.Skip((page_no - 1) * PageSize)
.Take(PageSize)
.ToListAsync();
@@ -150,32 +155,50 @@ public class QuotesController : ControllerBase
/// [AUTHED] Add a new quote
/// </summary>
/// <returns>Newly created quote's id</returns>
/// <remarks>
/// <b>Note</b>:
/// User-provided image URLs are validated by checking
/// if they start with "https://", "http://" or "/".
/// This is rather a naive solution.
/// </remarks>
/// <param name="request">Form data containing required quote information</param>
/// <response code="201">Returned on valid request</response>
/// <response code="400">Returned when any of the categories does not exist</response>
/// <response code="403">Returned when user's id does not match the creator's id</response>
/// <response code="406">Returned when image url is invalid (does not start with "https://", "http://", or "/")</response>
[HttpPost("new")]
[Authorize]
[EnableCors]
[ProducesResponseType(201)]
[ProducesResponseType(typeof(ErrorDTO), 400)]
[ProducesResponseType(typeof(ErrorDTO), 403)]
[ProducesResponseType(typeof(ErrorDTO), 406)]
public async Task<IActionResult> CreateQuote([FromBody] CreateQuoteDTO request)
{
// Get user ID from claims
var userIdClaim = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
if (userIdClaim == null || !int.TryParse(userIdClaim, out int userId))
// https://stackoverflow.com/a/47708867
return StatusCode(403, new ErrorDTO { Status = "error", Error_msg = "Invalid user ID" });
// Find or create image
// Try to find the image inside the DB
Image? image = null;
if (!string.IsNullOrEmpty(request.ImageUrl))
{
image = await _db.Images.FirstOrDefaultAsync(i => i.Url == request.ImageUrl);
// Failed? Just insert it yourself
if (image == null)
{
// Simple (naive) sanity check for image URLs
if ( !request.ImageUrl.StartsWith("http://")
&& !request.ImageUrl.StartsWith("https://")
&& !request.ImageUrl.StartsWith("/"))
return StatusCode(406, new ErrorDTO {
Status = "error",
Error_msg = "Image URLs should point to http/https url or a local resource"
});
image = new Image { Url = request.ImageUrl };
_db.Images.Add(image);
await _db.SaveChangesAsync();
@@ -232,7 +255,8 @@ public class QuotesController : ControllerBase
{
IQueryable<Quote> query = _db.Quotes
.Include(q => q.QuoteCategories!)
.ThenInclude(qc => qc.Category);
.ThenInclude(qc => qc.Category)
.Include(q => q.Image);
if (category_id.HasValue)
{
@@ -255,8 +279,6 @@ public class QuotesController : ControllerBase
var skip = random.Next(0, totalQuotes);
var quote = await query
.Include(q => q.QuoteCategories!)
.ThenInclude(qc => qc.Category)
.Skip(skip)
.Take(1)
.FirstOrDefaultAsync();
@@ -339,13 +361,19 @@ public class QuotesController : ControllerBase
/// While "categories = null" will not alter the quote's categories,
/// "categories = []" will (and in turn, empty each and every present category)!<br/>
/// Be careful when handling user-provided categories!
/// <br/><br/>
/// <b>Note</b>:
/// User-provided image URLs are validated by checking
/// if they start with "https://", "http://" or "/".
/// This is rather a naive solution.
/// </remarks>
/// <returns>Newly modified quote as a DTO</returns>
/// <param name="id">Quote to be modified</param>
/// <param name="updatedQuote">Updated quote form data</param>
/// <param name="updatedQuote">Updated quote form data. Id is ignored.</param>
/// <response code="204">Returned on valid request</response>
/// <response code="400">Returned when request text or author is empty (or whitespace)</response>
/// <response code="404">Returned when no such quote exists</response>
/// <response code="406">Returned when image url is invalid (does not start with "https://", "http://", or "/")</response>
[HttpPatch("{id}")]
[Authorize]
[EnableCors]
@@ -377,9 +405,19 @@ public class QuotesController : ControllerBase
if (!string.IsNullOrEmpty(updatedQuote.ImageUrl))
{
image = await _db.Images.FirstOrDefaultAsync(i => i.Url == updatedQuote.ImageUrl);
// Failed? Just insert it yourself
if (image == null)
{
// Simple (naive) sanity check for image URLs
if ( !updatedQuote.ImageUrl.StartsWith("http://")
&& !updatedQuote.ImageUrl.StartsWith("https://")
&& !updatedQuote.ImageUrl.StartsWith("/"))
return StatusCode(406, new ErrorDTO {
Status = "error",
Error_msg = "Image URLs should point to http/https url or a local resource"
});
image = new Image { Url = updatedQuote.ImageUrl };
_db.Images.Add(image);
await _db.SaveChangesAsync();

View File

@@ -10,12 +10,12 @@ namespace QuotifyBE.Controllers;
[EnableCors]
[Route("api/v1/stats")]
[Produces("application/json")]
public class StatisticController : ControllerBase
public class StatisticsController : ControllerBase
{
private readonly ApplicationDbContext _db;
public StatisticController( ApplicationDbContext db)
public StatisticsController( ApplicationDbContext db)
{
_db = db;
}