Läuft soweit, bis auf Authorisierung

This commit is contained in:
OlgunR 2024-07-10 09:00:36 +02:00
parent 9999d257e0
commit c41c0bab6c
50 changed files with 2088 additions and 53 deletions

View File

@ -0,0 +1,4 @@
namespace Project.Application.DTOs.Auth
{
public record AuthCheckDto(bool IsAuthenticated);
}

View File

@ -0,0 +1,4 @@
namespace Project.Application.DTOs.Auth
{
public record LoginDto(string Username, string Password);
}

View File

@ -1,4 +1,5 @@
using Project.Domain.Entities;
using Project.Application.DTOs.Outgoing;
using Project.Domain.Entities;
namespace Project.Application.DTOs.Incoming
{
@ -6,6 +7,6 @@ namespace Project.Application.DTOs.Incoming
{
public string Name { get; set; }
public decimal Price { get; set; }
public CreatingCategoryDto? Category { get; set; }
public int CategoryId { get; set; }
}
}

View File

@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Project.Application.DTOs.Incoming
{
public class CreatingRoleDto
{
public string Name { get; set; }
}
}

View File

@ -0,0 +1,15 @@
namespace Project.Application.DTOs.Incoming
{
public class CreatingUserDto
{
public string UserName { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Password { get; init; }
public int RoleId { get; set; }
}
}

View File

@ -11,6 +11,6 @@ namespace Project.Application.DTOs.Incoming
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
public CreatingCategoryDto? Category { get; set; }
public int CategoryId { get; set; }
}
}

View File

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Project.Application.DTOs.Incoming
{
public class UpdatingRoleDto
{
public int Id { get; set; }
public string Name { get; set; }
}
}

View File

@ -0,0 +1,17 @@
namespace Project.Application.DTOs.Incoming
{
public class UpdatingUserDto
{
public int Id { get; set; }
public string UserName { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Password { get; init; }
public int RoleId { get; set; }
}
}

View File

@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Project.Application.DTOs.Outgoing
{
public class ReadingRoleDto
{
public int Id { get; set; }
public string Name { get; set; }
}
}

View File

@ -0,0 +1,14 @@
namespace Project.Application.DTOs.Outgoing
{
public class ReadingUserDto
{
public int Id { get; set; }
public string UserName { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public ReadingRoleDto? Role { get; set; }
}
}

View File

@ -0,0 +1,10 @@
using Project.Domain.Entities;
namespace Project.Application.Interfaces
{
public interface IAuthService
{
// AUTHENTICATE
Task<bool> ValidateAsync(string username, string password);
}
}

View File

@ -0,0 +1,27 @@
using Project.Application.DTOs.Incoming;
using Project.Application.DTOs.Outgoing;
using Project.Domain.Entities;
namespace Project.Application.Interfaces
{
public interface IRoleService
{
// CREATE
Task<Role?> AddRoleAsync(CreatingRoleDto creatingRoleDto);
// READ ALL
Task<IEnumerable<ReadingRoleDto>> GetAllAsync();
// READ BY ID
Task<ReadingRoleDto> GetByIdAsync(int id);
// READ BY NAME
Task<ReadingRoleDto> GetByNameAsync(string name);
// UPDATE
Task<bool> UpdateRoleAsync(UpdatingRoleDto updatedRoleDto);
// DELETE
Task<bool> DeleteRoleAsync(int id);
}
}

View File

@ -0,0 +1,30 @@
using Project.Application.DTOs.Incoming;
using Project.Application.DTOs.Outgoing;
using Project.Domain.Entities;
namespace Project.Application.Interfaces
{
public interface IUserService
{
// CREATE
Task<User?> AddUserAsync(CreatingUserDto creatingUserDto);
// READ ALL
Task<IEnumerable<ReadingUserDto>> GetUsersAsync();
// READ BY ID
Task<ReadingUserDto> GetByIdAsync(int id);
// READ BY USERNAME
Task<ReadingUserDto> GetByUsernameAsync(string username);
// UPDATE
Task<bool> UpdateUserAsync(UpdatingUserDto updatingUserDto);
// UPDATE USER ROLE -- die Rolle eines Users aktualisieren
Task UpdateUserRoleAsync(int userId, int roleId);
// DELETE
Task<bool> DeleteUserAsync(int id);
}
}

View File

@ -9,13 +9,25 @@ namespace Project.Application.MappingProfiles
{
public BasicDtoMappingProfile()
{
// CATEGORY
CreateMap<Category, CreatingCategoryDto>().ReverseMap();
CreateMap<Category, ReadingCategoryDto>().ReverseMap();
CreateMap<Category, UpdatingCategoryDto>().ReverseMap();
// PRODUCT
CreateMap<Product, CreatingProductDto>().ReverseMap();
CreateMap<Product, ReadingProductDto>().ReverseMap();
CreateMap<Product, UpdatingProductDto>().ReverseMap();
// ROLE
CreateMap<Role, CreatingRoleDto>().ReverseMap();
CreateMap<Role, ReadingRoleDto>().ReverseMap();
CreateMap<Role, UpdatingRoleDto>().ReverseMap();
// USER
CreateMap<User, CreatingUserDto>().ReverseMap();
CreateMap<User, ReadingUserDto>().ReverseMap();
CreateMap<User, UpdatingUserDto>().ReverseMap();
}
}
}

View File

@ -7,6 +7,7 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.Cookies" Version="2.2.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.6" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="8.0.6" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="8.0.6">

View File

@ -0,0 +1,26 @@
using Project.Application.Interfaces;
using Project.Domain.Entities;
using Project.Infrastructure.Interfaces;
namespace Project.Application.Services
{
public class AuthService : IAuthService
{
// FIELDS FOR CTOR
private IUserRepository _userRepository;
// CTOR
public AuthService(IUserRepository userRepository)
{
_userRepository = userRepository;
}
// AUTHENTICATE
public async Task<bool> ValidateAsync(string username, string password)
{
var user = await _userRepository.GetByUsernameAsync(username);
return user?.Password == password;
}
}
}

View File

@ -56,8 +56,8 @@ namespace Project.Application.Services
public async Task<bool> UpdateProductAsync(UpdatingProductDto updatingProductDto)
{
var product = _mapper.Map<Product>(updatingProductDto);
bool idUpdated = await _productRepository.UpdateAsync(product);
return idUpdated;
bool isUpdated = await _productRepository.UpdateAsync(product);
return isUpdated;
}
// DELETE

View File

@ -0,0 +1,75 @@
using AutoMapper;
using Project.Application.DTOs.Incoming;
using Project.Application.DTOs.Outgoing;
using Project.Application.Interfaces;
using Project.Domain.Entities;
using Project.Infrastructure.Interfaces;
namespace Project.Application.Services
{
public class RoleService : IRoleService
{
// FIELDS FOR CTOR
private readonly IRoleRepository _roleRepository;
private readonly IMapper _mapper;
// CTOR
public RoleService(IRoleRepository roleRepository, IMapper mapper)
{
_roleRepository = roleRepository;
_mapper = mapper;
}
// CREATE
public async Task<Role?> AddRoleAsync(CreatingRoleDto creatingRoleDto)
{
var role = _mapper.Map<Role>(creatingRoleDto);
var created = await _roleRepository.AddAsync(role);
return created;
}
// READ ALL
public async Task<IEnumerable<ReadingRoleDto>> GetAllAsync()
{
var roles = await _roleRepository.GetAllAsync();
var readDto = _mapper.Map<IEnumerable<ReadingRoleDto>>(roles);
return readDto;
}
// READ BY ID
public async Task<ReadingRoleDto> GetByIdAsync(int id)
{
var role = await _roleRepository.GetByIdAsync(id);
var readDto = _mapper.Map<ReadingRoleDto>(role);
return readDto;
}
// READ BY NAME
public async Task<ReadingRoleDto> GetByNameAsync(string name)
{
var role = await _roleRepository.GetByNameAsync(name);
var readDto = _mapper.Map<ReadingRoleDto>(role);
return readDto;
}
// UPDATE
public async Task<bool> UpdateRoleAsync(UpdatingRoleDto updatingRoleDto)
{
var role = _mapper.Map<Role>(updatingRoleDto);
bool isUpdated = await _roleRepository.UpdateAsync(role);
return isUpdated;
}
// DELETE
public async Task<bool> DeleteRoleAsync(int id)
{
Role? role = await _roleRepository.GetByIdAsync(id);
if (role is null)
return false;
bool isDeleted = await _roleRepository.DeleteAsync(role);
return isDeleted;
}
}
}

View File

@ -0,0 +1,104 @@
using AutoMapper;
using Project.Application.DTOs.Incoming;
using Project.Application.DTOs.Outgoing;
using Project.Application.Interfaces;
using Project.Domain.Entities;
using Project.Infrastructure.Interfaces;
namespace Project.Application.Services
{
public class UserService : IUserService
{
// FIELDS FOR CTOR
private readonly IUserRepository _userRepository;
private readonly IRoleRepository _roleRepository;
private readonly IMapper _mapper;
// CTOR
public UserService(IUserRepository userRepository, IRoleRepository roleRepository, IMapper mapper)
{
_userRepository = userRepository;
_roleRepository = roleRepository;
_mapper = mapper;
}
// CREATE
public async Task<User?> AddUserAsync(CreatingUserDto creatingUserDto)
{
// validating role
var role = await _roleRepository.GetByIdAsync(creatingUserDto.RoleId);
if (role == null)
{
throw new ArgumentException("Role not found");
}
// mapping dto to entity
var user = _mapper.Map<User>(creatingUserDto);
var created = await _userRepository.AddAsync(user);
return created;
}
// READ ALL
public async Task<IEnumerable<ReadingUserDto>> GetUsersAsync()
{
var users = await _userRepository.GetAllAsync();
var readDto = _mapper.Map<IEnumerable<ReadingUserDto>>(users);
return readDto;
}
// READ BY ID
public async Task<ReadingUserDto> GetByIdAsync(int id)
{
var user = await _userRepository.GetByIdAsync(id);
var readDto = _mapper.Map<ReadingUserDto>(user);
return readDto;
}
// READ BY USERNAME
public async Task<ReadingUserDto> GetByUsernameAsync(string username)
{
var user = await _userRepository.GetByUsernameAsync(username);
var readDto = _mapper.Map<ReadingUserDto>(user);
return readDto;
}
// UPDATE
public async Task<bool> UpdateUserAsync(UpdatingUserDto updatingUserDto)
{
var user = _mapper.Map<User>(updatingUserDto);
bool isUpdated = await _userRepository.UpdateAsync(user);
return isUpdated;
}
// UPDATE USER ROLE -- die Rolle eines Users aktualisieren
public async Task UpdateUserRoleAsync(int userId, int roleId)
{
var user = await _userRepository.GetByIdAsync(userId);
if (user == null)
{
throw new ArgumentException("User not found");
}
var role = await _roleRepository.GetByIdAsync(roleId);
if (role == null)
{
throw new ArgumentException("Role not found");
}
user.RoleId = roleId;
await _userRepository.SaveAsync();
}
// DELETE
public async Task<bool> DeleteUserAsync(int id)
{
User? user = await _userRepository.GetByIdAsync(id);
if (user is null)
return false;
bool isDeleted = await _userRepository.DeleteAsync(user);
return isDeleted;
}
}
}

View File

@ -10,9 +10,11 @@ namespace Project.Domain.Entities
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Column("ID")]
public int Id { get; set; } = 0;
[Required]
[Column("CATEGORY_NAME")]
public string Name { get; set; }
[Required]
[Column("CREATION_DATE", TypeName = "datetime")]
public DateTime CreationDate { get; set; } = DateTime.Now;

View File

@ -10,12 +10,16 @@ namespace Project.Domain.Entities
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Column("ID")]
public int Id { get; set; }
public int CategoryId { get; set; }
public int RoleId { get; set; }
[ForeignKey("CategoryId")]
[Required]
[Column("PRODUCT_CATEGORY")]
public Category? Category { get; set; }
[ForeignKey("RoleId")]
public Role? Role { get; set; }
}

View File

@ -10,13 +10,17 @@ namespace Project.Domain.Entities
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Column("ID")]
public int Id { get; set; } = 0;
[Required]
[Column("PRODUCT_NAME")]
public string Name { get; set; }
[Required]
[Column("PRICE", TypeName = "decimal(18,2)")]
public decimal Price { get; set; }
public int CategoryId { get; set; }
[ForeignKey("CategoryId")]
[Column("PRODUCT_CATEGORY")]
public Category? Category { get; set; }

View File

@ -10,11 +10,13 @@ namespace Project.Domain.Entities
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Column("ID")]
public int Id { get; set; }
[Required]
[Column("ROLE")]
public string Name { get; set; }
[Required]
[Column("CREATION_DATE", TypeName = "datetime")]
public DateTime CreationDate { get; set; }
public DateTime CreationDate { get; set; } = DateTime.Now;
}
}

View File

@ -6,21 +6,29 @@ namespace Project.Domain.Entities
[Table("USER", Schema = "dbo")]
public class User
{
[Column("ID")]
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Column("ID")]
public int Id { get; set; }
[Required]
[Column("USER_NAME")]
public string UserName { get; set; }
[Required]
[Column("FIRST_NAME")]
public string FirstName { get; set; }
[Required]
[Column("LAST_NAME")]
public string LastName { get; set; }
[Required]
[Column("PASSWORD")]
public string Password { get; init; }
public int RoleId { get; set; }
[ForeignKey("RoleId")]
public Role? Role { get; set; }
}

View File

@ -7,6 +7,7 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.Cookies" Version="2.2.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.6" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="8.0.6" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="8.0.6">

View File

@ -20,7 +20,10 @@ namespace Project.Infrastructure
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<User>();
modelBuilder.Entity<User>()
.HasOne(u => u.Role)
.WithMany()
.HasForeignKey(u => u.RoleId);
}
}
}

View File

@ -0,0 +1,25 @@
using Project.Domain.Entities;
namespace Project.Infrastructure.Interfaces
{
public interface IRoleRepository
{
// CREATE
Task<Role?> AddAsync(Role role);
// READ ALL
Task<IEnumerable<Role>> GetAllAsync();
// READ BY ID
Task<Role?> GetByIdAsync(int id);
// READ BY NAME
Task<Role?> GetByNameAsync(string name);
// UPDATE
Task<bool> UpdateAsync(Role role);
// DELETE
Task<bool> DeleteAsync(Role role);
}
}

View File

@ -0,0 +1,28 @@
using Project.Domain.Entities;
namespace Project.Infrastructure.Interfaces
{
public interface IUserRepository
{
// CREATE
Task<User?> AddAsync(User user);
// READ ALL
Task<IEnumerable<User>> GetAllAsync();
// READ BY ID
Task<User?> GetByIdAsync(int id);
// READ BY USERNAME
Task<User?> GetByUsernameAsync(string username);
// UPDATE
Task<bool> UpdateAsync(User user);
// DELETE
Task<bool> DeleteAsync(User user);
// SAVE
Task<bool> SaveAsync();
}
}

View File

@ -8,6 +8,7 @@
<ItemGroup>
<PackageReference Include="AutoMapper" Version="13.0.1" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.Cookies" Version="2.2.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.6" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="8.0.6" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="8.0.6">

View File

@ -9,13 +9,11 @@ namespace Project.Infrastructure.Repositories
{
// FIELDS FOR CTOR
private readonly ApplicationDbContext _context;
private readonly IMapper _mapper;
// CTOR
public CategoryRepository(ApplicationDbContext context, IMapper mapper)
public CategoryRepository(ApplicationDbContext context)
{
_context = context;
_mapper = mapper;
}
// CREATE

View File

@ -9,13 +9,11 @@ namespace Project.Infrastructure.Repositories
{
// FIELDS FOR CTOR
private readonly ApplicationDbContext _context;
private readonly IMapper _mapper;
// CTOR
public ProductRepository(ApplicationDbContext context, IMapper mapper)
public ProductRepository(ApplicationDbContext context)
{
_context = context;
_mapper = mapper;
}
// CREATE
@ -27,7 +25,6 @@ namespace Project.Infrastructure.Repositories
}
// READ ALL
[Authorize]
public async Task<IEnumerable<Product>> GetAllAsync()
{
return await _context.Products.Include(p => p.Category).ToListAsync();

View File

@ -0,0 +1,61 @@
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using Project.Domain.Entities;
using Project.Infrastructure.Interfaces;
namespace Project.Infrastructure.Repositories
{
public class RoleRepository : IRoleRepository
{
// FIELDS FOR CTOR
private readonly ApplicationDbContext _context;
// CTOR
public RoleRepository(ApplicationDbContext context)
{
_context = context;
}
// CREATE
public async Task<Role?> AddAsync(Role role)
{
await _context.Roles.AddAsync(role);
await _context.SaveChangesAsync();
return role;
}
// READ ALL
public async Task<IEnumerable<Role>> GetAllAsync()
{
return await _context.Roles.ToListAsync();
}
// READ BY ID
public async Task<Role?> GetByIdAsync(int id)
{
return await _context.Roles.FindAsync(id);
}
// READ BY NAME
public async Task<Role?> GetByNameAsync(string name)
{
return await _context.Roles.FirstOrDefaultAsync(n => n.Name == name);
}
// UPDATE
public async Task<bool> UpdateAsync(Role role)
{
_context.Entry(role).State = EntityState.Modified;
var results = await _context.SaveChangesAsync();
return results > 0;
}
// DELETE
public async Task<bool> DeleteAsync(Role role)
{
_context.Roles.Remove(role);
var result = await _context.SaveChangesAsync();
return result > 0;
}
}
}

View File

@ -0,0 +1,68 @@
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using Project.Domain.Entities;
using Project.Infrastructure.Interfaces;
namespace Project.Infrastructure.Repositories
{
public class UserRepository : IUserRepository
{
// FIELDS FOR CTOR
private readonly ApplicationDbContext _context;
// CTOR
public UserRepository(ApplicationDbContext context)
{
_context = context;
}
// CREATE
public async Task<User?> AddAsync(User user)
{
await _context.Users.AddAsync(user);
await _context.SaveChangesAsync();
return user;
}
// READ ALL
public async Task<IEnumerable<User>> GetAllAsync()
{
return await _context.Users.Include(u => u.Role).ToListAsync();
}
// READ BY ID
public async Task<User?> GetByIdAsync(int id)
{
return await _context.Users.FindAsync(id);
}
// READ BY USERNAME
public async Task<User?> GetByUsernameAsync(string username)
{
return await _context.Users.FirstOrDefaultAsync(u => u.UserName == username);
}
// UPDATE
public async Task<bool> UpdateAsync(User user)
{
_context.Entry(user).State = EntityState.Modified;
var results = await _context.SaveChangesAsync();
return results > 0;
}
// DELETE
public async Task<bool> DeleteAsync(User user)
{
_context.Users.Remove(user);
var result = await _context.SaveChangesAsync();
return result > 0;
}
// SAVE
public async Task<bool> SaveAsync()
{
var saved = await _context.SaveChangesAsync();
return saved > 0 ? true : false;
}
}
}

View File

@ -0,0 +1,131 @@
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Project.Application.DTOs.Auth;
using Project.Application.DTOs.Outgoing;
using Project.Application.Interfaces;
using System.Security.Claims;
namespace Project.Web.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class AuthController : ControllerBase
{
// FIELDS FOR CTOR
private readonly IUserService _userService;
private readonly IAuthService _authService;
// CTOR
public AuthController(IUserService userService, IAuthService authService)
{
_userService = userService;
_authService = authService;
}
// LOGIN
[AllowAnonymous]
[HttpPost("login")]
public async Task<IActionResult> Login([FromBody] LoginDto login)
{
var isValid = await _authService.ValidateAsync(login.Username, login.Password);
if (!isValid)
{
return Unauthorized();
}
var user = await _userService.GetByUsernameAsync(login.Username);
if (user == null)
{
return Unauthorized(user);
}
var claims = new List<Claim>
{
new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
new Claim(ClaimTypes.Name, user.UserName),
new Claim(ClaimTypes.Surname, user.LastName ?? ""),
new Claim(ClaimTypes.GivenName, user.FirstName ?? "")
};
var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
var authProperties = new AuthenticationProperties
{
IsPersistent = true,
AllowRefresh = true,
ExpiresUtc = DateTime.UtcNow.AddMinutes(60)
};
await HttpContext.SignInAsync(
CookieAuthenticationDefaults.AuthenticationScheme,
new ClaimsPrincipal(claimsIdentity),
authProperties
);
return Ok();
}
// LOGOUT
[HttpPost("logout")]
public async Task<IActionResult> Logout()
{
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
return Ok();
}
//// LOGIN
//[HttpPost("login")]
//public async Task<IActionResult> Login(LoginDto login)
//{
// var user = await _authService.AuthenticateAsync(login.Username, login.Password);
// if (user == null)
// {
// return Unauthorized();
// }
// var claims = new ClaimsIdentity(new[]
// {
// new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
// new Claim(ClaimTypes.Name, user.UserName)
// }, CookieAuthenticationDefaults.AuthenticationScheme);
// var authProperties = new AuthenticationProperties
// {
// IsPersistent = false,
// ExpiresUtc = DateTime.UtcNow.AddMinutes(10)
// };
// await HttpContext.SignInAsync(
// CookieAuthenticationDefaults.AuthenticationScheme,
// new ClaimsPrincipal(claims),
// authProperties);
// return Ok("Login successful");
//}
//// LOGOUT
//public async Task<IActionResult> Logout()
//{
// await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
// return Ok("Logout successful");
//}
}
}

View File

@ -8,7 +8,6 @@ namespace Project.Web.Controllers
[ApiController]
public class CategoryController : ControllerBase
{
// FIELDS FOR CTOR
private readonly ICategoryService _categoryService;
@ -25,19 +24,31 @@ namespace Project.Web.Controllers
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public async Task<IActionResult> CreateCategory([FromBody] CreatingCategoryDto creatingCategoryDto)
{
var result = await _categoryService.AddCategoryAsync(creatingCategoryDto);
if (result != null)
if (!ModelState.IsValid)
{
var id = result.Id;
var createdResource = new { Id = id };
var actionName = nameof(GetCategoryById);
var routeValue = new { id = createdResource.Id };
return CreatedAtAction(actionName, routeValue, createdResource);
return BadRequest(ModelState);
}
else
try
{
return BadRequest("geht nix");
var result = await _categoryService.AddCategoryAsync(creatingCategoryDto);
if (result != null)
{
var id = result.Id;
var createdResource = new { Id = id };
var actionName = nameof(GetCategoryById);
var routeValue = new { id = createdResource.Id };
return CreatedAtAction(actionName, routeValue, createdResource);
}
else
{
return BadRequest("geht nix");
}
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
}

View File

@ -2,23 +2,22 @@
using Microsoft.AspNetCore.Mvc;
using Project.Application.DTOs.Incoming;
using Project.Application.Interfaces;
using Project.Application.Services;
using System.Security.Claims;
namespace Project.Web.Controllers
{
[Route("api/[controller]")]
[ApiController]
[Authorize(Roles = "Admin")]
public class ProductController : ControllerBase
{
// FIELDS FOR CTOR
private readonly IProductService _productService;
private readonly IUserService _userService;
// CTOR
public ProductController(IProductService productService)
public ProductController(IProductService productService, IUserService userService)
{
_productService = productService;
_userService = userService;
}
// CREATE
@ -26,26 +25,48 @@ namespace Project.Web.Controllers
[ProducesResponseType(StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public async Task<IActionResult> CreateProduct([FromBody] CreatingProductDto creatingProductDto) // with form body
//[AllowAnonymous]
public async Task<IActionResult> CreateProduct([FromBody] CreatingProductDto creatingProductDto)
{
var result = await _productService.AddProductAsync(creatingProductDto);
if (result != null)
if (!ModelState.IsValid)
{
var id = result.Id;
var createdResource = new { Id = id };
var actionName = nameof(GetProductById);
var routeValue = new { id = createdResource.Id };
return CreatedAtAction(actionName, routeValue, createdResource);
return BadRequest(ModelState);
}
else
try
{
return BadRequest("geht nix");
var result = await _productService.AddProductAsync(creatingProductDto);
//---------
//var current_user = await GetUser();
//if (current_user is null)
// return Unauthorized();
//_productService.getbyUsername(current_user.UserName);
//----------
if (result != null)
{
var id = result.Id;
var createdResource = new { Id = id };
var actionName = nameof(GetProductById);
var routeValue = new { id = createdResource.Id };
return CreatedAtAction(actionName, routeValue, createdResource);
}
else
{
return BadRequest("geht nix");
}
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
}
// READ ALL
[Authorize(Roles ="Admin")]
//[Authorize(Roles = "Admin")] // Authorization
[HttpGet]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task<IActionResult> GetProducts()
@ -54,14 +75,6 @@ namespace Project.Web.Controllers
return Ok(products);
}
public async Task<IActionResult> GetProducts()
{
var id = User.FindFirst(ClaimTypes.NameIdentifier);
var products = await _productService.getproductbyuserid(id);
return Ok(products);
}
// READ BY ID
[HttpGet("id/{id}", Name = "GetProductById")]
[ProducesResponseType(StatusCodes.Status200OK)]
@ -120,5 +133,17 @@ namespace Project.Web.Controllers
await _productService.DeleteProductAsync(id);
return Ok();
}
//---------------
//async Task<ReadingUserDto?> GetUser()
//{
// var id_st = this.User.FindFirstValue(ClaimTypes.NameIdentifier);
// if (int.TryParse(id_st, out int id))
// return null;
// var user = await _userService.GetByIdAsync(id);
// return user;
//}
//--------------
}
}

View File

@ -0,0 +1,123 @@
using Microsoft.AspNetCore.Mvc;
using Project.Application.DTOs.Incoming;
using Project.Application.Interfaces;
namespace Project.Web.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class RoleController : ControllerBase
{
// FIELDS FOR CTOR
private readonly IRoleService _roleService;
// CTOR
public RoleController(IRoleService roleService)
{
_roleService = roleService;
}
// CREATE
[HttpPost]
[ProducesResponseType(StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public async Task<IActionResult> CreateRole([FromBody] CreatingRoleDto creatingRoleDto)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
try
{
var result = await _roleService.AddRoleAsync(creatingRoleDto);
if (result != null)
{
var id = result.Id;
var createdResource = new { Id = id };
var actionName = nameof(GetRoleById);
var routeValue = new { id = createdResource.Id };
return CreatedAtAction(actionName, routeValue, createdResource);
}
else
{
return BadRequest("geht nix");
}
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
}
// READ ALL
[HttpGet]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task<IActionResult> GetRoles()
{
var roles = await _roleService.GetAllAsync();
return Ok(roles);
}
// READ BY ID
[HttpGet("id/{id}", Name = "GetRoleById")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> GetRoleById(int id)
{
if (id <= 0)
{
return BadRequest("Invalid Id");
}
var role = await _roleService.GetByIdAsync(id);
if (role == null)
{
return NotFound();
}
return Ok(role);
}
// READ BY NAME
[HttpGet("name/{name}", Name = "GetRoleByName")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> GetRoleByName(string name)
{
if (string.IsNullOrEmpty(name))
{
return BadRequest("Name cannot be empty");
}
var role = await _roleService.GetByNameAsync(name);
if (role == null)
{
return NotFound();
}
return Ok(role);
}
// UPDATE
[HttpPut("id/{id}", Name = "UpdateRole")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public async Task<IActionResult> UpdateRole(int id, UpdatingRoleDto updatingRoleDto)
{
var updated = await _roleService.UpdateRoleAsync(updatingRoleDto);
return Ok(updated);
}
// DELETE
[HttpDelete("id/{id}", Name = "DeleteRole")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public async Task<IActionResult> DeleteRole([FromRoute] int id)
{
await _roleService.DeleteRoleAsync(id);
return Ok();
}
}
}

View File

@ -0,0 +1,125 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Project.Application.DTOs.Incoming;
using Project.Application.Interfaces;
namespace Project.Web.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class UserController : Controller
{
// FIELDS FOR CTOR
private readonly IUserService _userService;
// CTOR
public UserController(IUserService userService)
{
_userService = userService;
}
// CREATE
[HttpPost]
[ProducesResponseType(StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public async Task<IActionResult> CreateUser([FromBody] CreatingUserDto creatingUserDto)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
try
{
var result = await _userService.AddUserAsync(creatingUserDto);
if (result != null)
{
var id = result.Id;
var createdResource = new { Id = id };
var actionName = nameof(GetUserById);
var routeValue = new { id = createdResource.Id };
return CreatedAtAction(actionName, routeValue, createdResource);
}
else
{
return BadRequest("Creation failed");
}
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
}
// READ ALL
//[Authorize(Roles = "Admin")]
[HttpGet]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task<IActionResult> GetUsers()
{
var users = await _userService.GetUsersAsync();
return Ok(users);
}
// READ BY ID
[HttpGet("id/{id}", Name = "GetUserById")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> GetUserById(int id)
{
if (id <= 0)
{
return BadRequest("Invalid Id");
}
var user = await _userService.GetByIdAsync(id);
if (user == null)
{
return NotFound();
}
return Ok(user);
}
// READ BY USERNAME
[HttpGet("username/{username}", Name = "GetUserByUsername")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> GetUserByUsername(string username)
{
if (string.IsNullOrEmpty(username))
{
return BadRequest("Username connot be empty");
}
var user = await _userService.GetByUsernameAsync(username);
if(user == null)
{
return NotFound();
}
return Ok(user);
}
// UPDATE
[HttpPut("id/{id}", Name = "UpdateUser")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public async Task<IActionResult> UpdateUser(int id, UpdatingUserDto updatingUserDto)
{
var updated = await _userService.UpdateUserAsync(updatingUserDto);
return Ok(updated);
}
// DELETE
[HttpDelete("id/{id}", Name = "DeleteUser")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public async Task<IActionResult> DeleteProduct([FromBody] int id)
{
await _userService.DeleteUserAsync(id);
return Ok();
}
}
}

View File

@ -0,0 +1,212 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Project.Infrastructure;
#nullable disable
namespace Project.Web.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
[Migration("20240704072427_Sechste")]
partial class Sechste
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "8.0.6")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("Project.Domain.Entities.Category", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasColumnName("ID");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<DateTime>("CreationDate")
.HasColumnType("datetime")
.HasColumnName("CREATION_DATE");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(max)")
.HasColumnName("CATEGORY_NAME");
b.HasKey("Id");
b.ToTable("CATEGORY", "dbo");
});
modelBuilder.Entity("Project.Domain.Entities.CategoryRole", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasColumnName("ID");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("CategoryId")
.HasColumnType("int");
b.Property<int>("RoleId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("CategoryId");
b.HasIndex("RoleId");
b.ToTable("CATEGORY_ROLE", "dbo");
});
modelBuilder.Entity("Project.Domain.Entities.Product", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasColumnName("ID");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("CategoryId")
.HasColumnType("int");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(max)")
.HasColumnName("PRODUCT_NAME");
b.Property<decimal>("Price")
.HasColumnType("decimal(18,2)")
.HasColumnName("PRICE");
b.Property<int>("Quantity")
.HasColumnType("int")
.HasColumnName("QUANTITY");
b.HasKey("Id");
b.HasIndex("CategoryId");
b.ToTable("PRODUCT", "dbo");
});
modelBuilder.Entity("Project.Domain.Entities.Role", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasColumnName("ID");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<DateTime>("CreationDate")
.HasColumnType("datetime")
.HasColumnName("CREATION_DATE");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(max)")
.HasColumnName("ROLE");
b.HasKey("Id");
b.ToTable("ROLE", "dbo");
});
modelBuilder.Entity("Project.Domain.Entities.User", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasColumnName("ID");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("FirstName")
.IsRequired()
.HasColumnType("nvarchar(max)")
.HasColumnName("FIRST_NAME");
b.Property<string>("LastName")
.IsRequired()
.HasColumnType("nvarchar(max)")
.HasColumnName("LAST_NAME");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("nvarchar(max)")
.HasColumnName("PASSWORD");
b.Property<int>("RoleId")
.HasColumnType("int");
b.Property<string>("UserName")
.IsRequired()
.HasColumnType("nvarchar(max)")
.HasColumnName("USER_NAME");
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("USER", "dbo");
});
modelBuilder.Entity("Project.Domain.Entities.CategoryRole", b =>
{
b.HasOne("Project.Domain.Entities.Category", "Category")
.WithMany()
.HasForeignKey("CategoryId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Project.Domain.Entities.Role", "Role")
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Category");
b.Navigation("Role");
});
modelBuilder.Entity("Project.Domain.Entities.Product", b =>
{
b.HasOne("Project.Domain.Entities.Category", "Category")
.WithMany()
.HasForeignKey("CategoryId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Category");
});
modelBuilder.Entity("Project.Domain.Entities.User", b =>
{
b.HasOne("Project.Domain.Entities.Role", "Role")
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Role");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,31 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Project.Web.Migrations
{
/// <inheritdoc />
public partial class Sechste : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "PASSWORD",
schema: "dbo",
table: "USER",
type: "nvarchar(max)",
nullable: false,
defaultValue: "");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "PASSWORD",
schema: "dbo",
table: "USER");
}
}
}

View File

@ -0,0 +1,196 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Project.Infrastructure;
#nullable disable
namespace Project.Web.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
[Migration("20240704090025_Siebte")]
partial class Siebte
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "8.0.6")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("Project.Domain.Entities.Category", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasColumnName("ID");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<DateTime>("CreationDate")
.HasColumnType("datetime")
.HasColumnName("CREATION_DATE");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(max)")
.HasColumnName("CATEGORY_NAME");
b.HasKey("Id");
b.ToTable("CATEGORY", "dbo");
});
modelBuilder.Entity("Project.Domain.Entities.CategoryRole", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasColumnName("ID");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("CategoryId")
.HasColumnType("int");
b.Property<int>("RoleId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("CategoryId");
b.HasIndex("RoleId");
b.ToTable("CATEGORY_ROLE", "dbo");
});
modelBuilder.Entity("Project.Domain.Entities.Product", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasColumnName("ID");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("CategoryId")
.HasColumnType("int");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(max)")
.HasColumnName("PRODUCT_NAME");
b.Property<decimal>("Price")
.HasColumnType("decimal(18,2)")
.HasColumnName("PRICE");
b.Property<int>("Quantity")
.HasColumnType("int")
.HasColumnName("QUANTITY");
b.HasKey("Id");
b.HasIndex("CategoryId");
b.ToTable("PRODUCT", "dbo");
});
modelBuilder.Entity("Project.Domain.Entities.Role", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasColumnName("ID");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<DateTime>("CreationDate")
.HasColumnType("datetime")
.HasColumnName("CREATION_DATE");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(max)")
.HasColumnName("ROLE");
b.HasKey("Id");
b.ToTable("ROLE", "dbo");
});
modelBuilder.Entity("Project.Domain.Entities.User", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasColumnName("ID");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("FirstName")
.IsRequired()
.HasColumnType("nvarchar(max)")
.HasColumnName("FIRST_NAME");
b.Property<string>("LastName")
.IsRequired()
.HasColumnType("nvarchar(max)")
.HasColumnName("LAST_NAME");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("nvarchar(max)")
.HasColumnName("PASSWORD");
b.Property<string>("UserName")
.IsRequired()
.HasColumnType("nvarchar(max)")
.HasColumnName("USER_NAME");
b.HasKey("Id");
b.ToTable("USER", "dbo");
});
modelBuilder.Entity("Project.Domain.Entities.CategoryRole", b =>
{
b.HasOne("Project.Domain.Entities.Category", "Category")
.WithMany()
.HasForeignKey("CategoryId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Project.Domain.Entities.Role", "Role")
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Category");
b.Navigation("Role");
});
modelBuilder.Entity("Project.Domain.Entities.Product", b =>
{
b.HasOne("Project.Domain.Entities.Category", "Category")
.WithMany()
.HasForeignKey("CategoryId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Category");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,57 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Project.Web.Migrations
{
/// <inheritdoc />
public partial class Siebte : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_USER_ROLE_RoleId",
schema: "dbo",
table: "USER");
migrationBuilder.DropIndex(
name: "IX_USER_RoleId",
schema: "dbo",
table: "USER");
migrationBuilder.DropColumn(
name: "RoleId",
schema: "dbo",
table: "USER");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<int>(
name: "RoleId",
schema: "dbo",
table: "USER",
type: "int",
nullable: false,
defaultValue: 0);
migrationBuilder.CreateIndex(
name: "IX_USER_RoleId",
schema: "dbo",
table: "USER",
column: "RoleId");
migrationBuilder.AddForeignKey(
name: "FK_USER_ROLE_RoleId",
schema: "dbo",
table: "USER",
column: "RoleId",
principalSchema: "dbo",
principalTable: "ROLE",
principalColumn: "ID",
onDelete: ReferentialAction.Cascade);
}
}
}

View File

@ -0,0 +1,212 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Project.Infrastructure;
#nullable disable
namespace Project.Web.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
[Migration("20240705074345_Achte")]
partial class Achte
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "8.0.6")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("Project.Domain.Entities.Category", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasColumnName("ID");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<DateTime>("CreationDate")
.HasColumnType("datetime")
.HasColumnName("CREATION_DATE");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(max)")
.HasColumnName("CATEGORY_NAME");
b.HasKey("Id");
b.ToTable("CATEGORY", "dbo");
});
modelBuilder.Entity("Project.Domain.Entities.CategoryRole", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasColumnName("ID");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("CategoryId")
.HasColumnType("int");
b.Property<int>("RoleId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("CategoryId");
b.HasIndex("RoleId");
b.ToTable("CATEGORY_ROLE", "dbo");
});
modelBuilder.Entity("Project.Domain.Entities.Product", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasColumnName("ID");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("CategoryId")
.HasColumnType("int");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(max)")
.HasColumnName("PRODUCT_NAME");
b.Property<decimal>("Price")
.HasColumnType("decimal(18,2)")
.HasColumnName("PRICE");
b.Property<int>("Quantity")
.HasColumnType("int")
.HasColumnName("QUANTITY");
b.HasKey("Id");
b.HasIndex("CategoryId");
b.ToTable("PRODUCT", "dbo");
});
modelBuilder.Entity("Project.Domain.Entities.Role", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasColumnName("ID");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<DateTime>("CreationDate")
.HasColumnType("datetime")
.HasColumnName("CREATION_DATE");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(max)")
.HasColumnName("ROLE");
b.HasKey("Id");
b.ToTable("ROLE", "dbo");
});
modelBuilder.Entity("Project.Domain.Entities.User", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasColumnName("ID");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("FirstName")
.IsRequired()
.HasColumnType("nvarchar(max)")
.HasColumnName("FIRST_NAME");
b.Property<string>("LastName")
.IsRequired()
.HasColumnType("nvarchar(max)")
.HasColumnName("LAST_NAME");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("nvarchar(max)")
.HasColumnName("PASSWORD");
b.Property<int>("RoleId")
.HasColumnType("int");
b.Property<string>("UserName")
.IsRequired()
.HasColumnType("nvarchar(max)")
.HasColumnName("USER_NAME");
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("USER", "dbo");
});
modelBuilder.Entity("Project.Domain.Entities.CategoryRole", b =>
{
b.HasOne("Project.Domain.Entities.Category", "Category")
.WithMany()
.HasForeignKey("CategoryId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Project.Domain.Entities.Role", "Role")
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Category");
b.Navigation("Role");
});
modelBuilder.Entity("Project.Domain.Entities.Product", b =>
{
b.HasOne("Project.Domain.Entities.Category", "Category")
.WithMany()
.HasForeignKey("CategoryId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Category");
});
modelBuilder.Entity("Project.Domain.Entities.User", b =>
{
b.HasOne("Project.Domain.Entities.Role", "Role")
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Role");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,57 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Project.Web.Migrations
{
/// <inheritdoc />
public partial class Achte : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<int>(
name: "RoleId",
schema: "dbo",
table: "USER",
type: "int",
nullable: false,
defaultValue: 0);
migrationBuilder.CreateIndex(
name: "IX_USER_RoleId",
schema: "dbo",
table: "USER",
column: "RoleId");
migrationBuilder.AddForeignKey(
name: "FK_USER_ROLE_RoleId",
schema: "dbo",
table: "USER",
column: "RoleId",
principalSchema: "dbo",
principalTable: "ROLE",
principalColumn: "ID",
onDelete: ReferentialAction.Cascade);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_USER_ROLE_RoleId",
schema: "dbo",
table: "USER");
migrationBuilder.DropIndex(
name: "IX_USER_RoleId",
schema: "dbo",
table: "USER");
migrationBuilder.DropColumn(
name: "RoleId",
schema: "dbo",
table: "USER");
}
}
}

View File

@ -0,0 +1,212 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Project.Infrastructure;
#nullable disable
namespace Project.Web.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
[Migration("20240705115117_Neunte")]
partial class Neunte
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "8.0.6")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("Project.Domain.Entities.Category", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasColumnName("ID");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<DateTime>("CreationDate")
.HasColumnType("datetime")
.HasColumnName("CREATION_DATE");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(max)")
.HasColumnName("CATEGORY_NAME");
b.HasKey("Id");
b.ToTable("CATEGORY", "dbo");
});
modelBuilder.Entity("Project.Domain.Entities.CategoryRole", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasColumnName("ID");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("CategoryId")
.HasColumnType("int");
b.Property<int>("RoleId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("CategoryId");
b.HasIndex("RoleId");
b.ToTable("CATEGORY_ROLE", "dbo");
});
modelBuilder.Entity("Project.Domain.Entities.Product", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasColumnName("ID");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("CategoryId")
.HasColumnType("int");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(max)")
.HasColumnName("PRODUCT_NAME");
b.Property<decimal>("Price")
.HasColumnType("decimal(18,2)")
.HasColumnName("PRICE");
b.Property<int>("Quantity")
.HasColumnType("int")
.HasColumnName("QUANTITY");
b.HasKey("Id");
b.HasIndex("CategoryId");
b.ToTable("PRODUCT", "dbo");
});
modelBuilder.Entity("Project.Domain.Entities.Role", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasColumnName("ID");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<DateTime>("CreationDate")
.HasColumnType("datetime")
.HasColumnName("CREATION_DATE");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(max)")
.HasColumnName("ROLE");
b.HasKey("Id");
b.ToTable("ROLE", "dbo");
});
modelBuilder.Entity("Project.Domain.Entities.User", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasColumnName("ID");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("FirstName")
.IsRequired()
.HasColumnType("nvarchar(max)")
.HasColumnName("FIRST_NAME");
b.Property<string>("LastName")
.IsRequired()
.HasColumnType("nvarchar(max)")
.HasColumnName("LAST_NAME");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("nvarchar(max)")
.HasColumnName("PASSWORD");
b.Property<int>("RoleId")
.HasColumnType("int");
b.Property<string>("UserName")
.IsRequired()
.HasColumnType("nvarchar(max)")
.HasColumnName("USER_NAME");
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("USER", "dbo");
});
modelBuilder.Entity("Project.Domain.Entities.CategoryRole", b =>
{
b.HasOne("Project.Domain.Entities.Category", "Category")
.WithMany()
.HasForeignKey("CategoryId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Project.Domain.Entities.Role", "Role")
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Category");
b.Navigation("Role");
});
modelBuilder.Entity("Project.Domain.Entities.Product", b =>
{
b.HasOne("Project.Domain.Entities.Category", "Category")
.WithMany()
.HasForeignKey("CategoryId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Category");
});
modelBuilder.Entity("Project.Domain.Entities.User", b =>
{
b.HasOne("Project.Domain.Entities.Role", "Role")
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Role");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,22 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Project.Web.Migrations
{
/// <inheritdoc />
public partial class Neunte : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
}
}
}

View File

@ -143,6 +143,11 @@ namespace Project.Web.Migrations
.HasColumnType("nvarchar(max)")
.HasColumnName("LAST_NAME");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("nvarchar(max)")
.HasColumnName("PASSWORD");
b.Property<int>("RoleId")
.HasColumnType("int");

View File

@ -1,3 +1,4 @@
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.EntityFrameworkCore;
using Project.Application.Interfaces;
using Project.Application.MappingProfiles;
@ -23,12 +24,37 @@ builder.Services.AddScoped<IProductRepository, ProductRepository>();
builder.Services.AddScoped<ICategoryService, CategoryService>();
builder.Services.AddScoped<ICategoryRepository, CategoryRepository>();
builder.Services.AddScoped<IUserService, UserService>();
builder.Services.AddScoped<IUserRepository, UserRepository>();
builder.Services.AddScoped<IRoleService, RoleService>();
builder.Services.AddScoped<IRoleRepository, RoleRepository>();
builder.Services.AddScoped<IAuthService, AuthService>();
//builder.Services.AddScoped<IAuthRepository, AuthRepository>();
builder.Services.AddDbContext<ApplicationDbContext>(options =>
{
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"), b => b.MigrationsAssembly("Project.Web"));
});
builder.Services.AddMemoryCache();
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.Cookie.HttpOnly = true;
options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
options.Cookie.SameSite = SameSiteMode.Strict;
options.LoginPath = "/api/auth/login";
options.LogoutPath = "/api/auth/logout";
});
//builder.Services.AddAuthorization(options =>
//{
// options.AddPolicy("AdminOnly", policy =>
// policy.RequireRole("Admin"));
//});
builder.Logging.ClearProviders();
builder.Logging.AddConsole();
@ -43,6 +69,8 @@ if (app.Environment.IsDevelopment())
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();

View File

@ -7,6 +7,7 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.Cookies" Version="2.2.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.6" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="8.0.6" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="8.0.6">

View File

@ -2,7 +2,7 @@
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<ActiveDebugProfile>https</ActiveDebugProfile>
<Controller_SelectedScaffolderID>ApiControllerEmptyScaffolder</Controller_SelectedScaffolderID>
<Controller_SelectedScaffolderCategoryPath>root/Common/Api</Controller_SelectedScaffolderCategoryPath>
<Controller_SelectedScaffolderID>MvcControllerEmptyScaffolder</Controller_SelectedScaffolderID>
<Controller_SelectedScaffolderCategoryPath>root/Common/MVC/Controller</Controller_SelectedScaffolderCategoryPath>
</PropertyGroup>
</Project>