Compare commits

...

2 Commits

Author SHA1 Message Date
OlgunR
64f3dc2875 Cleaned up the architecture 2024-10-01 11:45:17 +02:00
OlgunR
3df98fb399 Added Logging + some little changes in repositories 2024-09-30 15:36:19 +02:00
11 changed files with 313 additions and 157 deletions

View File

@ -1,9 +1,6 @@
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Swashbuckle.AspNetCore.Annotations;
using System.Security.Claims;
using UserManagement.Application.Dtos.Auth;
using UserManagement.Application.Interfaces;
@ -16,75 +13,57 @@ namespace UserManagement.API.Controllers
// CTOR
private readonly IUserService _userService;
private readonly IAuthService _authService;
public AuthController(IUserService userService, IAuthService authService)
private readonly ILogger<AuthController> _logger;
public AuthController(IUserService userService, IAuthService authService, ILogger<AuthController> logger)
{
_userService = userService;
_authService = authService;
_logger = logger;
}
// LOGIN
[AllowAnonymous]
// SIGN IN
[HttpPost("login")]
[SwaggerOperation(Summary = "Login")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public async Task<IActionResult> Login([FromBody] LoginDto login)
{
// Validate user
var user = await _userService.GetByUsernameAsync(login.Username, includeRoles: true);
if (user is null)
try
{
return Unauthorized("Benutzername und Passwort stimmen nicht überein!");
await _authService.SignInAsync(login.Username, login.Password, HttpContext);
return Ok();
}
// Validate login credentials
var isValid = await _authService.ValidateAsync(login.Username, login.Password);
if (!isValid)
catch (UnauthorizedAccessException ex)
{
return Unauthorized("Benutzername und Passwort stimmen nicht überein!");
_logger.LogError(ex, ex.Message);
return Unauthorized(ex.Message);
}
// Create claims based on the user information
var claims = new List<Claim>
catch (Exception ex)
{
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 ?? ""),
};
foreach (var userRole in user.UserRoles)
{
claims.Add(new Claim(ClaimTypes.Role, userRole!.Name));
_logger.LogError(ex, ex.Message);
return StatusCode(StatusCodes.Status500InternalServerError);
}
// Create a ClaimsIdentity based on the created claims
var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
// Set the authentication properties
var authProperties = new AuthenticationProperties
{
IsPersistent = true,
AllowRefresh = true,
ExpiresUtc = DateTime.UtcNow.AddMinutes(60)
};
// Sign in user using cookie-based authentication
await HttpContext.SignInAsync(
CookieAuthenticationDefaults.AuthenticationScheme,
new ClaimsPrincipal(claimsIdentity),
authProperties
);
return Ok();
}
// LOGOUT
[HttpPost("logout")]
[SwaggerOperation(Summary = "Logout")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public async Task<IActionResult> Logout()
{
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
return Ok();
try
{
await _authService.SignOutAsync(HttpContext);
return Ok();
}
catch (Exception ex)
{
_logger.LogError(ex, ex.Message);
return StatusCode(StatusCodes.Status500InternalServerError);
}
}
// AUTH CHECK

View File

@ -13,9 +13,11 @@ namespace UserManagement.API.Controllers
{
// CTOR
private readonly IRoleService _roleService;
public RoleController(IRoleService roleService)
private readonly ILogger<UserController> _logger;
public RoleController(IRoleService roleService, ILogger<UserController> logger)
{
_roleService = roleService;
_logger = logger;
}
// CREATE
@ -26,7 +28,6 @@ namespace UserManagement.API.Controllers
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public async Task<IActionResult> CreateRole([FromBody] CreatingRoleDto creatingRoleDto)
{
// Validate incomming model
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
@ -34,25 +35,20 @@ namespace UserManagement.API.Controllers
try
{
// Try to add role asynchronously
var result = await _roleService.AddRoleAsync(creatingRoleDto);
var createdRole = await _roleService.AddRoleAsync(creatingRoleDto);
// If role is successfully created, return a CreatedAtAction response with the created resource
if (result is not null)
if (createdRole is not 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);
return CreatedAtAction(nameof(GetRoleById), new { id = createdRole.Id }, createdRole);
}
else
{
return BadRequest("geht nix");
return BadRequest("Erstellung der Rolle fehlgeschlagen!");
}
}
catch (Exception ex)
{
_logger.LogError(ex, ex.Message);
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
}
@ -61,95 +57,145 @@ namespace UserManagement.API.Controllers
[HttpGet]
[SwaggerOperation(Summary = "Get all Roles")]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task<IActionResult> GetRoles()
[ProducesResponseType(StatusCodes.Status404NotFound)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public async Task<IActionResult> GetAllRoles()
{
var roles = await _roleService.GetAllAsync();
return Ok(roles);
try
{
var roles = await _roleService.GetAllRolesAsync();
return Ok(roles);
}
catch (KeyNotFoundException ex)
{
return NotFound(ex.Message);
}
catch (Exception ex)
{
_logger.LogError(ex, ex.Message);
return StatusCode(StatusCodes.Status500InternalServerError);
}
}
// READ BY ID
[HttpGet("id/{id}", Name = "GetRoleById")]
[HttpGet("roleId/{id}", Name = "GetRoleById")]
[SwaggerOperation(Summary = "Get Role by Id")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> GetRoleById(int id)
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public async Task<IActionResult> GetRoleById([FromRoute] int id)
{
if (id <= 0)
try
{
return BadRequest("Invalid Id");
var role = await _roleService.GetRoleByIdAsync(id);
return Ok(role);
}
var role = await _roleService.GetByIdAsync(id);
if (role == null)
catch (ArgumentException ex)
{
return NotFound();
return BadRequest(ex.Message);
}
catch (KeyNotFoundException ex)
{
return NotFound(ex.Message);
}
catch (Exception ex)
{
_logger.LogError(ex, ex.Message);
return StatusCode(StatusCodes.Status500InternalServerError);
}
return Ok(role);
}
// READ BY NAME
[HttpGet("name/{name}", Name = "GetRoleByName")]
[HttpGet("rolename/{name}", Name = "GetRoleByName")]
[SwaggerOperation(Summary = "Get Role by Name")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> GetRoleByName(string name)
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public async Task<IActionResult> GetRoleByName([FromRoute] string name)
{
if (string.IsNullOrEmpty(name))
try
{
return BadRequest("Name cannot be empty");
var role = await _roleService.GetRoleByNameAsync(name);
return Ok(role);
}
var role = await _roleService.GetByNameAsync(name);
if (role == null)
catch (ArgumentException ex)
{
return NotFound();
return BadRequest(ex.Message);
}
catch (KeyNotFoundException ex)
{
return NotFound(ex.Message);
}
catch (Exception ex)
{
_logger.LogError(ex, ex.Message);
return StatusCode(StatusCodes.Status500InternalServerError);
}
return Ok(role);
}
// UPDATE
[HttpPut("id/{id}", Name = "UpdateRole")]
[HttpPut("roleId/{id}", Name = "UpdateRole")]
[SwaggerOperation(Summary = "Update Role")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public async Task<IActionResult> UpdateRole(int id, UpdatingRoleDto updatingRoleDto)
[ProducesResponseType(StatusCodes.Status404NotFound)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public async Task<IActionResult> UpdateRole([FromRoute] int id,[FromBody] UpdatingRoleDto updatingRoleDto)
{
if (id <= 0)
if (!ModelState.IsValid)
{
return BadRequest("Invalid Id");
return BadRequest(ModelState);
}
var updated = await _roleService.UpdateRoleAsync(updatingRoleDto);
if (!updated)
try
{
return BadRequest("Update failed");
var updated = await _roleService.UpdateRoleAsync(updatingRoleDto);
return NoContent();
}
catch (ArgumentException ex)
{
return BadRequest(ex.Message);
}
catch (KeyNotFoundException ex)
{
return NotFound(ex.Message);
}
catch (Exception ex)
{
_logger.LogError(ex, ex.Message);
return StatusCode(StatusCodes.Status500InternalServerError);
}
return Ok(updated);
}
// DELETE
[HttpDelete("id/{id}", Name = "DeleteRole")]
[HttpDelete("roleId/{id}", Name = "DeleteRole")]
[SwaggerOperation(Summary = "Delete Role")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public async Task<IActionResult> DeleteRole([FromRoute] int id)
{
if (id <= 0)
try
{
return BadRequest("Invalid Id");
var deleted = await _roleService.DeleteRoleAsync(id);
return NoContent();
}
var deleted = await _roleService.DeleteRoleAsync(id);
if (!deleted)
catch (ArgumentException ex)
{
return BadRequest("Deletion failed");
return BadRequest(ex.Message);
}
catch (KeyNotFoundException ex)
{
return NotFound(ex.Message);
}
catch (Exception ex)
{
_logger.LogError(ex, ex.Message);
return StatusCode(StatusCodes.Status500InternalServerError);
}
return Ok();
}
}
}

View File

@ -8,7 +8,7 @@ namespace UserManagement.API.Controllers
{
[Route("api/[controller]")]
[ApiController]
//[Authorize(Roles = "Admin")]
[Authorize(Roles = "Admin")]
public class UserController : Controller
{
// CTOR
@ -26,7 +26,6 @@ namespace UserManagement.API.Controllers
[ProducesResponseType(StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
[Authorize(Roles = "Admin")]
public async Task<IActionResult> CreateUser([FromBody] CreatingUserDto creatingUserDto)
{
if (!ModelState.IsValid)
@ -49,7 +48,8 @@ namespace UserManagement.API.Controllers
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
_logger.LogError(ex, ex.Message);
return StatusCode(StatusCodes.Status500InternalServerError);
}
}
@ -58,30 +58,37 @@ namespace UserManagement.API.Controllers
[SwaggerOperation(Summary = "Get all Users")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public async Task<IActionResult> GetAllUsers([FromQuery] bool includeRoles = true)
{
try
{
var users = await _userService.GetUsersAsync(includeRoles);
var users = await _userService.GetAllUsersAsync(includeRoles);
return Ok(users);
}
catch (KeyNotFoundException ex)
{
return NotFound(ex.Message);
}
catch (Exception ex)
{
_logger.LogError(ex, ex.Message);
return StatusCode(StatusCodes.Status500InternalServerError);
}
}
// READ BY ID
[HttpGet("id/{id}", Name = "GetUserById")]
[HttpGet("userId/{id}", Name = "GetUserById")]
[SwaggerOperation(Summary = "Get User by Id")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> GetUserById(int id, [FromQuery] bool includeRoles = true)
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public async Task<IActionResult> GetUserById([FromRoute] int id, [FromQuery] bool includeRoles = true)
{
try
{
var user = await _userService.GetByIdAsync(id, includeRoles);
var user = await _userService.GetUserByIdAsync(id, includeRoles);
return Ok(user);
}
catch (ArgumentException ex)
@ -92,6 +99,11 @@ namespace UserManagement.API.Controllers
{
return NotFound(ex.Message);
}
catch (Exception ex)
{
_logger.LogError(ex, ex.Message);
return StatusCode(StatusCodes.Status500InternalServerError);
}
}
// READ BY USERNAME
@ -100,11 +112,12 @@ namespace UserManagement.API.Controllers
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> GetUserByUsername(string username, [FromQuery] bool includeRoles = true)
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public async Task<IActionResult> GetUserByUsername([FromRoute] string username, [FromQuery] bool includeRoles = true)
{
try
{
var user = await _userService.GetByUsernameAsync(username, includeRoles);
var user = await _userService.GetUserByUsernameAsync(username, includeRoles);
return Ok(user);
}
catch (ArgumentException ex)
@ -115,6 +128,11 @@ namespace UserManagement.API.Controllers
{
return NotFound(ex.Message);
}
catch (Exception ex)
{
_logger.LogError(ex, ex.Message);
return StatusCode(StatusCodes.Status500InternalServerError);
}
}
// READ BY ROLE
@ -123,11 +141,12 @@ namespace UserManagement.API.Controllers
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> GetUsersByRole(string role)
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public async Task<IActionResult> GetUsersByRole([FromRoute] string role)
{
try
{
var users = await _userService.GetByRoleAsync(role);
var users = await _userService.GetUsersByRoleAsync(role);
return Ok(users);
}
catch (ArgumentException ex)
@ -138,20 +157,31 @@ namespace UserManagement.API.Controllers
{
return NotFound(ex.Message);
}
catch (Exception ex)
{
_logger.LogError(ex, ex.Message);
return StatusCode(StatusCodes.Status500InternalServerError);
}
}
// UPDATE
[HttpPut("id/{id}", Name = "UpdateUser")]
[HttpPut("userId/{id}", Name = "UpdateUser")]
[SwaggerOperation(Summary = "Update User")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public async Task<IActionResult> UpdateUser(int id, UpdatingUserDto updatingUserDto)
public async Task<IActionResult> UpdateUser([FromRoute] int id, [FromBody] UpdatingUserDto updatingUserDto)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
try
{
var updated = await _userService.UpdateUserAsync(updatingUserDto);
return Ok(updated);
return NoContent();
}
catch (ArgumentException ex)
{
@ -169,17 +199,18 @@ namespace UserManagement.API.Controllers
}
// DELETE
[HttpDelete("id/{id}", Name = "DeleteUser")]
[HttpDelete("userId/{id}", Name = "DeleteUser")]
[SwaggerOperation(Summary = "Delete User")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public async Task<IActionResult> DeleteUser([FromBody] int id)
[ProducesResponseType(StatusCodes.Status404NotFound)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public async Task<IActionResult> DeleteUser([FromRoute] int id)
{
try
{
var deleted = await _userService.DeleteUserAsync(id);
return Ok(deleted);
return NoContent();
}
catch (ArgumentException ex)
{
@ -189,6 +220,11 @@ namespace UserManagement.API.Controllers
{
return NotFound(ex.Message);
}
catch (Exception ex)
{
_logger.LogError(ex, ex.Message);
return StatusCode(StatusCodes.Status500InternalServerError);
}
}
}
}

View File

@ -1,8 +1,15 @@
namespace UserManagement.Application.Interfaces
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
namespace UserManagement.Application.Interfaces
{
public interface IAuthService
{
// AUTHENTICATE
Task<bool> ValidateAsync(string username, string password);
// SIGN IN
Task<ClaimsPrincipal> SignInAsync(string username, string password, HttpContext httpContext);
// SIGN OUT
Task SignOutAsync(HttpContext httpContext);
}
}

View File

@ -10,13 +10,13 @@ namespace UserManagement.Application.Interfaces
Task<Role?> AddRoleAsync(CreatingRoleDto creatingRoleDto);
// READ ALL
Task<IEnumerable<ReadingRoleDto>> GetAllAsync();
Task<IEnumerable<ReadingRoleDto>> GetAllRolesAsync();
// READ BY ID
Task<ReadingRoleDto> GetByIdAsync(int id);
Task<ReadingRoleDto> GetRoleByIdAsync(int id);
// READ BY NAME
Task<ReadingRoleDto> GetByNameAsync(string name);
Task<ReadingRoleDto> GetRoleByNameAsync(string name);
// UPDATE
Task<bool> UpdateRoleAsync(UpdatingRoleDto updatingRoleDto);

View File

@ -10,16 +10,16 @@ namespace UserManagement.Application.Interfaces
Task<User?> AddUserAsync(CreatingUserDto creatingUserDto);
// READ ALL
Task<IEnumerable<ReadingUserDto>> GetUsersAsync(bool includeRoles = true);
Task<IEnumerable<ReadingUserDto>> GetAllUsersAsync(bool includeRoles = true);
// READ BY ID
Task<ReadingUserDto> GetByIdAsync(int id, bool includeRoles = true);
Task<ReadingUserDto> GetUserByIdAsync(int id, bool includeRoles = true);
// READ BY USERNAME
Task<ReadingUserDto> GetByUsernameAsync(string username, bool includeRoles = true);
Task<ReadingUserDto> GetUserByUsernameAsync(string username, bool includeRoles = true);
// READ BY ROLE
Task<IEnumerable<ReadingUserDto>> GetByRoleAsync(string role);
Task<IEnumerable<ReadingUserDto>> GetUsersByRoleAsync(string role);
// UPDATE
Task<bool> UpdateUserAsync(UpdatingUserDto updatingUserDto);

View File

@ -1,4 +1,8 @@
using UserManagement.Application.Interfaces;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Http;
using System.Security.Claims;
using UserManagement.Application.Interfaces;
using UserManagement.Infrastructure.Interfaces;
namespace UserManagement.Application.Services
@ -12,12 +16,46 @@ namespace UserManagement.Application.Services
_userRepository = userRepository;
}
// AUTHENTICATE
public async Task<bool> ValidateAsync(string username, string password)
// LOGIN
public async Task<ClaimsPrincipal> SignInAsync(string username, string password, HttpContext httpContext)
{
var user = await _userRepository.GetByUsernameAsync(username, includeRoles: true);
return BCrypt.Net.BCrypt.Verify(password, user!.PasswordHash);
if (user == null || !BCrypt.Net.BCrypt.Verify(password, user.PasswordHash))
{
throw new UnauthorizedAccessException("Benutzername und Passwort stimmen nicht überein!");
}
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 ?? "")
};
claims.AddRange(user.UserRoles.Select(role => new Claim(ClaimTypes.Role, role.Role.Name)));
var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
var authProperties = new AuthenticationProperties
{
IsPersistent = true,
AllowRefresh = true,
ExpiresUtc = DateTime.UtcNow.AddMinutes(60)
};
var principal = new ClaimsPrincipal(claimsIdentity);
await httpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal, authProperties);
return principal;
}
// LOGOUT
public async Task SignOutAsync(HttpContext httpContext)
{
await httpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
}
}
}

View File

@ -22,51 +22,103 @@ namespace UserManagement.Application.Services
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()
public async Task<IEnumerable<ReadingRoleDto>> GetAllRolesAsync()
{
var roles = await _roleRepository.GetAllAsync();
if (roles == null)
{
throw new KeyNotFoundException("Keine Rollen gefunden!");
}
var readDto = _mapper.Map<IEnumerable<ReadingRoleDto>>(roles);
return readDto;
}
// READ BY ID
public async Task<ReadingRoleDto> GetByIdAsync(int id)
public async Task<ReadingRoleDto> GetRoleByIdAsync(int id)
{
if (id <= 0)
{
throw new ArgumentException("Ungültige Id!");
}
var role = await _roleRepository.GetByIdAsync(id);
if (role == null)
{
throw new KeyNotFoundException("Rolle nicht gefunden!");
}
var readDto = _mapper.Map<ReadingRoleDto>(role);
return readDto;
}
// READ BY NAME
public async Task<ReadingRoleDto> GetByNameAsync(string name)
public async Task<ReadingRoleDto> GetRoleByNameAsync(string name)
{
if (string.IsNullOrEmpty(name))
{
throw new ArgumentException("Ungültiger Rollenname!");
}
var role = await _roleRepository.GetByNameAsync(name);
if (role == null)
{
throw new KeyNotFoundException("Rolle nicht gefunden!");
}
var readDto = _mapper.Map<ReadingRoleDto>(role);
return readDto;
}
// UPDATE
public async Task<bool> UpdateRoleAsync(UpdatingRoleDto updatingRoleDto)
{
if (updatingRoleDto.Id <= 0)
{
throw new ArgumentException("Ungültige Id!");
}
var role = _mapper.Map<Role>(updatingRoleDto);
if (role == null)
{
throw new KeyNotFoundException("Rolle nicht gefunden!");
}
bool isUpdated = await _roleRepository.UpdateAsync(role);
return isUpdated;
}
// DELETE
public async Task<bool> DeleteRoleAsync(int id)
{
Role? role = await _roleRepository.GetByIdAsync(id);
if (id <= 0)
{
throw new ArgumentException("Ungültige Id!");
}
if (role is null)
return false;
var role = await _roleRepository.GetByIdAsync(id);
if (role == null)
{
throw new KeyNotFoundException("Rolle nicht gefunden!");
}
bool isDeleted = await _roleRepository.DeleteAsync(role);
return isDeleted;
}
}

View File

@ -36,7 +36,7 @@ namespace UserManagement.Application.Services
}
// READ ALL
public async Task<IEnumerable<ReadingUserDto>> GetUsersAsync(bool includeRoles = true)
public async Task<IEnumerable<ReadingUserDto>> GetAllUsersAsync(bool includeRoles = true)
{
var users = await _userRepository.GetAllAsync(includeRoles);
@ -51,7 +51,7 @@ namespace UserManagement.Application.Services
}
// READ BY ID
public async Task<ReadingUserDto> GetByIdAsync(int id, bool includeRoles = true)
public async Task<ReadingUserDto> GetUserByIdAsync(int id, bool includeRoles = true)
{
if (id <= 0)
{
@ -71,7 +71,7 @@ namespace UserManagement.Application.Services
}
// READ BY USERNAME
public async Task<ReadingUserDto> GetByUsernameAsync(string username, bool includeRoles = true)
public async Task<ReadingUserDto> GetUserByUsernameAsync(string username, bool includeRoles = true)
{
if (string.IsNullOrEmpty(username))
{
@ -91,7 +91,7 @@ namespace UserManagement.Application.Services
}
// READ BY ROLE
public async Task<IEnumerable<ReadingUserDto>> GetByRoleAsync(string role)
public async Task<IEnumerable<ReadingUserDto>> GetUsersByRoleAsync(string role)
{
if (string.IsNullOrEmpty(role))
{

View File

@ -24,19 +24,25 @@ namespace UserManagement.Infrastructure.Repositories
// READ ALL
public async Task<IEnumerable<Role>> GetAllAsync()
{
return await _context.Roles.ToListAsync();
return await _context.Roles
.AsNoTracking()
.ToListAsync();
}
// READ BY ID
public async Task<Role?> GetByIdAsync(int id)
{
return await _context.Roles.FindAsync(id);
return await _context.Roles
.AsNoTracking()
.FirstOrDefaultAsync(r => r.Id == id);
}
// READ BY NAME
public async Task<Role?> GetByNameAsync(string name)
{
return await _context.Roles.FirstOrDefaultAsync(n => n.Name == name);
return await _context.Roles
.AsNoTracking()
.FirstOrDefaultAsync(n => n.Name == name);
}
// UPDATE

View File

@ -37,13 +37,10 @@ namespace UserManagement.Infrastructure.Repositories
{
var query = _context.Users.AsNoTracking();
if (id > 0)
query = query.Where(u => u.Id == id);
if (includeRoles)
query = query.Include(user => user.UserRoles)!.ThenInclude(ur => ur.Role);
return await query.FirstOrDefaultAsync();
return await query.FirstOrDefaultAsync(u => u.Id == id);
}
// READ BY USERNAME
@ -51,13 +48,10 @@ namespace UserManagement.Infrastructure.Repositories
{
var query = _context.Users.AsNoTracking();
if (!string.IsNullOrEmpty(username))
query = query.Where(u => u.UserName == username);
if (includeRoles)
query = query.Include(user => user.UserRoles)!.ThenInclude(ur => ur.Role);
return await query.FirstOrDefaultAsync();
return await query.FirstOrDefaultAsync(u => u.UserName == username);
}
// READ BY ROLE
@ -68,8 +62,6 @@ namespace UserManagement.Infrastructure.Repositories
.ThenInclude(ur => ur.Role)
.Where(ur => ur.UserRoles!.Any(r => r.Role!.Name == role));
var sql = query.ToQueryString();
return await query.ToListAsync();
}