29 Commits

Author SHA1 Message Date
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
10d2a35e61 Merge branch 'main' into Tydz3,-losowanie-z-kategoria 2025-07-22 12:06:44 +02:00
ca78f43f73 chore: documentation for category modification 2025-07-22 12:06:22 +02:00
3a82e4291e edycja kategorii 2025-07-22 11:45:48 +02:00
341755d77e feat: basic stats endpoint 2025-07-22 11:39:40 +02:00
468d502827 fix: disable clock skew
reference:
https://stackoverflow.com/a/46231102
https://stackoverflow.com/a/47155318
2025-07-22 11:00:10 +02:00
0ec7bdf2fe chore: adjust line endings, show git info 2025-07-22 10:59:12 +02:00
b292586764 fix: handle requests with a non-integer list for category_id 2025-07-21 14:29:26 +02:00
779772e60c Merge remote-tracking branch 'origin/Tydz3,-losowanie-z-kategoria' into Tydz3,-losowanie-z-kategoria 2025-07-21 14:21:06 +02:00
b96c780533 chore: documentation and formatting for random quote and deleting categories 2025-07-21 13:27:11 +02:00
f773f886b4 paginacja z kategoriami 2025-07-21 13:25:22 +02:00
d502e9d120 usuwanie kategorii (do przetestowania dla cytatow z kategoriami) 2025-07-21 12:40:13 +02:00
a8a82df6ed losowanie z kategoria 2025-07-21 11:49:01 +02:00
d09d8f85e3 fix: deleting quote produces response code 200, not 204 2025-07-21 11:38:59 +02:00
05e6b9bc86 feat: ensure the number of draws is present in the db 2025-07-21 11:16:46 +02:00
db6f57830a feat: add db model for statistics 2025-07-21 11:16:26 +02:00
ddfab4dac1 fix: cors allows any method for known origins 2025-07-21 11:15:05 +02:00
d99755e7af fix: pass DTO from API, and pass objects instead of raw ints
fixes cyclic import when passing categories
2025-07-21 10:57:38 +02:00
1f9c04e2fc feat: return user's role name inside UserInfoDTO 2025-07-21 09:47:31 +02:00
d53b85fe9e chore: tiny documentation changes 2025-07-18 13:38:55 +02:00
644e9de0bd feat: endpoint for getting user data 2025-07-18 13:05:00 +02:00
ee7e7762e0 chore: update documentation for new quotes endpoints 2025-07-18 12:54:28 +02:00
7d20e4d4f9 edycja naprawiona 2025-07-18 12:12:22 +02:00
908a56665d Merge branch 'enhanced_categories' 2025-07-18 11:14:22 +02:00
76258bc0eb usuwanie 2025-07-18 11:12:55 +02:00
17 changed files with 902 additions and 116 deletions

View File

@@ -1,5 +1,5 @@
[*]
end_of_line = crlf
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true

View File

@@ -3,7 +3,6 @@ using Microsoft.AspNetCore.Mvc;
using QuotifyBE.Data;
using QuotifyBE.Entities;
using QuotifyBE.DTOs;
using System.Threading.Tasks;
using QuotifyBE.Mapping;
using Microsoft.AspNetCore.Cors;
@@ -71,7 +70,7 @@ public class AuthController : ControllerBase
{
// All set - generate the token and return it
var token = guhf.GenerateJwtToken(user);
SuccessfulLoginDTO response = user.ToSuccessfulLoginDTO(token);
SuccessfulLoginDTO response = user.ToSuccessfulLoginDTO(token, guhf.UserRoleAsStr(user));
return Ok(response);
} else return Unauthorized(new {status = "error", error_msg = "Unknown pair of email and password"});
@@ -83,8 +82,11 @@ public class AuthController : ControllerBase
/// </summary>
/// <remarks>
/// Dummy, authed endpoint used to test JWTs.
/// <br/><br/>
/// <b>Important!</b>
/// Authed endpoints expect Authorization header, e.g.:
/// Authorization: bearer {jwt}</remarks>
/// Authorization: bearer {jwt}
/// </remarks>
/// <returns>Dummy json</returns>
/// <response code="200">Returned on request with valid credentials</response>
/// <response code="401">Returned on request with invalid JWT</response>
@@ -104,8 +106,7 @@ public class AuthController : ControllerBase
/// </summary>
/// <remarks>
/// Authed endpoint used to check human-readable user role.
/// Authed endpoints expect Authorization header, e.g.:
/// Authorization: bearer {jwt}</remarks>
/// </remarks>
/// <returns>Json containing single field "role"</returns>
/// <response code="200">Returned on request with valid credentials</response>
/// <response code="400">Returned on request with JWT whose user could not be found (sanity check)</response>
@@ -125,4 +126,31 @@ public class AuthController : ControllerBase
return Ok(new { Role = guhf.UserRoleAsStr(u) });
}
// GET /api/v1/auth/me
/// <summary>
/// [AUTHED] Get user info
/// </summary>
/// <remarks>
/// Authed endpoint used to get info about the user.
/// </remarks>
/// <returns>Json containing user info DTO</returns>
/// <response code="200">Returned on request with valid credentials</response>
/// <response code="400">Returned on request with JWT whose user could not be found (sanity check)</response>
[HttpGet("me")]
[Authorize]
[EnableCors]
[ProducesResponseType(typeof(UserInfoDTO), 200)]
[ProducesResponseType(typeof(ErrorDTO), 400)]
public IActionResult GetUserData()
{
// Get user token from Authorization header
User? u = guhf.GetUserFromToken(Request.Headers.Authorization!);
if (u == null) // sanity check
return BadRequest(new ErrorDTO { Status = "error", Error_msg = "User not found" });
// Return user data as a DTO
return Ok(u.ToUserInfoDTO(guhf.UserRoleAsStr(u)));
}
}

View File

@@ -29,19 +29,20 @@ public class CategoryController : ControllerBase
// GET /api/v1/categories
/// <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 there are no categories to list</response>
[HttpGet]
/// <response code="404">Returned when requested page is invalid (page_no &lt;= 0)</response>
[HttpGet("page/{page_no}")]
[EnableCors]
[ProducesResponseType(typeof(CategoryShortDTO), 200)]
// [ProducesResponseType(typeof(ErrorDTO), 404)]
public async Task<IActionResult> GetQuotePage()
[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
//
@@ -49,12 +50,23 @@ public class CategoryController : ControllerBase
//
// if (totalCategories <= 0)
// {
// return NotFound(new ErrorDTO { Status = "error", Error_msg = "No categories to list" });
// 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
.ToListAsync();
.Skip((page_no - 1) * PageSize)
.Take(PageSize)
.ToListAsync();
// Convert them to a list of DTO
List<CategoryShortDTO> result = categories
@@ -71,8 +83,10 @@ public class CategoryController : ControllerBase
/// [AUTHED] Create a new category
/// </summary>
/// <remarks>
/// Allows authorized users to create categories. <br/>
/// Important! Category names are case insensitive. <br/>
/// Allows authorized users to create categories.
/// <br/><br/>
/// <b>Important!</b>
/// Category names are case insensitive. <br/>
/// Has CORS set.
/// </remarks>
/// <response code="200">Returned on valid request</response>
@@ -108,4 +122,94 @@ public class CategoryController : ControllerBase
}
// DELETE /api/v1/categories
/// <summary>
/// [AUTHED] Delete a category
/// </summary>
/// <remarks>
/// Allows authorized users to delete categories.
/// <br/><br/>
/// Has CORS set.
/// </remarks>
/// <param name="id">Id of the category which shall be deleted</param>
/// <response code="200">Returned on valid request</response>
/// <response code="404">Returned when no such category exists</response>
[HttpDelete("{id}")]
[Authorize]
[EnableCors]
[ProducesResponseType(200)]
[ProducesResponseType(typeof(ErrorDTO), 404)]
public async Task<IActionResult> DeleteCategory(int id)
{
// (Attempt to) find the category
Category? cat = await _db.Categories
.FirstOrDefaultAsync(c => c.Id == id);
// Failed?
if (cat == null)
return NotFound(new { status = "error", error_msg = "Category not found" });
// Find all the QuoteId <-> CategoryId pairs for provided id
List<QuoteCategory> quoteLinks = await _db.QuoteCategories
.Where(qc => qc.CategoryId == id)
.ToListAsync();
// For each of the dependent quotes
foreach (var link in quoteLinks) {
// Remove all the associative pairs
_db.QuoteCategories.Remove(link);
}
// Finally, remove the category
_db.Categories.Remove(cat);
await _db.SaveChangesAsync();
// Return ok
return Ok(new { Status = "ok" });
}
// PATCH /api/v1/categories/1
/// <summary>
/// [AUTHED] Modify an existing category
/// </summary>
/// <remarks>
/// Allows authorized users to modify categories.
/// <br/><br/>
/// Has CORS set.
/// </remarks>
/// <param name="id">Id of the category which shall be modified</param>
/// <param name="updatedCategory">DTO with new name and description. Id and creation date are ignored.</param>
/// <response code="200">Returned on valid request</response>
/// <response code="400">Returned when category name is empty or null</response>
/// <response code="404">Returned when no such category exists</response>
[HttpPatch("{id}")]
[Authorize]
[EnableCors]
[ProducesResponseType(typeof(CategoryShortDTO), 200)]
[ProducesResponseType(typeof(ErrorDTO), 400)]
[ProducesResponseType(typeof(ErrorDTO), 404)]
public async Task<IActionResult> EditCategory(int id, [FromBody] CategoryShortDTO updatedCategory)
{
// Find the category to modify
Category? cat = await _db.Categories.FirstOrDefaultAsync(c => c.Id == id);
// Failed?
if (cat == null)
return NotFound(new { status = "error", error_msg = "Category not found" });
// Otherwise, ensure the category name is not empty or null
if (string.IsNullOrWhiteSpace(updatedCategory.Name))
return BadRequest(new ErrorDTO { Status = "error", Error_msg = "Category name cannot be empty." });
// Update the fields
cat.Name = updatedCategory.Name;
cat.Description = updatedCategory.Description;
// Note the user cannot modify the createdAt field,
// and we do not store last modification date.
await _db.SaveChangesAsync();
// Return the modified category to user
return Ok(cat.ToCategoryShortDTO());
}
}

View File

@@ -32,53 +32,106 @@ public class QuotesController : ControllerBase
/// </summary>
/// <remarks>
/// A page of quotes consists of 10 quotes or less.
/// If a page does not contain any quotes, 404 is returned.
/// Important! Has CORS set, unlike e.g. GET /api/v1/quote/{id} or GET /api/v1/quote/random.
/// If a page does not contain any quotes, an empty list is returned.
/// <br/><br/>
/// <b>Important!</b>
/// 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>
/// <returns>A page (10 quotes)</returns>
/// <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>
/// <response code="404">Returned when requested page is invalid</response>
/// <response code="404">Returned when requested page is invalid (page_no &lt;= 0)</response>
[HttpGet("page/{page_no}")]
[EnableCors]
[ProducesResponseType(typeof(List<QuoteShortDTO>), 200)]
[ProducesResponseType(typeof(ErrorDTO), 404)]
public async Task<IActionResult> GetQuotePage(int page_no)
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;
List<int>? categories;
try
{
categories = category_id?
.Split(",")
.Select(Int32.Parse)
.ToList();
} catch
{
// Try to catch badly formatted requests
return BadRequest(new ErrorDTO {
Status = "error",
Error_msg = "Category_id can be either an integer, or comma separated integers"
});
}
if (page_no <= 0)
{
return NotFound(new ErrorDTO { Status = "error", Error_msg = "Numer strony musi być większy niż 0" });
}
var quotes = await _db.Quotes
.Include(q => q.QuoteCategories)
.ThenInclude(qc => qc.Category)
.Include(q => q.User)
.Include(q => q.Image)
.OrderBy(q => q.Id)
.Skip((page_no - 1) * PageSize)
.Take(PageSize)
.ToListAsync();
var result = quotes
.Select(q => q.ToQuoteShortDTO())
.ToList();
// Paginacja bez filtra
var baseQuery = _db.Quotes
.Include(q => q.QuoteCategories!)
.ThenInclude(qc => qc.Category)
.Include(q => q.User)
.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;
// Filtrowanie przed pobraniem strony
if (categories != null)
{
pageQuotes = await orderedQuery
.Where(q => q.QuoteCategories!
.Any(qc => categories.Contains(qc.CategoryId))
//.Any(qc => qc.CategoryId == category_id.Value)
)
.Skip((page_no - 1) * PageSize)
.Take(PageSize)
.ToListAsync();
}
else
{
pageQuotes = await orderedQuery
.Skip((page_no - 1) * PageSize)
.Take(PageSize)
.ToListAsync();
}
var result = pageQuotes
.Select(q => q.ToQuoteShortDTO())
.ToList();
return Ok(result);
}
// GET /api/v1/quotes/{id}
/// <summary>
/// Get specified quote summary
/// [AUTHED] Get specified quote summary
/// </summary>
/// <remarks>
/// As per project's guidelines, requires a JWT.
/// </remarks>
/// <param name="id">The quote id in question</param>
/// <returns>A quote: id, quote content and author, imageUrl and categories if successful, otherwise: error message</returns>
/// <response code="200">Returned on valid request</response>
/// <response code="404">Returned when quote id is invalid or simply doesn't exist</response>
[HttpGet("{id}")]
[Authorize]
[ProducesResponseType(typeof(QuoteShortDTO), 200)]
[ProducesResponseType(typeof(ErrorDTO), 404)]
public async Task<IActionResult> GetQuoteById(int id)
@@ -102,16 +155,24 @@ 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
@@ -120,13 +181,24 @@ public class QuotesController : ControllerBase
// 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();
@@ -148,13 +220,13 @@ public class QuotesController : ControllerBase
// Attach categories
foreach (var categoryId in request.CategoryIds ?? [])
{
var categoryExists = await _db.Categories.AnyAsync(c => c.Id == categoryId);
if (!categoryExists)
return BadRequest(new ErrorDTO { Status = "error", Error_msg = $"Category ID {categoryId} not found"});
Category? category = await _db.Categories.FirstOrDefaultAsync(c => c.Id == categoryId);
if (category == null)
return BadRequest(new ErrorDTO { Status = "error", Error_msg = $"Category ID {categoryId} not found" });
quote.QuoteCategories.Add(new QuoteCategory
{
CategoryId = categoryId,
Category = category,
Quote = quote
});
}
@@ -162,30 +234,50 @@ public class QuotesController : ControllerBase
_db.Quotes.Add(quote);
await _db.SaveChangesAsync();
return CreatedAtAction(nameof(GetQuoteById), new { id = quote.Id }, quote);
return CreatedAtAction(nameof(GetQuoteById), new { id = quote.Id }, quote.ToQuoteShortDTO());
}
// GET /api/v1/quotes/random
/// <summary>
/// Get a random quote summary
/// Draw a random quote
/// </summary>
/// <returns>A quote: id, quote content and author, imageUrl and categories if successful, otherwise: error message</returns>
/// <param name="category_id">(Optional) category id to draw from</param>
/// <response code="200">Returned on valid request</response>
/// <response code="404">Returned when no quotes exist</response>
/// <response code="204">Returned when no quotes exist matching provided criteria</response>
/// <response code="404">Returned when no quotes exist (in the DB)</response>
[HttpGet("random")]
[AllowAnonymous]
[ProducesResponseType(typeof(QuoteShortDTO), 200)]
[ProducesResponseType(204)]
[ProducesResponseType(typeof(ErrorDTO), 404)]
public async Task<IActionResult> GetRandomQuote()
public async Task<IActionResult> GetRandomQuote([FromQuery] int? category_id = null)
{
var totalQuotes = await _db.Quotes.CountAsync();
IQueryable<Quote> query = _db.Quotes
.Include(q => q.QuoteCategories!)
.ThenInclude(qc => qc.Category);
if (category_id.HasValue)
{
query = query
.Where(q => q.QuoteCategories!
.Any(qc => qc.CategoryId == category_id.Value)
);
}
var totalQuotes = await query.CountAsync();
if (totalQuotes == 0)
return NotFound(new ErrorDTO { Status = "error", Error_msg = "No quotes to choose from" });
{
if (category_id.HasValue)
return NoContent(); // Brak cytatów w wybranej kategorii
else
return NotFound(new ErrorDTO { Status = "error", Error_msg = "No quotes to choose from" });
}
var random = new Random();
var skip = random.Next(0, totalQuotes);
var quote = await _db.Quotes
var quote = await query
.Include(q => q.QuoteCategories!)
.ThenInclude(qc => qc.Category)
.Skip(skip)
@@ -193,28 +285,201 @@ public class QuotesController : ControllerBase
.FirstOrDefaultAsync();
if (quote == null)
return NotFound(new ErrorDTO { Status = "error", Error_msg = "Unknown error - couldn't get quote"});
return NotFound(new ErrorDTO { Status = "error", Error_msg = "Unknown error - couldn't get quote" });
Image? image = null;
if (quote.ImageId != 0)
{
image = await _db.Images.FirstOrDefaultAsync(i => i.Id == quote.ImageId);
}
// After getting and checking the quote, update the number of draws
Statistic s = await _db.Statistics
.FirstAsync(s => s.Label == "number_of_draws");
s.IValue += 1;
await _db.SaveChangesAsync();
var dto = new QuoteShortDTO
{
Id = quote.Id,
Text = quote.Text,
Author = quote.Author,
ImageUrl = image?.Url,
Categories = quote.QuoteCategories?
.Select(qc => qc.Category?.Name ?? "")
.Where(name => !string.IsNullOrEmpty(name))
.ToList() ?? new List<string>()
};
return Ok(dto);
return Ok(quote.ToQuoteShortDTO());
}
// DELETE /api/v1/quotes/{id}
/// <summary>
/// [AUTHED] Delete a quote
/// </summary>
/// <remarks>
/// Deletes a quote, granted it exists. <br/>
/// <br/>
/// <i>
/// Is this the best practice? Marking the quote as hidden is also an option.
/// </i> ~eee4
/// </remarks>
/// <returns>Json with status</returns>
/// <param name="id">Quote id which will be deleted</param>
/// <response code="200">Returned on valid request</response>
/// <response code="404">Returned when no such quote exists</response>
[HttpDelete("{id}")]
[Authorize]
[EnableCors]
[ProducesResponseType(200)]
[ProducesResponseType(typeof(ErrorDTO), 404)]
public async Task<IActionResult> DeleteQuote(int id)
{
// (Attempt to) find the quote
Quote? quote = await _db.Quotes
.FirstOrDefaultAsync(q => q.Id == id);
// Failed?
if (quote == null)
return NotFound(new { status = "error", error_msg = "Quote not found" });
// If succeded, remove the quote
_db.Quotes.Remove(quote);
await _db.SaveChangesAsync();
// ====================================================================== //
// Important! //
// Is this the best we can do? Won't marking the quote as "hidden" //
// be better than explicitly deleting it? ~eee4 //
// ====================================================================== //
// Return ok
return Ok(new { Status = "ok" });
}
// PATCH /api/v1/quotes/{id}
/// <summary>
/// [AUTHED] Modify an existing quote
/// </summary>
/// <remarks>
/// Modifies an existing quote.
/// <br/><br/>
/// <b>Warning!</b>
/// We don't check the user id which created the quote.
/// In case of single-user instances, this should not be a problem.
/// This might become one, if we want users with non-admin roles;
/// that would need some proper ACL checks here (with the help of GUHF).
/// <br/><br/>
/// <b>Important!</b>
/// Image handling works the same as with creating new quote.
/// This means that images not present in the DB will be added automatically.
/// <br/><br/>
/// <b>Important!</b>
/// "categories = null" is not the same as "categories = []"!
/// 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. 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]
[ProducesResponseType(typeof(QuoteShortDTO), 200)]
[ProducesResponseType(typeof(ErrorDTO), 400)]
[ProducesResponseType(typeof(ErrorDTO), 404)]
public async Task<IActionResult> EditQuote(int id, [FromBody] QuoteShortDTO updatedQuote)
{
// Try to find the quote in question
Quote? quote = await _db.Quotes
.Include(q => q.QuoteCategories)
.FirstOrDefaultAsync(q => q.Id == id);
// Failed?
if (quote == null)
return NotFound(new { status = "error", error_msg = "Quote not found" });
// Is quote contents or author empty?
if (string.IsNullOrWhiteSpace(updatedQuote.Text) || string.IsNullOrWhiteSpace(updatedQuote.Author))
return BadRequest(new ErrorDTO { Status = "error", Error_msg = "Text and author are required." });
// Alter the quote's content
quote.Text = updatedQuote.Text;
quote.Author = updatedQuote.Author;
quote.LastUpdatedAt = DateTime.UtcNow;
// Try to find the image inside the DB
Image? image = null;
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();
}
}
quote.Image = image;
// Don't touch categories if they are explicitly null
if (updatedQuote.Categories == null) { }
// If they aren't
else if (updatedQuote.Categories.Any())
{
// Get all the categories associated with a quote from DB
List<Category> categoriesFromDb = await _db.Categories
.Where(c => updatedQuote.Categories.Contains(c.Name))
.ToListAsync();
// Determine which ones are already present, and which to add
IEnumerable<string> existingNames = categoriesFromDb
.Select(c => c.Name);
List<string> newNames = updatedQuote.Categories
.Except(existingNames)
.ToList();
// For all the categories not present
foreach (var name in newNames)
{
// Add them to the DB
var newCat = new Category
{
Name = name,
Description = string.Empty,
CreatedAt = DateTime.UtcNow
};
_db.Categories.Add(newCat);
categoriesFromDb.Add(newCat);
}
// If any categories were added, save changes
if (newNames.Any())
await _db.SaveChangesAsync();
// Assign all the new categories to the quote
quote.QuoteCategories = categoriesFromDb
.Select(cat => new QuoteCategory
{
CategoryId = cat.Id,
QuoteId = quote.Id
})
.ToList();
}
else
{
// No categories (empty list) inside DTO?
// Clear them all!
quote.QuoteCategories.Clear();
}
// Save changes, return new quote as a DTO
await _db.SaveChangesAsync();
return Ok(quote.ToQuoteShortDTO());
}
}

View File

@@ -1,41 +1,60 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using QuotifyBE.Data;
using QuotifyBE.DTOs;
using QuotifyBE.Entities;
using QuotifyBE.Mapping;
using System.Security.Claims;
using Microsoft.EntityFrameworkCore;
namespace QuotifyBE.Controllers
{
public class Seed : Controller
{
private readonly ApplicationDbContext _db;
private readonly GeneralUseHelpers guhf;
public Seed(ApplicationDbContext db, GeneralUseHelpers GUHF)
{
_db = db;
guhf = GUHF;
}
public async Task SeedAsync()
{
var AccountNum = await _db.Users.CountAsync();
if (AccountNum == 0)
{
var Admin = new User
{
Name="admin",
Email = "admin@mail.com",
// hashed twice, once by frontend, and second time by backend
PasswordHash = guhf.HashWithSHA512(guhf.HashWithSHA512("admin")),
Role = 0 // role 0 - greatest power, admin, role 0 > role 1
};
_db.Users.Add(Admin);
await _db.SaveChangesAsync();
}
}
}
}
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using QuotifyBE.Data;
using QuotifyBE.DTOs;
using QuotifyBE.Entities;
using QuotifyBE.Mapping;
using System.Security.Claims;
using Microsoft.EntityFrameworkCore;
namespace QuotifyBE.Controllers
{
public class Seed : Controller
{
private readonly ApplicationDbContext _db;
private readonly GeneralUseHelpers guhf;
public Seed(ApplicationDbContext db, GeneralUseHelpers GUHF)
{
_db = db;
guhf = GUHF;
}
public async Task SeedAsync()
{
Console.WriteLine($"You're running QuotifyBE, commit {ThisAssembly.Git.Commit} of branch {ThisAssembly.Git.Branch} ({ThisAssembly.Git.CommitDate})\n");
// Create a user account if no exist
var AccountNum = await _db.Users.CountAsync();
if (AccountNum == 0)
{
var Admin = new User
{
Name="admin",
Email = "admin@mail.com",
// hashed twice, once by frontend, and second time by backend
PasswordHash = guhf.HashWithSHA512(guhf.HashWithSHA512("admin")),
Role = 0 // role 0 - greatest power, admin, role 0 > role 1
};
_db.Users.Add(Admin);
await _db.SaveChangesAsync();
Console.WriteLine("[QuotifyBE] Administrator user account added!\nDefault credentials are: admin@mail.com, password: admin");
}
// Create sitewide statistic - number of draws
Statistic? numOfDraws = await _db.Statistics
.FirstOrDefaultAsync(s => s.Label == "number_of_draws");
if (numOfDraws == null)
{
Statistic newRow = new Statistic
{
Label = "number_of_draws",
IValue = 0
};
_db.Statistics.Add(newRow);
await _db.SaveChangesAsync();
Console.WriteLine("[QuotifyBE] Sitewide statistic for number of draws added!");
}
}
}
}

View File

@@ -0,0 +1,59 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using QuotifyBE.Data;
using Microsoft.AspNetCore.Cors;
namespace QuotifyBE.Controllers;
[ApiController]
[EnableCors]
[Route("api/v1/stats")]
[Produces("application/json")]
public class StatisticsController : ControllerBase
{
private readonly ApplicationDbContext _db;
public StatisticsController( ApplicationDbContext db)
{
_db = db;
}
// GET /api/v1/stats
/// <summary>
/// Return server statistics
/// </summary>
/// <remarks>
/// Provides, info on last commit # and date, branch name,
/// sitewide stats (number of draws) and available endpoints
/// (machine-friendly json).
/// <br/>
/// Has CORS set.
/// </remarks>
/// <returns>Dummy json</returns>
// /// <response code="200">Returned on request with valid credentials</response>
// /// <response code="401">Returned on request with invalid JWT</response>
[HttpGet]
[EnableCors]
[ProducesResponseType(200)]
// [ProducesResponseType(401)]
public IActionResult GetStats()
{
return Ok(new
{
version = new
{
lastCommit = ThisAssembly.Git.Commit,
lastUpdatedAt = ThisAssembly.Git.CommitDate,
currentBranch = ThisAssembly.Git.Branch
},
endpointDiscovery = "/swagger/v1/swagger.json",
sitewideStats = new
{
numberOfDraws = _db.Statistics.First(s => s.Label == "number_of_draws").IValue
}
});
}
}

View File

@@ -6,7 +6,7 @@ public record class QuoteShortDTO
public string Text { get; set; } = string.Empty;
public string Author { get; set; } = string.Empty;
public string? ImageUrl { get; set; }
public List<string> Categories { get; set; } = new();
public List<string>? Categories { get; set; } = new();
};

View File

@@ -6,5 +6,6 @@ public record class UserInfoDTO
required public string Name { get; set; }
required public string Email { get; set; }
public int Role { get; set; }
public string? RoleName { get; set; }
};

View File

@@ -18,6 +18,7 @@ namespace QuotifyBE.Data
public DbSet<Category> Categories => Set<Category>();
public DbSet<Image> Images => Set<Image>();
public DbSet<QuoteCategory> QuoteCategories => Set<QuoteCategory>();
public DbSet<Statistic> Statistics => Set<Statistic>();
protected override void OnModelCreating(ModelBuilder builder)
{
@@ -25,6 +26,10 @@ namespace QuotifyBE.Data
builder.Entity<QuoteCategory>()
.HasKey(vs => new { vs.QuoteId, vs.CategoryId });
builder.Entity<Statistic>(e => {
e.HasIndex(e => e.Label).IsUnique();
});
}
}
}

View File

@@ -1,4 +1,4 @@
namespace QuotifyBE.Entities
namespace QuotifyBE.Entities
{
public class Image
{

9
Entities/Statistic.cs Normal file
View File

@@ -0,0 +1,9 @@
namespace QuotifyBE.Entities;
public class Statistic
{
public int Id { get; set; }
required public string Label { get; set; }
public int? IValue { get; set; }
public string? SValue { get; set; }
}

View File

@@ -5,18 +5,18 @@ namespace QuotifyBE.Mapping;
public static class UserMapping
{
public static SuccessfulLoginDTO ToSuccessfulLoginDTO(this User user, string token)
public static SuccessfulLoginDTO ToSuccessfulLoginDTO(this User user, string token, string? roleName)
{
return new SuccessfulLoginDTO
{
Status = "ok",
Token = token,
User = user.ToUserInfoDTO()
User = user.ToUserInfoDTO(roleName)
};
}
public static UserInfoDTO ToUserInfoDTO(this User user)
public static UserInfoDTO ToUserInfoDTO(this User user, string? roleName)
{
return new UserInfoDTO
@@ -24,7 +24,8 @@ public static class UserMapping
Id = user.Id,
Name = user.Name,
Email = user.Email,
Role = user.Role
Role = user.Role,
RoleName = roleName
};
}
}

View File

@@ -0,0 +1,216 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using QuotifyBE.Data;
#nullable disable
namespace QuotifyBE.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
[Migration("20250721081641_sitewide_statistics")]
partial class sitewide_statistics
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "9.0.7")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("QuotifyBE.Entities.Category", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<DateTime?>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("Description")
.HasColumnType("text");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("Categories");
});
modelBuilder.Entity("QuotifyBE.Entities.Image", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("Url")
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("Images");
});
modelBuilder.Entity("QuotifyBE.Entities.Quote", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("Author")
.IsRequired()
.HasColumnType("text");
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<int?>("ImageId")
.HasColumnType("integer");
b.Property<DateTime>("LastUpdatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("Text")
.IsRequired()
.HasColumnType("text");
b.Property<int>("UserId")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("ImageId");
b.HasIndex("UserId");
b.ToTable("Quotes");
});
modelBuilder.Entity("QuotifyBE.Entities.QuoteCategory", b =>
{
b.Property<int>("QuoteId")
.HasColumnType("integer");
b.Property<int>("CategoryId")
.HasColumnType("integer");
b.HasKey("QuoteId", "CategoryId");
b.HasIndex("CategoryId");
b.ToTable("QuoteCategories");
});
modelBuilder.Entity("QuotifyBE.Entities.Statistic", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<int?>("IValue")
.HasColumnType("integer");
b.Property<string>("Label")
.IsRequired()
.HasColumnType("text");
b.Property<string>("SValue")
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("Label")
.IsUnique();
b.ToTable("Statistics");
});
modelBuilder.Entity("QuotifyBE.Entities.User", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("Email")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<string>("PasswordHash")
.IsRequired()
.HasColumnType("text");
b.Property<int>("Role")
.HasColumnType("integer");
b.HasKey("Id");
b.ToTable("Users");
});
modelBuilder.Entity("QuotifyBE.Entities.Quote", b =>
{
b.HasOne("QuotifyBE.Entities.Image", "Image")
.WithMany()
.HasForeignKey("ImageId");
b.HasOne("QuotifyBE.Entities.User", "User")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Image");
b.Navigation("User");
});
modelBuilder.Entity("QuotifyBE.Entities.QuoteCategory", b =>
{
b.HasOne("QuotifyBE.Entities.Category", "Category")
.WithMany()
.HasForeignKey("CategoryId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("QuotifyBE.Entities.Quote", "Quote")
.WithMany("QuoteCategories")
.HasForeignKey("QuoteId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Category");
b.Navigation("Quote");
});
modelBuilder.Entity("QuotifyBE.Entities.Quote", b =>
{
b.Navigation("QuoteCategories");
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -0,0 +1,43 @@
using Microsoft.EntityFrameworkCore.Migrations;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace QuotifyBE.Migrations
{
/// <inheritdoc />
public partial class sitewide_statistics : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Statistics",
columns: table => new
{
Id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
Label = table.Column<string>(type: "text", nullable: false),
IValue = table.Column<int>(type: "integer", nullable: true),
SValue = table.Column<string>(type: "text", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Statistics", x => x.Id);
});
migrationBuilder.CreateIndex(
name: "IX_Statistics_Label",
table: "Statistics",
column: "Label",
unique: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Statistics");
}
}
}

View File

@@ -113,6 +113,32 @@ namespace QuotifyBE.Migrations
b.ToTable("QuoteCategories");
});
modelBuilder.Entity("QuotifyBE.Entities.Statistic", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<int?>("IValue")
.HasColumnType("integer");
b.Property<string>("Label")
.IsRequired()
.HasColumnType("text");
b.Property<string>("SValue")
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("Label")
.IsUnique();
b.ToTable("Statistics");
});
modelBuilder.Entity("QuotifyBE.Entities.User", b =>
{
b.Property<int>("Id")

View File

@@ -33,7 +33,9 @@ builder.Services.AddCors(options =>
{
policy
.WithOrigins(CorsOrigins.ToArray())
.AllowAnyHeader(); // this might not be the greatest idea
// this might not be the greatest idea:
.AllowAnyHeader()
.AllowAnyMethod();
});
});
@@ -52,7 +54,11 @@ builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
ValidAudience = DomainName,
IssuerSigningKey = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes(JwtSecret)
)
),
// disable clock skew
// https://stackoverflow.com/a/46231102
// https://stackoverflow.com/a/47155318
ClockSkew = TimeSpan.Zero
};
});

View File

@@ -7,12 +7,16 @@
<UserSecretsId>b302b0ab-745f-4b53-b32a-12fbbc3e622d</UserSecretsId>
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
<DockerfileContext>.</DockerfileContext>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<NoWarn>$(NoWarn);1591</NoWarn>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<NoWarn>$(NoWarn);1591</NoWarn>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="EntityFramework" Version="6.5.1" />
<PackageReference Include="GitInfo" Version="3.5.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.18" />
<PackageReference Include="Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore" Version="8.0.18" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="9.0.7" />