mirror of
https://github.com/QuotifyTeam/QuotifyBE.git
synced 2025-12-16 11:20:05 +01:00
Compare commits
42 Commits
AddQuote
...
ceb1829eb9
| Author | SHA1 | Date | |
|---|---|---|---|
| ceb1829eb9 | |||
| a1086b94f1 | |||
| ba162c34cc | |||
| 197918e526 | |||
| ac80061437 | |||
| e7cebc32a4 | |||
| 9e1e9c86d3 | |||
| 10d2a35e61 | |||
| ca78f43f73 | |||
| 3a82e4291e | |||
| 341755d77e | |||
| 468d502827 | |||
| 0ec7bdf2fe | |||
| b292586764 | |||
| 779772e60c | |||
| b96c780533 | |||
| f773f886b4 | |||
| d502e9d120 | |||
| a8a82df6ed | |||
| d09d8f85e3 | |||
| 05e6b9bc86 | |||
| db6f57830a | |||
| ddfab4dac1 | |||
| d99755e7af | |||
| 1f9c04e2fc | |||
| d53b85fe9e | |||
| 644e9de0bd | |||
| ee7e7762e0 | |||
| 7d20e4d4f9 | |||
| 908a56665d | |||
| 76258bc0eb | |||
| b20b7d9127 | |||
| 0a6633316c | |||
| af233d9ee9 | |||
| abebb84c69 | |||
| 2350935e8a | |||
| 3cd2eff522 | |||
| f34a1ee995 | |||
| b84de07941 | |||
| 09bc6637a8 | |||
| 4b7b731679 | |||
| 9e00954c29 |
@@ -1,5 +1,5 @@
|
||||
[*]
|
||||
end_of_line = crlf
|
||||
end_of_line = lf
|
||||
charset = utf-8
|
||||
trim_trailing_whitespace = true
|
||||
insert_final_newline = true
|
||||
@@ -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)));
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
256
Controllers/CategoryController.cs
Normal file
256
Controllers/CategoryController.cs
Normal 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 <= 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());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -14,6 +14,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 +104,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())
|
||||
};
|
||||
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Cors;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using QuotifyBE.Data;
|
||||
using QuotifyBE.DTOs;
|
||||
using QuotifyBE.Entities;
|
||||
using QuotifyBE.Mapping;
|
||||
using System.Security.Claims;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace QuotifyBE.Controllers;
|
||||
|
||||
@@ -29,48 +30,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 (<= 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 <= 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 +147,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 +212,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 +234,251 @@ 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());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
60
Controllers/Seed.cs
Normal file
60
Controllers/Seed.cs
Normal 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!");
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
59
Controllers/StatisticController.cs
Normal file
59
Controllers/StatisticController.cs
Normal 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
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
9
DTOs/CategoryShortDTO.cs
Normal file
9
DTOs/CategoryShortDTO.cs
Normal 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;
|
||||
|
||||
};
|
||||
@@ -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; }
|
||||
};
|
||||
|
||||
@@ -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
6
DTOs/NewCategoryDTO.cs
Normal file
@@ -0,0 +1,6 @@
|
||||
namespace QuotifyBE.DTOs;
|
||||
public class NewCategoryDTO
|
||||
{
|
||||
public string Name { get; set; } = string.Empty;
|
||||
public string? Description { get; set; }
|
||||
}
|
||||
@@ -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();
|
||||
|
||||
};
|
||||
|
||||
|
||||
9
DTOs/SuccessfulLoginDTO.cs
Normal file
9
DTOs/SuccessfulLoginDTO.cs
Normal 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
11
DTOs/UserInfoDTO.cs
Normal 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; }
|
||||
|
||||
};
|
||||
@@ -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();
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
namespace QuotifyBE.Entities
|
||||
namespace QuotifyBE.Entities
|
||||
{
|
||||
public class Image
|
||||
{
|
||||
|
||||
9
Entities/Statistic.cs
Normal file
9
Entities/Statistic.cs
Normal 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; }
|
||||
}
|
||||
@@ -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; }
|
||||
}
|
||||
}
|
||||
|
||||
19
Mapping/CategoryMapping.cs
Normal file
19
Mapping/CategoryMapping.cs
Normal 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
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -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
31
Mapping/UserMapping.cs
Normal 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
|
||||
};
|
||||
}
|
||||
}
|
||||
183
Migrations/20250717083328_user_roles.Designer.cs
generated
Normal file
183
Migrations/20250717083328_user_roles.Designer.cs
generated
Normal 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
|
||||
}
|
||||
}
|
||||
}
|
||||
29
Migrations/20250717083328_user_roles.cs
Normal file
29
Migrations/20250717083328_user_roles.cs
Normal 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");
|
||||
}
|
||||
}
|
||||
}
|
||||
190
Migrations/20250718084441_more_category_data.Designer.cs
generated
Normal file
190
Migrations/20250718084441_more_category_data.Designer.cs
generated
Normal 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
|
||||
}
|
||||
}
|
||||
}
|
||||
57
Migrations/20250718084441_more_category_data.cs
Normal file
57
Migrations/20250718084441_more_category_data.cs
Normal 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");
|
||||
}
|
||||
}
|
||||
}
|
||||
216
Migrations/20250721081641_sitewide_statistics.Designer.cs
generated
Normal file
216
Migrations/20250721081641_sitewide_statistics.Designer.cs
generated
Normal 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
|
||||
}
|
||||
}
|
||||
}
|
||||
43
Migrations/20250721081641_sitewide_statistics.cs
Normal file
43
Migrations/20250721081641_sitewide_statistics.cs
Normal 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");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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");
|
||||
|
||||
67
Program.cs
67
Program.cs
@@ -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();
|
||||
|
||||
|
||||
@@ -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" />
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
"Microsoft.AspNetCore": "Information"
|
||||
}
|
||||
}
|
||||
},
|
||||
"Microsoft.AspNetCore.HttpLogging.HttpLoggingMiddleware": "Information"
|
||||
}
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
{
|
||||
"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": [
|
||||
"http://localhost:5259", "http://localhost:5258", "http://example.com"
|
||||
],
|
||||
"ConnectionStrings": {
|
||||
"DefaultConnection": "Server=server-host;Database=db-name;Username=quotify-user;Password=user-secret"
|
||||
},
|
||||
|
||||
Reference in New Issue
Block a user