mirror of
https://github.com/QuotifyTeam/QuotifyBE.git
synced 2025-12-16 11:20:05 +01:00
Compare commits
7 Commits
ba162c34cc
...
user_conte
| Author | SHA1 | Date | |
|---|---|---|---|
| 11d24dcc11 | |||
| bb9bdcfaa0 | |||
| 601d99bccd | |||
| df4cd1c8a7 | |||
| f60f613969 | |||
| ceb1829eb9 | |||
| a1086b94f1 |
@@ -27,7 +27,7 @@ public class CategoryController : ControllerBase
|
|||||||
guhf = GUHF;
|
guhf = GUHF;
|
||||||
}
|
}
|
||||||
|
|
||||||
// GET /api/v1/categories
|
// GET /api/v1/categories/page/1
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Get a category page
|
/// Get a category page
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -40,7 +40,7 @@ public class CategoryController : ControllerBase
|
|||||||
/// <response code="404">Returned when requested page is invalid (page_no <= 0)</response>
|
/// <response code="404">Returned when requested page is invalid (page_no <= 0)</response>
|
||||||
[HttpGet("page/{page_no}")]
|
[HttpGet("page/{page_no}")]
|
||||||
[EnableCors]
|
[EnableCors]
|
||||||
[ProducesResponseType(typeof(CategoryShortDTO), 200)]
|
[ProducesResponseType(typeof(List<CategoryShortDTO>), 200)]
|
||||||
[ProducesResponseType(typeof(ErrorDTO), 404)]
|
[ProducesResponseType(typeof(ErrorDTO), 404)]
|
||||||
public async Task<IActionResult> GetCategoryPage(int page_no = 1)
|
public async Task<IActionResult> GetCategoryPage(int page_no = 1)
|
||||||
{
|
{
|
||||||
@@ -78,6 +78,47 @@ public class CategoryController : ControllerBase
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 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(List<CategoryShortDTO>), 200)]
|
||||||
|
public async Task<IActionResult> GetQuotePage()
|
||||||
|
{
|
||||||
|
// 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 NotFound(new ErrorDTO { Status = "error", Error_msg = "No categories to list" });
|
||||||
|
// }
|
||||||
|
|
||||||
|
// Get all the categories
|
||||||
|
List<Category> categories = await _db.Categories
|
||||||
|
.ToListAsync();
|
||||||
|
|
||||||
|
// Convert them to a list of DTO
|
||||||
|
List<CategoryShortDTO> result = categories
|
||||||
|
.Select(c => c.ToCategoryShortDTO())
|
||||||
|
.ToList();
|
||||||
|
|
||||||
|
// Return to user
|
||||||
|
return Ok(result);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
// POST /api/v1/categories
|
// POST /api/v1/categories
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// [AUTHED] Create a new category
|
/// [AUTHED] Create a new category
|
||||||
|
|||||||
@@ -255,7 +255,8 @@ public class QuotesController : ControllerBase
|
|||||||
{
|
{
|
||||||
IQueryable<Quote> query = _db.Quotes
|
IQueryable<Quote> query = _db.Quotes
|
||||||
.Include(q => q.QuoteCategories!)
|
.Include(q => q.QuoteCategories!)
|
||||||
.ThenInclude(qc => qc.Category);
|
.ThenInclude(qc => qc.Category)
|
||||||
|
.Include(q => q.Image);
|
||||||
|
|
||||||
if (category_id.HasValue)
|
if (category_id.HasValue)
|
||||||
{
|
{
|
||||||
@@ -278,8 +279,6 @@ public class QuotesController : ControllerBase
|
|||||||
var skip = random.Next(0, totalQuotes);
|
var skip = random.Next(0, totalQuotes);
|
||||||
|
|
||||||
var quote = await query
|
var quote = await query
|
||||||
.Include(q => q.QuoteCategories!)
|
|
||||||
.ThenInclude(qc => qc.Category)
|
|
||||||
.Skip(skip)
|
.Skip(skip)
|
||||||
.Take(1)
|
.Take(1)
|
||||||
.FirstOrDefaultAsync();
|
.FirstOrDefaultAsync();
|
||||||
|
|||||||
200
Controllers/UserContentController.cs
Normal file
200
Controllers/UserContentController.cs
Normal file
@@ -0,0 +1,200 @@
|
|||||||
|
using Microsoft.AspNetCore.Authorization;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using QuotifyBE.Data;
|
||||||
|
using QuotifyBE.Entities;
|
||||||
|
using QuotifyBE.DTOs;
|
||||||
|
using QuotifyBE.Mapping;
|
||||||
|
using Microsoft.AspNetCore.Cors;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
|
||||||
|
namespace QuotifyBE.Controllers;
|
||||||
|
|
||||||
|
|
||||||
|
[ApiController]
|
||||||
|
[EnableCors]
|
||||||
|
[Route("api/v1/uc")]
|
||||||
|
[Produces("application/json")]
|
||||||
|
public class UserContentController : ControllerBase
|
||||||
|
{
|
||||||
|
|
||||||
|
private readonly IConfiguration _appsettings;
|
||||||
|
private readonly ApplicationDbContext _db;
|
||||||
|
private readonly GeneralUseHelpers guhf;
|
||||||
|
|
||||||
|
public UserContentController(IConfiguration appsettings, ApplicationDbContext db, GeneralUseHelpers GUHF)
|
||||||
|
{
|
||||||
|
_appsettings = appsettings;
|
||||||
|
_db = db;
|
||||||
|
guhf = GUHF;
|
||||||
|
}
|
||||||
|
|
||||||
|
// GET /api/v1/uc/images
|
||||||
|
/// <summary>
|
||||||
|
/// [AUTHED] Get every image
|
||||||
|
/// </summary>
|
||||||
|
/// <remarks>
|
||||||
|
/// Can (and will) return an empty list if no images are found in DB. <br/>
|
||||||
|
/// Requires authorization with a JWT, has CORS set.
|
||||||
|
/// </remarks>
|
||||||
|
/// <response code="200">Returned on valid request</response>
|
||||||
|
[HttpGet("images")]
|
||||||
|
[Authorize]
|
||||||
|
[EnableCors]
|
||||||
|
[ProducesResponseType(typeof(List<Image>), 200)]
|
||||||
|
public async Task<IActionResult> GetImages()
|
||||||
|
{
|
||||||
|
|
||||||
|
// Get all the images
|
||||||
|
List<Image> images = await _db.Images
|
||||||
|
.ToListAsync();
|
||||||
|
|
||||||
|
// Return to user
|
||||||
|
return Ok(images);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// POST /api/v1/uc/images
|
||||||
|
/// <summary>
|
||||||
|
/// [AUTHED] Upload an image and get an its URI
|
||||||
|
/// </summary>
|
||||||
|
/// <remarks>
|
||||||
|
/// Allows authorized users to publish images.
|
||||||
|
/// A user-reachable path and image id is returned on success.<br/>
|
||||||
|
/// </remarks>
|
||||||
|
/// <response code="200">Returned on valid request</response>
|
||||||
|
/// <response code="400">Returned when request does not contain a file or the file is blank</response>
|
||||||
|
/// <response code="413">Returned when image size is too large</response>
|
||||||
|
/// <response code="415">Returned when file extension/mimetype is unknown</response>
|
||||||
|
[HttpPost("images")]
|
||||||
|
[Authorize]
|
||||||
|
[EnableCors]
|
||||||
|
[ProducesResponseType(200)]
|
||||||
|
[ProducesResponseType(typeof(ErrorDTO), 400)]
|
||||||
|
[ProducesResponseType(typeof(ErrorDTO), 413)]
|
||||||
|
[ProducesResponseType(typeof(ErrorDTO), 415)]
|
||||||
|
public IActionResult PostNewImage(IFormFile file)
|
||||||
|
{
|
||||||
|
// Obsługa braku pliku
|
||||||
|
if (file == null || file.Length == 0)
|
||||||
|
{
|
||||||
|
return BadRequest(new ErrorDTO
|
||||||
|
{
|
||||||
|
Status = "error",
|
||||||
|
Error_msg = "No file was uploaded."
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Dozwolone rozszerzenia
|
||||||
|
List<string> allowedExtensions = new List<string>() { ".jpg", ".jpeg", ".jfif", ".png", ".gif", ".avif", ".webp" };
|
||||||
|
string fileExtension = Path.GetExtension(file.FileName).ToLower();
|
||||||
|
|
||||||
|
if (!allowedExtensions.Contains(fileExtension))
|
||||||
|
{
|
||||||
|
return StatusCode(415, new ErrorDTO
|
||||||
|
{
|
||||||
|
Status = "error",
|
||||||
|
Error_msg = $"Unknown file extension. Allowed: {string.Join(", ", allowedExtensions)}"
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sprawdzenie typu MIME (opcjonalnie dokładniejsze)
|
||||||
|
if (!file.ContentType.StartsWith("image/"))
|
||||||
|
{
|
||||||
|
return StatusCode(415, new ErrorDTO
|
||||||
|
{
|
||||||
|
Status = "error",
|
||||||
|
Error_msg = "Uploaded file is not an image."
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ograniczenie rozmiaru pliku do tego, ustawionego przez użytkownika
|
||||||
|
int MaxFileSize = int.TryParse(_appsettings.GetSection("UserContent")["MaxFileSize"], out int r)
|
||||||
|
? r
|
||||||
|
: 5 * 1024 * 1024;
|
||||||
|
if (file.Length > MaxFileSize)
|
||||||
|
{
|
||||||
|
return StatusCode(413, new ErrorDTO
|
||||||
|
{
|
||||||
|
Status = "error",
|
||||||
|
Error_msg = $"File size exceeds {MaxFileSize / 1024 / 1024} MB."
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Generowanie unikalnej nazwy
|
||||||
|
string uniqueFileName = $"{Guid.NewGuid()}{fileExtension}";
|
||||||
|
string relativePath = $"/uploads/images/{uniqueFileName}";
|
||||||
|
string absolutePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "uploads", "images", uniqueFileName);
|
||||||
|
|
||||||
|
// Upewnij się, że katalog istnieje
|
||||||
|
Directory.CreateDirectory(Path.GetDirectoryName(absolutePath)!);
|
||||||
|
|
||||||
|
// Zapis pliku na dysk
|
||||||
|
using (var stream = new FileStream(absolutePath, FileMode.Create))
|
||||||
|
{
|
||||||
|
file.CopyTo(stream);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Dodaj do bazy
|
||||||
|
Image image = new Image { Url = relativePath };
|
||||||
|
_db.Images.Add(image);
|
||||||
|
_db.SaveChanges();
|
||||||
|
|
||||||
|
// Zwracany adres URL (np. do użytku w cytacie)
|
||||||
|
return Ok(new
|
||||||
|
{
|
||||||
|
Status = "ok",
|
||||||
|
Filepath = relativePath,
|
||||||
|
ImageId = image.Id
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// DELETE /api/v1/uc/images/{id}
|
||||||
|
/// <summary>
|
||||||
|
/// [AUTHED] Delete an image
|
||||||
|
/// </summary>
|
||||||
|
/// <remarks>
|
||||||
|
/// Deletes an image, granted it exists. <br/>
|
||||||
|
/// <b>Note</b>:
|
||||||
|
/// If the image is a file on disk, it's also deleted.
|
||||||
|
/// </remarks>
|
||||||
|
/// <returns>Json with status</returns>
|
||||||
|
/// <param name="id">Image id which will be deleted</param>
|
||||||
|
/// <response code="200">Returned on valid request</response>
|
||||||
|
/// <response code="404">Returned when no such image exists</response>
|
||||||
|
[HttpDelete("images/{id}")]
|
||||||
|
[Authorize]
|
||||||
|
[EnableCors]
|
||||||
|
[ProducesResponseType(200)]
|
||||||
|
[ProducesResponseType(typeof(ErrorDTO), 404)]
|
||||||
|
public async Task<IActionResult> DeleteImage(int id)
|
||||||
|
{
|
||||||
|
// (Attempt to) find the image
|
||||||
|
Image? image = await _db.Images
|
||||||
|
.FirstOrDefaultAsync(q => q.Id == id);
|
||||||
|
// Failed?
|
||||||
|
if (image == null)
|
||||||
|
return NotFound(new { status = "error", error_msg = "Image not found" });
|
||||||
|
|
||||||
|
// If succeded, remove the image:
|
||||||
|
// - from disk - if saved locally
|
||||||
|
if (!string.IsNullOrEmpty(image.Url)) {
|
||||||
|
if (image.Url.StartsWith("/uploads/images/")) {
|
||||||
|
// delete from disk
|
||||||
|
int fileNameStart = image.Url.LastIndexOf('/');
|
||||||
|
string uniqueFileName = image.Url.Substring(fileNameStart + 1);
|
||||||
|
string absolutePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "uploads", "images", uniqueFileName);
|
||||||
|
System.IO.File.Delete(absolutePath);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// - from db
|
||||||
|
_db.Images.Remove(image);
|
||||||
|
await _db.SaveChangesAsync();
|
||||||
|
|
||||||
|
// Return ok
|
||||||
|
return Ok(new { Status = "ok" });
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
@@ -151,5 +151,5 @@ app.UseAuthentication();
|
|||||||
app.UseAuthorization();
|
app.UseAuthorization();
|
||||||
|
|
||||||
app.MapControllers();
|
app.MapControllers();
|
||||||
|
app.UseStaticFiles();
|
||||||
app.Run();
|
app.Run();
|
||||||
|
|||||||
@@ -35,4 +35,8 @@
|
|||||||
<PackageReference Include="Swashbuckle.AspNetCore.Annotations" Version="9.0.3" />
|
<PackageReference Include="Swashbuckle.AspNetCore.Annotations" Version="9.0.3" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<Folder Include="wwwroot\uploads\images\" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
</Project>
|
</Project>
|
||||||
|
|||||||
@@ -2,8 +2,11 @@
|
|||||||
"JwtSecret": "this is a sample jwt secret token required for quotify - it needs to have at least 256 bits (32 bytes long)",
|
"JwtSecret": "this is a sample jwt secret token required for quotify - it needs to have at least 256 bits (32 bytes long)",
|
||||||
"DomainName": "example.com",
|
"DomainName": "example.com",
|
||||||
"CorsOrigins": [
|
"CorsOrigins": [
|
||||||
"http://localhost:5259", "http://localhost:5258", "http://example.com"
|
"http://localhost:5259", "http://localhost:5258", "http://localhost:3000", "http://example.com"
|
||||||
],
|
],
|
||||||
|
"UserContent": {
|
||||||
|
"MaxFileSize": 5242880,
|
||||||
|
},
|
||||||
"ConnectionStrings": {
|
"ConnectionStrings": {
|
||||||
"DefaultConnection": "Server=server-host;Database=db-name;Username=quotify-user;Password=user-secret"
|
"DefaultConnection": "Server=server-host;Database=db-name;Username=quotify-user;Password=user-secret"
|
||||||
},
|
},
|
||||||
|
|||||||
BIN
wwwroot/uploads/images/42cbadf4-7804-4fde-991c-d56eb1f4a1b4.png
Normal file
BIN
wwwroot/uploads/images/42cbadf4-7804-4fde-991c-d56eb1f4a1b4.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 141 KiB |
Reference in New Issue
Block a user