11 Commits

24 changed files with 940 additions and 54 deletions

View File

@@ -4,11 +4,14 @@ 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 +38,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,19 +64,22 @@ 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);
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.
@@ -83,6 +90,7 @@ public class AuthController : ControllerBase
/// <response code="401">Returned on request with invalid JWT</response>
[HttpGet("some_values")]
[Authorize]
[EnableCors]
[ProducesResponseType(200)]
[ProducesResponseType(401)]
public IActionResult GetValues()
@@ -90,4 +98,31 @@ 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.
/// Authed endpoints expect Authorization header, e.g.:
/// Authorization: bearer {jwt}</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) });
}
}

View File

@@ -0,0 +1,111 @@
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
/// <summary>
/// Get every category
/// </summary>
/// <remarks>
/// Can (and will) return an empty list if no categories are found in DB. <br/>
/// 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]
[EnableCors]
[ProducesResponseType(typeof(CategoryShortDTO), 200)]
// [ProducesResponseType(typeof(ErrorDTO), 404)]
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/>
/// Important! 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());
}
}

View File

@@ -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())
};

View File

@@ -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,36 +30,43 @@ 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, 404 is returned.
/// Important! 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>
/// <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</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" });
return Ok(result);
{
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();
var result = quotes
.Select(q => q.ToQuoteShortDTO())
.ToList();
return Ok(result);
}
@@ -86,29 +94,31 @@ 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>
/// <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>
[HttpPost("new")]
[Authorize]
[ProducesResponseType(201)] // ?
[EnableCors]
[ProducesResponseType(201)]
[ProducesResponseType(typeof(ErrorDTO), 400)]
[ProducesResponseType(typeof(ErrorDTO), 401)]
[ProducesResponseType(typeof(ErrorDTO), 403)]
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
Image? image = null;
@@ -130,17 +140,17 @@ 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"});
return BadRequest(new ErrorDTO { Status = "error", Error_msg = $"Category ID {categoryId} not found"});
quote.QuoteCategories.Add(new QuoteCategory
{
@@ -170,12 +180,11 @@ public class QuotesController : ControllerBase
{
var totalQuotes = await _db.Quotes.CountAsync();
if (totalQuotes == 0)
return NotFound(new { status = "error", error_msg = "No quotes to choose from" });
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)
@@ -184,7 +193,7 @@ public class QuotesController : ControllerBase
.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)
@@ -194,6 +203,7 @@ public class QuotesController : ControllerBase
var dto = new QuoteShortDTO
{
Id = quote.Id,
Text = quote.Text,
Author = quote.Author,
ImageUrl = image?.Url,

41
Controllers/Seed.cs Normal file
View File

@@ -0,0 +1,41 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using QuotifyBE.Data;
using QuotifyBE.DTOs;
using QuotifyBE.Entities;
using QuotifyBE.Mapping;
using System.Security.Claims;
using Microsoft.EntityFrameworkCore;
namespace QuotifyBE.Controllers
{
public class Seed : Controller
{
private readonly ApplicationDbContext _db;
private readonly GeneralUseHelpers guhf;
public Seed(ApplicationDbContext db, GeneralUseHelpers GUHF)
{
_db = db;
guhf = GUHF;
}
public async Task SeedAsync()
{
var AccountNum = await _db.Users.CountAsync();
if (AccountNum == 0)
{
var Admin = new User
{
Name="admin",
Email = "admin@mail.com",
// hashed twice, once by frontend, and second time by backend
PasswordHash = guhf.HashWithSHA512(guhf.HashWithSHA512("admin")),
Role = 0 // role 0 - greatest power, admin, role 0 > role 1
};
_db.Users.Add(Admin);
await _db.SaveChangesAsync();
}
}
}
}

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

@@ -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; }
};

10
DTOs/UserInfoDTO.cs Normal file
View File

@@ -0,0 +1,10 @@
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; }
};

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,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 = [];

30
Mapping/UserMapping.cs Normal file
View File

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

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

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

View File

@@ -21,6 +21,22 @@ 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())
.AllowAnyHeader(); // this might not be the greatest idea
});
});
// 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)
@@ -43,9 +59,11 @@ builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
// 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 +85,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

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

View File

@@ -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"
},