mirror of
https://github.com/QuotifyTeam/QuotifyBE.git
synced 2025-12-16 19:00:07 +01:00
builder in Program.cs is not aware of it, so [Authorize] decorator can't be provided data necessary to validate requests which contain JWT with password
158 lines
4.7 KiB
C#
158 lines
4.7 KiB
C#
using Microsoft.AspNetCore.Mvc;
|
|
using Microsoft.AspNetCore.Authorization;
|
|
using QuotifyBE.Data;
|
|
using QuotifyBE.Entities;
|
|
using QuotifyBE.Mapping;
|
|
using System.Security.Claims;
|
|
using Microsoft.EntityFrameworkCore;
|
|
|
|
namespace QuotifyBE.Controllers;
|
|
|
|
|
|
[ApiController]
|
|
[Route("api/v1/quotes")]
|
|
public class QuotesController : ControllerBase
|
|
{
|
|
|
|
private readonly ApplicationDbContext _db;
|
|
private readonly GeneralUseHelpers guhf;
|
|
|
|
public QuotesController(ApplicationDbContext db, GeneralUseHelpers GUHF)
|
|
{
|
|
_db = db;
|
|
guhf = GUHF;
|
|
}
|
|
|
|
// GET /api/v1/quotes
|
|
/// <summary>
|
|
/// Get a given quote page
|
|
/// </summary>
|
|
[HttpGet("page/{page_no}")]
|
|
public async Task<IActionResult> GetQuotePage(int page_no)
|
|
{
|
|
// TODO...
|
|
|
|
return NotFound(new { status = "error", error_msg = "Not implemented" });
|
|
|
|
// TODO: Consider turning the quote into a DTO
|
|
}
|
|
|
|
// GET /api/v1/quotes/{id}
|
|
[HttpGet("{id}")]
|
|
public async Task<IActionResult> GetQuoteById(int id)
|
|
{
|
|
// FIXME: The expression 'q.QuoteCategories' is invalid inside an 'Include' operation, since it does not represent a property access: 't => t.MyProperty'.
|
|
var quote = await _db.Quotes
|
|
.Include(q => q.QuoteCategories!)
|
|
.ThenInclude(qc => qc.Category)
|
|
.Include(q => q.User)
|
|
.Include(q => q.Image)
|
|
.FirstOrDefaultAsync(q => q.Id == id);
|
|
|
|
if (quote == null)
|
|
return NotFound(new { status = "error", error_msg = "Quote not found" });
|
|
|
|
return Ok(quote.ToQuoteShortDTO(_db));
|
|
}
|
|
|
|
// POST /api/v1/quotes/new
|
|
[HttpPost("new")]
|
|
[Authorize]
|
|
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))
|
|
return Unauthorized(new {status = "error", error_msg = "Invalid user ID"});
|
|
|
|
// Find or create image
|
|
Image? image = null;
|
|
if (!string.IsNullOrEmpty(request.ImageUrl))
|
|
{
|
|
image = await _db.Images.FirstOrDefaultAsync(i => i.Url == request.ImageUrl);
|
|
if (image == null)
|
|
{
|
|
image = new Image { Url = request.ImageUrl };
|
|
_db.Images.Add(image);
|
|
await _db.SaveChangesAsync();
|
|
}
|
|
}
|
|
|
|
// Create quote
|
|
var quote = new Quote
|
|
{
|
|
Text = request.Text,
|
|
Author = request.Author,
|
|
CreatedAt = DateTime.UtcNow,
|
|
LastUpdatedAt = DateTime.UtcNow,
|
|
ImageId = image?.Id ?? 0,
|
|
UserId = userId,
|
|
QuoteCategories = new List<QuoteCategory>()
|
|
};
|
|
|
|
// Attach categories
|
|
foreach (var categoryId in request.CategoryIds)
|
|
{
|
|
var categoryExists = await _db.Categories.AnyAsync(c => c.Id == categoryId);
|
|
if (!categoryExists)
|
|
return BadRequest(new {status = "error", error_msg = $"Category ID {categoryId} not found"});
|
|
|
|
quote.QuoteCategories.Add(new QuoteCategory
|
|
{
|
|
CategoryId = categoryId,
|
|
Quote = quote
|
|
});
|
|
}
|
|
|
|
_db.Quotes.Add(quote);
|
|
await _db.SaveChangesAsync();
|
|
|
|
return CreatedAtAction(nameof(GetQuoteById), new { id = quote.Id }, quote);
|
|
}
|
|
|
|
// GET /api/v1/quotes/random
|
|
[HttpGet("random")]
|
|
[AllowAnonymous]
|
|
public async Task<IActionResult> GetRandomQuote()
|
|
{
|
|
var totalQuotes = await _db.Quotes.CountAsync();
|
|
if (totalQuotes == 0)
|
|
return NotFound(new { status = "error", error_msg = "No quotes to choose from" });
|
|
|
|
var random = new Random();
|
|
var skip = random.Next(0, totalQuotes);
|
|
|
|
// FIXME
|
|
var quote = await _db.Quotes
|
|
.Include(q => q.QuoteCategories!)
|
|
.ThenInclude(qc => qc.Category)
|
|
.Skip(skip)
|
|
.Take(1)
|
|
.FirstOrDefaultAsync();
|
|
|
|
if (quote == null)
|
|
return NotFound();
|
|
|
|
Image? image = null;
|
|
if (quote.ImageId != 0)
|
|
{
|
|
image = await _db.Images.FirstOrDefaultAsync(i => i.Id == quote.ImageId);
|
|
}
|
|
|
|
var dto = new QuoteShortDTO
|
|
{
|
|
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);
|
|
|
|
}
|
|
|
|
}
|