47 Commits

Author SHA1 Message Date
3e823fb37b feat: LLM API endpoint 2025-07-23 18:45:03 +02:00
9e9017717a feat: helper function for generating LLM responses 2025-07-23 18:28:28 +02:00
bc05e91790 chore: add core dependency, and a DTO for user input 2025-07-23 18:24:35 +02:00
df4cd1c8a7 fix: include .jpeg as an allowed file extension 2025-07-23 12:48:05 +02:00
f60f613969 feat: template for image upload 2025-07-23 12:19:29 +02:00
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
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
b20b7d9127 feat: basic category controller (create & retrieve) 2025-07-18 11:09:27 +02:00
0a6633316c chore: migrate to new category structure 2025-07-18 11:08:00 +02:00
af233d9ee9 feat: bring authorization bearer to swagger 2025-07-18 09:41:30 +02:00
abebb84c69 feat: helper functions for checking roles and a demo endpoint 2025-07-17 13:48:12 +02:00
2350935e8a fix: fixes to addQuote (don't require categories nor imageUrl)
also sends back role upon login
2025-07-17 10:55:38 +02:00
3cd2eff522 fix: use userid for jwt, migration for user roles 2025-07-17 10:39:22 +02:00
f34a1ee995 feat: experimental cors support 2025-07-16 21:30:57 +02:00
b84de07941 feat: enable request logging for development environment 2025-07-16 21:25:13 +02:00
09bc6637a8 feat: provide user data on login, minor fix to seeding, logical fixes 2025-07-16 16:51:54 +02:00
4b7b731679 fix: return id for random quote as well 2025-07-16 12:20:47 +02:00
9e00954c29 Seedowanie 2025-07-16 11:34:03 +02:00
35 changed files with 2129 additions and 94 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,12 +3,14 @@ using Microsoft.AspNetCore.Mvc;
using QuotifyBE.Data;
using QuotifyBE.Entities;
using QuotifyBE.DTOs;
using System.Threading.Tasks;
using QuotifyBE.Mapping;
using Microsoft.AspNetCore.Cors;
namespace QuotifyBE.Controllers;
[ApiController]
[EnableCors]
[Route("api/v1/auth")]
[Produces("application/json")]
public class AuthController : ControllerBase
@@ -35,13 +37,14 @@ public class AuthController : ControllerBase
/// in the Authorization header, e.g.: Authorization: bearer {jwt}
/// </remarks>
/// <param name="formUser">User's credentials (email and password)</param>
/// <returns>JWT valid for 5 minutes.</returns>
/// <response code="200">Returned on request with valid credentials</response>
/// <returns>JWT valid for 5 minutes and basic user data.</returns>
/// <response code="200">Returned on request with valid credentials. Contains the token, but also user data.</response>
/// <response code="400">Returned on request with missing form data (email, password or both)</response>
/// <response code="401">Returned on request with unknown pair of email and password (wrong password)</response>
/// <response code="404">Returned on request with unknwon email</response>
[HttpPost("login")]
[ProducesResponseType(200)]
[EnableCors]
[ProducesResponseType(typeof(SuccessfulLoginDTO), 200)]
[ProducesResponseType(typeof(ErrorDTO), 400)]
[ProducesResponseType(typeof(ErrorDTO), 401)]
[ProducesResponseType(typeof(ErrorDTO), 404)]
@@ -60,29 +63,36 @@ public class AuthController : ControllerBase
return NotFound(new {status = "error", error_msg = "User not found"});
}
// Hash the password and compare with the user-provided one
string hashedFormPassword = guhf.HashWithSHA512(formUser.Password);
if (hashedFormPassword == user.PasswordHash)
{
// All set - generate the token and return it
var token = guhf.GenerateJwtToken(formUser.Email);
return Ok(new { status = "ok", token });
var token = guhf.GenerateJwtToken(user);
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"});
}
// GET /api/v1/auth/some_values
/// <summary>
/// Dummy, authed endpoint
/// [AUTHED] Dummy, authed endpoint
/// </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>
[HttpGet("some_values")]
[Authorize]
[EnableCors]
[ProducesResponseType(200)]
[ProducesResponseType(401)]
public IActionResult GetValues()
@@ -90,4 +100,57 @@ public class AuthController : ControllerBase
return Ok(new string[] { "value1", "value2" });
}
// GET /api/v1/auth/user_role
/// <summary>
/// [AUTHED] Get user role as a string
/// </summary>
/// <remarks>
/// Authed endpoint used to check human-readable user role.
/// </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>
[HttpGet("user_role")]
[Authorize]
[EnableCors]
[ProducesResponseType(200)]
[ProducesResponseType(typeof(ErrorDTO), 400)]
public IActionResult GetUserRole()
{
// Get user from token
User? u = guhf.GetUserFromToken(Request.Headers.Authorization!);
if (u == null)
return BadRequest(new ErrorDTO { Status = "error", Error_msg = "User not found" });
// Return the role as a string
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

@@ -0,0 +1,256 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using QuotifyBE.Data;
using QuotifyBE.Entities;
using QuotifyBE.DTOs;
using System.Threading.Tasks;
using QuotifyBE.Mapping;
using Microsoft.AspNetCore.Cors;
using Microsoft.EntityFrameworkCore;
namespace QuotifyBE.Controllers;
[ApiController]
[EnableCors]
[Route("api/v1/categories")]
[Produces("application/json")]
public class CategoryController : ControllerBase
{
private readonly ApplicationDbContext _db;
private readonly GeneralUseHelpers guhf;
public CategoryController(ApplicationDbContext db, GeneralUseHelpers GUHF)
{
_db = db;
guhf = GUHF;
}
// GET /api/v1/categories/page/1
/// <summary>
/// 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(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
/// <summary>
/// [AUTHED] Create a new category
/// </summary>
/// <remarks>
/// 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>
/// <response code="406">Returned when such category already exists (case insensitive)</response>
[HttpPost]
[Authorize]
[EnableCors]
[ProducesResponseType(typeof(CategoryShortDTO), 200)]
[ProducesResponseType(typeof(ErrorDTO), 406)]
public async Task<IActionResult> PostNewCategory([FromBody] NewCategoryDTO formCategory)
{
// Check if such category doesn't already exist
Category? cat = await _db.Categories.FirstOrDefaultAsync(c => c.Name.ToLower() == formCategory.Name.ToLower());
if (cat != null)
{
return StatusCode(406, new ErrorDTO { Status = "error", Error_msg = "This category already exists" });
}
// Create new category
cat = new Category
{
Name = formCategory.Name,
Description = formCategory.Description,
CreatedAt = DateTime.UtcNow
};
// Add to DB
await _db.Categories.AddAsync(cat);
await _db.SaveChangesAsync();
// And send back to the user as DTO
return Ok(cat.ToCategoryShortDTO());
}
// 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

@@ -1,5 +1,7 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using QuotifyBE.Data;
using QuotifyBE.Entities;
using System.IdentityModel.Tokens.Jwt;
@@ -14,6 +16,78 @@ public class GeneralUseHelpers(ApplicationDbContext db, IConfiguration appsettin
private readonly ApplicationDbContext _db = db;
private readonly IConfiguration _appsettings = appsettings;
// Allows to check whether the user is of role present in roles.
// Example:
// For user with role 0,
// - IsUser(["Manager"], req) yields false
// - IsUser(["Admin"], req) yields true
// - IsUser(["Admin", "Manager"], req) yields true because the user is an admin
public bool IsUser(string[] roles, HttpRequest req)
{
// Get the user to read its roles
User? user = GetUserFromToken(req.Headers.Authorization!);
if (user == null) {
return false;
}
foreach (var role in roles)
{
if (string.IsNullOrEmpty(role))
{
continue;
}
switch (role)
{
case "Admin":
if (user.Role == 0)
return true;
break;
case "Manager":
if (user.Role == 1)
return true;
break;
case "Pracownik":
if (user.Role == 2)
return true;
break;
default:
continue;
}
}
return false;
}
public string UserRoleAsStr(User user)
{
switch (user.Role)
{
case 0:
return "Admin";
case 1:
return "Manager";
case 2:
return "Pracownik";
default:
return "Unknown role";
}
}
public User? GetUserFromToken(string token)
{
if (token.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase))
{
token = token.Substring("Bearer ".Length).Trim();
}
var handler = new JwtSecurityTokenHandler();
var jwtSecurityToken = handler.ReadJwtToken(token);
if (int.TryParse(jwtSecurityToken.Subject, out int userId))
{
return _db.Users.FirstOrDefault(u => u.Id == userId);
}
return null;
}
async public Task<User?> GetUserFromEmail(string email)
{
return await _db.Users.FirstOrDefaultAsync(e => e.Email == email);
@@ -32,11 +106,11 @@ public class GeneralUseHelpers(ApplicationDbContext db, IConfiguration appsettin
}
}
public string GenerateJwtToken(string username)
public string GenerateJwtToken(User user)
{
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.Sub, username),
new Claim(JwtRegisteredClaimNames.Sub, user.Id.ToString()),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
};
@@ -60,4 +134,108 @@ public class GeneralUseHelpers(ApplicationDbContext db, IConfiguration appsettin
return new JwtSecurityTokenHandler().WriteToken(token);
}
public async Task<JObject?> GenerateLLMResponse(string? prompt, string? model, float? temp, int? includedCategory, bool? includeCategorySample)
{
string _model = model ?? _appsettings.GetSection("LlmIntegration")["DefaultModel"] ?? "deepclaude";
float _temp = temp ?? 0.6f; // sane default
string _included_sample = string.Empty;
string _prompt = prompt ?? _appsettings.GetSection("LlmIntegration")["DefaultPrompt"] ??
"Cześć, czy jesteś w stanie wymyślić i stworzyć jeden oryginalny cytat? " +
"Zastanów się nad jego puentą, a kiedy będziesz gotów - zwróć sam cytat. " +
"Nie pytaj mnie co o nim sądzę, ani nie używaj emotikonów (emoji). " +
"Pamiętaj, że dobre cytaty są krótkie, zwięzłe.";
if (includedCategory != null)
{
// Check if category to be included is present.
Category? cat = await _db.Categories.FirstOrDefaultAsync(c => c.Id == includedCategory.Value);
// It isn't?
if (cat == null) return null;
// It is?
_prompt += $" Niech należy on do kategorii o nazwie \"{cat.Name}\" ({cat.Description}).";
}
// Sanity check
if (includeCategorySample != null && includeCategorySample == true)
{
if (includedCategory == null)
{
// Can't append something that we're not given.
return null;
}
else
{
// Try to find the category in question.
Category? cat = await _db.Categories.FirstOrDefaultAsync(c => c.Id == includedCategory.Value);
// Failed?
if (cat == null)
{
return null;
}
else
{
IQueryable<Quote> query = _db.Quotes
.Include(q => q.QuoteCategories!)
.Where(q => q.QuoteCategories
.Any(qc => qc.Category == cat)
);
int totalQuotes = await query.CountAsync();
if (totalQuotes > 0) {
Random random = new();
int skip = random.Next(0, totalQuotes);
Quote? quote = await query
.Skip(skip)
.Take(1)
.FirstOrDefaultAsync();
if (quote != null) {
_prompt += $" Przykładowy cytat z tej kategorii brzmi: \"{quote.Text} ~ {quote.Author}\".\n";
}
}
}
}
}
List<Dictionary<string, string>> promptMessages =
[
new() { { "role", "user" }, {"content", _prompt } }
];
// Will throw error if not present
string apiUrl = _appsettings.GetSection("LlmIntegration")["ApiUrl"] + "/chat/completions"
?? throw new MissingFieldException("API URL missing in LlmIntegration section of appsettings.json!");
string apiKey = _appsettings.GetSection("LlmIntegration")["ApiKey"]
?? throw new MissingFieldException("API key missing in LlmIntegration section of appsettings.json!");
using (var client = new HttpClient())
{
// Not the best practice if we want reusable connections
// https://stackoverflow.com/a/40707446
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
var json = JsonConvert.SerializeObject(new
{
model = _model,
temperature = _temp,
max_tokens = (includeCategorySample ?? false) ? 2000 : 1000,
messages = promptMessages
});
var content = new StringContent(json, Encoding.UTF8, "application/json");
var response = await client.PostAsync(apiUrl, content);
if (response.IsSuccessStatusCode)
{
string receivedResponse = await response.Content.ReadAsStringAsync();
return JObject.Parse(receivedResponse);
}
else
{
// Handle the error
Console.WriteLine($"[QuotifyBE] Error: response status code from API was {response.StatusCode}.");
return null;
}
}
}
}

View File

@@ -1,11 +1,13 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json.Linq;
using QuotifyBE.Data;
using QuotifyBE.DTOs;
using QuotifyBE.Entities;
using QuotifyBE.Mapping;
using System.Security.Claims;
using Microsoft.EntityFrameworkCore;
namespace QuotifyBE.Controllers;
@@ -29,48 +31,108 @@ public class QuotesController : ControllerBase
/// <summary>
/// Get a page of quotes
/// </summary>
/// <remarks>A page of quotes consists of 10 quotes or less. If a page does not contain any quotes, 404 is returned.</remarks>
/// <remarks>
/// A page of quotes consists of 10 quotes or less.
/// 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 or does not exist</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)
{
var totalQuotes = await _db.Quotes.CountAsync();
const int PageSize = 10;
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();
if (quotes == null || totalQuotes == 0)
{
return NotFound(new ErrorDTO { Status = "error", error_msg = "Brak cytatów na tej stronie." });
}
var result = quotes.Select(q => q.ToQuoteShortDTO(_db)).ToList();
//return NotFound(new { status = "error", error_msg = "Not implemented" });
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" });
}
// 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)
@@ -86,37 +148,58 @@ public class QuotesController : ControllerBase
if (quote == null)
return NotFound(new { status = "error", error_msg = "Quote not found" });
return Ok(quote.ToQuoteShortDTO(_db));
return Ok(quote.ToQuoteShortDTO());
}
// POST /api/v1/quotes/new
/// <summary>
/// Add a new quote
/// [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="401">Returned when user's id does not match the creator's id</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]
[ProducesResponseType(201)] // ?
[EnableCors]
[ProducesResponseType(201)]
[ProducesResponseType(typeof(ErrorDTO), 400)]
[ProducesResponseType(typeof(ErrorDTO), 401)]
[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))
return Unauthorized(new {status = "error", error_msg = "Invalid user ID"});
// 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();
@@ -130,21 +213,21 @@ public class QuotesController : ControllerBase
Author = request.Author,
CreatedAt = DateTime.UtcNow,
LastUpdatedAt = DateTime.UtcNow,
ImageId = image?.Id ?? 0,
ImageId = image?.Id ?? null,
UserId = userId,
QuoteCategories = new List<QuoteCategory>()
};
// Attach categories
foreach (var categoryId in request.CategoryIds)
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"});
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
});
}
@@ -152,59 +235,322 @@ 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)
.Include(q => q.Image);
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 { 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);
// FIXME
var quote = await _db.Quotes
.Include(q => q.QuoteCategories!)
.ThenInclude(qc => qc.Category)
var quote = await query
.Skip(skip)
.Take(1)
.FirstOrDefaultAsync();
if (quote == null)
return NotFound();
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
{
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());
}
// POST /api/v1/quotes/ai
/// <summary>
/// [AUTHED] Request a LLM-generated quote
/// </summary>
/// <returns>Generated quote's text</returns>
/// <remarks>
/// <b>Notes</b>:<br/>
///
/// <ul>
/// If <i>customPrompt</i> is passed:
/// <li>The default prompt is overriden by whatever has been passed by the user.</li>
/// </ul><br/>
///
/// <ul>
/// If <i>model</i> is passed:
/// <li>The default large language model is overriden by whatever has been passed by the user.</li>
/// </ul><br/>
///
/// <ul>
/// If <i>temperature</i> is passed:
/// <li>The default temperature (= 0.8) is overriden by whatever has been passed by the user.</li>
/// </ul><br/>
///
/// <ul>
/// If <i>categoryId</i> is passed:
/// <li>The prompt is appended with an instruction in Polish to generate quotes based on the provided category
/// (both name and description get passed to the model).</li>
/// <li><b>Heads up!</b> The text is appended even if <i>customPrompt</i> has been provided.</li>
/// </ul><br/>
///
/// <ul>
/// If <i>useSampleQuote</i> is passed:
/// <li>The prompt will be appended with a randomly chosen quote from the categoryId (if any exist),
/// thus passing categoryId becomes a prerequisite.</li>
/// <li><b>Heads up!</b> The request will fail returning status code 400 if categoryId isn't provided!</li>
/// </ul>
/// </remarks>
/// <param name="request">Form data containing required quote information</param>
/// <response code="200">Returned on valid request</response>
/// <response code="400">Returned when generation failed due to remote server error (likely because of a bad request)</response>
/// <response code="500">Returned when response has been generated, but couldn't be parsed (likely because of incompatible server or bad URL)</response>
[HttpPost("ai")]
[Authorize]
[EnableCors]
[ProducesResponseType(200)]
[ProducesResponseType(typeof(ErrorDTO), 400)]
[ProducesResponseType(typeof(ErrorDTO), 500)]
public async Task<IActionResult> CreateLLMQuote([FromBody] AskLLMInDTO request)
{
JObject? generatedResponse = await guhf.GenerateLLMResponse(
request.CustomPrompt, request.Model, request.Temperature, request.CategoryId, request.UseSampleQuote
);
// Check if any errors occurred
if (generatedResponse == null)
{
return StatusCode(400, new ErrorDTO { Status = "error", Error_msg = "Generation failed most likely due to bad request" });
}
// Parse JSON to get the bot reply
string? llmResponse = generatedResponse["choices"]?[0]?["message"]?["content"]?.ToString().Trim('"');
// If response string is not where we expect it, return 500
if (llmResponse == null)
return StatusCode(500, new ErrorDTO { Status = "error", Error_msg = "Unexpected API response" });
// Otherwise, return the response
return Ok(new { Status = "ok", BotResponse = llmResponse });
}
}

60
Controllers/Seed.cs Normal file
View File

@@ -0,0 +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()
{
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

@@ -0,0 +1,119 @@
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]
[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 is returned on success.<br/>
/// </remarks>
/// <response code="200">Returned on valid request</response>
/// <response code="400">Returned when file extension is unknown</response>
/// <response code="406">Returned when request does not follow user-provided config</response>
[HttpPost]
[Authorize]
[EnableCors]
[ProducesResponseType(200)]
[ProducesResponseType(typeof(ErrorDTO), 400)]
[ProducesResponseType(typeof(ErrorDTO), 406)]
public IActionResult PostNewImage(IFormFile file)
{
// Ideally, a hash of the file would be stored somewhere
// in the database to have a basic redundancy check,
// but this will do for now. ~eee4
// A good idea would be to also check the Content-Type
// of submitted files. ~eee4
List<string> allowedExtensions = new List<string>() { ".jpg", ".jpeg", ".jfif", ".png", ".gif", ".avif", ".webp" };
string fileExtension = Path.GetExtension(file.FileName);
if (!allowedExtensions.Contains(fileExtension.ToLower())) {
return BadRequest(new ErrorDTO {
Status = "error",
Error_msg = $"Unknown file extension. Please use one of the following: {string.Join(", ", allowedExtensions)}"
});
}
// TODO:
// https://www.youtube.com/watch?v=6-FNejMrVuk
// Sprawdź, czy plik spełnia ograniczenia:
// 1. Czy rozmiar jest mniejszy od _appsettings["UserContent"]["MaxFileSize"] ?
// Jeśli nie, zwróć ErrorDTO ze wiadomością: $"File size exceeds {_appsettings["UserContent"]["MaxFileSize"]}"
// Zapisz plik na dysku z pseudolosową nazwą GUID
// Wrzucić go do folderu "uploads/images/"
// Stwórz URL postaci: "/uploads/images/<nazwa pliku>.<rozszerzenie>"
// Zwróć powyższy URL
return Ok(new { Status = "ok", Filepath = "miejsce na wspomniany URL" });
}
}

12
DTOs/AskLLMInDTO.cs Normal file
View File

@@ -0,0 +1,12 @@
namespace QuotifyBE.DTOs;
public record class AskLLMInDTO
{
public string? CustomPrompt { get; set; }
public string? Model { get; set; } = "deepclaude";
public float? Temperature { get; set; } = 0.8f;
public int? CategoryId { get; set; } = null;
public bool? UseSampleQuote { get; set; } = false;
};

9
DTOs/CategoryShortDTO.cs Normal file
View File

@@ -0,0 +1,9 @@
namespace QuotifyBE.DTOs;
public record class CategoryShortDTO
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public string? Description { get; set; }
public DateTime? CreatedAt { get; set; } = DateTime.UtcNow;
};

View File

@@ -2,6 +2,6 @@ public record class CreateQuoteDTO
{
public string Text { get; set; }
public string Author { get; set; }
public List<int> CategoryIds { get; set; }
public List<int>? CategoryIds { get; set; }
public string? ImageUrl { get; set; }
};

View File

@@ -2,6 +2,7 @@ namespace QuotifyBE.DTOs;
public record class ErrorDTO
{
public string Status { get; set; }
public string error_msg { get; set; }
required public string Status { get; set; }
required public string Error_msg { get; set; }
}

6
DTOs/NewCategoryDTO.cs Normal file
View File

@@ -0,0 +1,6 @@
namespace QuotifyBE.DTOs;
public class NewCategoryDTO
{
public string Name { get; set; } = string.Empty;
public string? Description { get; set; }
}

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

@@ -0,0 +1,9 @@
namespace QuotifyBE.DTOs;
public record class SuccessfulLoginDTO
{
required public string Status { get; set; }
required public string Token { get; set; }
required public UserInfoDTO User { get; set; }
};

11
DTOs/UserInfoDTO.cs Normal file
View File

@@ -0,0 +1,11 @@
namespace QuotifyBE.DTOs;
public record class UserInfoDTO
{
public int Id { get; set; }
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,8 +1,10 @@
namespace QuotifyBE.Entities
namespace QuotifyBE.Entities
{
public class Category
{
public int Id { get; set; }
public string? Name { get; set; }
required public string Name { get; set; } = string.Empty;
public string? Description { get; set; }
public DateTime? CreatedAt { get; set; } = DateTime.UtcNow;
}
}

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

@@ -1,10 +1,11 @@
namespace QuotifyBE.Entities
namespace QuotifyBE.Entities
{
public class User
{
public int Id { get; set; }
required public string Name { get; set; }
required public string Email { get; set; }
public int Role { get; set; }
required public string PasswordHash { get; set; }
}
}

View File

@@ -0,0 +1,19 @@
using QuotifyBE.DTOs;
using QuotifyBE.Entities;
namespace QuotifyBE.Mapping;
public static class CategoryMapping
{
public static CategoryShortDTO ToCategoryShortDTO(this Category category)
{
return new CategoryShortDTO
{
Id = category.Id,
Name = category.Name,
Description = category.Description,
CreatedAt = category.CreatedAt
};
}
}

View File

@@ -8,7 +8,7 @@ namespace QuotifyBE.Mapping;
public static class QuoteMapping
{
public static QuoteShortDTO ToQuoteShortDTO(this Quote quote, ApplicationDbContext db)
public static QuoteShortDTO ToQuoteShortDTO(this Quote quote)
{
List<string> categoryNames = [];

31
Mapping/UserMapping.cs Normal file
View File

@@ -0,0 +1,31 @@
using QuotifyBE.DTOs;
using QuotifyBE.Entities;
namespace QuotifyBE.Mapping;
public static class UserMapping
{
public static SuccessfulLoginDTO ToSuccessfulLoginDTO(this User user, string token, string? roleName)
{
return new SuccessfulLoginDTO
{
Status = "ok",
Token = token,
User = user.ToUserInfoDTO(roleName)
};
}
public static UserInfoDTO ToUserInfoDTO(this User user, string? roleName)
{
return new UserInfoDTO
{
Id = user.Id,
Name = user.Name,
Email = user.Email,
Role = user.Role,
RoleName = roleName
};
}
}

View File

@@ -0,0 +1,183 @@
// <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("20250717083328_user_roles")]
partial class user_roles
{
/// <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<string>("Name")
.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.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,29 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace QuotifyBE.Migrations
{
/// <inheritdoc />
public partial class user_roles : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<int>(
name: "Role",
table: "Users",
type: "integer",
nullable: false,
defaultValue: 0);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "Role",
table: "Users");
}
}
}

View File

@@ -0,0 +1,190 @@
// <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("20250718084441_more_category_data")]
partial class more_category_data
{
/// <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.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,57 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace QuotifyBE.Migrations
{
/// <inheritdoc />
public partial class more_category_data : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterColumn<string>(
name: "Name",
table: "Categories",
type: "text",
nullable: false,
defaultValue: "",
oldClrType: typeof(string),
oldType: "text",
oldNullable: true);
migrationBuilder.AddColumn<DateTime>(
name: "CreatedAt",
table: "Categories",
type: "timestamp with time zone",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "Description",
table: "Categories",
type: "text",
nullable: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "CreatedAt",
table: "Categories");
migrationBuilder.DropColumn(
name: "Description",
table: "Categories");
migrationBuilder.AlterColumn<string>(
name: "Name",
table: "Categories",
type: "text",
nullable: true,
oldClrType: typeof(string),
oldType: "text");
}
}
}

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

@@ -30,7 +30,14 @@ namespace QuotifyBE.Migrations
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");
@@ -106,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")
@@ -126,6 +159,9 @@ namespace QuotifyBE.Migrations
.IsRequired()
.HasColumnType("text");
b.Property<int>("Role")
.HasColumnType("integer");
b.HasKey("Id");
b.ToTable("Users");

View File

@@ -21,6 +21,24 @@ var JwtSecret = builder.Configuration["JwtSecret"]
var DomainName = builder.Configuration["DomainName"]
?? throw new InvalidOperationException("Domain name is not configured!!! Please configure DomainName in appsettings.json!");
var CorsOrigins = builder.Configuration.GetSection("CorsOrigins").Get<List<string>>()
?? throw new InvalidOperationException("CORS is not configured!!! Please configure CorsOrigins in appsettings.json!");
// Add default CORS policy
builder.Services.AddCors(options =>
{
options.AddDefaultPolicy(
policy =>
{
policy
.WithOrigins(CorsOrigins.ToArray())
// this might not be the greatest idea:
.AllowAnyHeader()
.AllowAnyMethod();
});
});
// Configure JWT authentication
// https://medium.com/@solomongetachew112/jwt-authentication-in-net-8-a-complete-guide-for-secure-and-scalable-applications-6281e5e8667c
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
@@ -36,16 +54,22 @@ 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
};
});
// Add services to the container.
builder.Services.AddAuthorization();
builder.Services.AddSingleton(builder.Configuration);
builder.Services.AddHttpContextAccessor();
builder.Services.AddScoped<GeneralUseHelpers>();
builder.Services.AddControllers();
builder.Services.AddHttpLogging(o => { });
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(options =>
@@ -67,23 +91,62 @@ builder.Services.AddSwaggerGen(options =>
}
});
// https://stackoverflow.com/a/58972781
options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Description = @"JWT Authorization header using the Bearer scheme. <br/>
Enter your JWT from /api/v1/auth/login to authorize.",
Name = "Authorization",
In = ParameterLocation.Header,
Type = SecuritySchemeType.Http,
Scheme = "Bearer"
});
options.AddSecurityRequirement(new OpenApiSecurityRequirement()
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
},
Scheme = "oauth2",
Name = "Bearer",
In = ParameterLocation.Header,
},
new List<string>()
}
});
// using System.Reflection;
var xmlFilename = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlFilename));
});
var app = builder.Build();
using (var scope = app.Services.CreateScope())
{
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
var guhf = scope.ServiceProvider.GetRequiredService<GeneralUseHelpers>();
var seeder = new Seed(db, guhf);
await seeder.SeedAsync();
}
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseHttpLogging();
app.UseMigrationsEndPoint();
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseCors();
app.UseAuthentication();
app.UseAuthorization();

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" />
@@ -25,10 +29,15 @@
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.22.1" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="Npgsql" Version="9.0.3" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="9.0.4" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="9.0.3" />
<PackageReference Include="Swashbuckle.AspNetCore.Annotations" Version="9.0.3" />
</ItemGroup>
<ItemGroup>
<Folder Include="uploads\images\" />
</ItemGroup>
</Project>

View File

@@ -2,7 +2,8 @@
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
"Microsoft.AspNetCore": "Information"
}
}
},
"Microsoft.AspNetCore.HttpLogging.HttpLoggingMiddleware": "Information"
}

View File

@@ -1,6 +1,18 @@
{
"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",
"CorsOrigins": [
"https://localhost:7029", "http://localhost:5259", "http://localhost:5258", "http://localhost:3000", "http://example.com"
],
"UserContent": {
"MaxFileSize": 5242880
},
"LlmIntegration": {
"ApiUrl": "URL to OpenAI-compatible API server, e.g. https://example.com/api/v1",
"ApiKey": "FILL ME for AI-generation capabilities",
"DefaultPrompt": "Cześć, czy jesteś w stanie wymyślić i stworzyć jeden oryginalny cytat?\nZastanów się nad jego puentą, a kiedy będziesz gotów - zwróć sam cytat.\nNie pytaj mnie co o nim sądzę, ani nie używaj emotikonów (emoji).\nPamiętaj, że dobre cytaty są krótkie, zwięzłe.",
"DefaultModel": "deepclaude"
},
"ConnectionStrings": {
"DefaultConnection": "Server=server-host;Database=db-name;Username=quotify-user;Password=user-secret"
},