#nullable disable
using CORE.Models;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Users.APP.Features.Users;
//Generated from Custom Microservices Template.
namespace Users.API.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class UsersController : ControllerBase
{
private readonly ILogger<UsersController> _logger;
private readonly IMediator _mediator;
// Constructor: injects logger to log the errors to Kestrel Console or Output Window and mediator
public UsersController(ILogger<UsersController> logger, IMediator mediator)
{
_logger = logger;
_mediator = mediator;
}
// GET: api/Users
[HttpGet]
[Authorize] // Only authenticated users can execute this action.
public async Task<IActionResult> Get()
{
try
{
// Send a query request to get query response
var response = await _mediator.Send(new UserQueryRequest());
// Convert the query response to a list
var list = await response.ToListAsync();
// If there are items, return them with 200 OK
if (list.Any())
return Ok(list);
// If no items found, return 204 No Content
return NoContent();
}
catch (Exception exception)
{
// Log the exception
_logger.LogError("UsersGet Exception: " + exception.Message);
// Return 500 Internal Server Error with an error command response with message
return StatusCode(StatusCodes.Status500InternalServerError, new CommandResponse(false, "An exception occured during UsersGet."));
}
}
// GET: api/Users/5
[HttpGet("{id}")]
[Authorize] // Only authenticated users can execute this action.
public async Task<IActionResult> Get(int id)
{
try
{
// Check if the user is in Admin role or trying to make
// the operation on his/her own account.
if (!IsOwnAccount(id) && !User.IsInRole("Admin"))
return BadRequest("You are not authorized for this operation!");
// Send a query request to get query response
var response = await _mediator.Send(new UserQueryRequest());
// Find the item with the given id
var item = await response.SingleOrDefaultAsync(r => r.Id == id);
// If item found, return it with 200 OK
if (item is not null)
return Ok(item);
// If item not found, return 204 No Content
return NoContent();
}
catch (Exception exception)
{
// Log the exception
_logger.LogError("UsersGetById Exception: " + exception.Message);
// Return 500 Internal Server Error with an error command response
// with message
return StatusCode(StatusCodes.Status500InternalServerError,
new CommandResponse(false, "An exception occured during UsersGetById."));
}
}
// POST: api/Users
[HttpPost]
[Authorize(Roles = "Admin")]
// Only authenticated users with role Admin can execute this action.
public async Task<IActionResult> Post(UserAddRequest request)
{
try
{
// Check if the request model is valid through data annotations
if (ModelState.IsValid)
{
// Send the create request
var response = await _mediator.Send(request);
// If creation is successful, return 200 OK with success command response
if (response.IsSuccessful)
{
//return CreatedAtAction(nameof(Get), new { id = response.Id }, response);
return Ok(response);
}
// If creation failed, add error command response message to model state
ModelState.AddModelError("UsersPost", response.Message);
}
// Return 400 Bad Request with all data annotation validation error messages and the error command response message if added seperated by |
return BadRequest(new CommandResponse(false, string.Join("|", ModelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage))));
}
catch (Exception exception)
{
// Log the exception
_logger.LogError("UsersPost Exception: " + exception.Message);
// Return 500 Internal Server Error with an error command response with message
return StatusCode(StatusCodes.Status500InternalServerError, new CommandResponse(false, "An exception occured during UsersPost."));
}
}
// PUT: api/Users
[HttpPut]
[Authorize] // Only authenticated users can execute this action.
public async Task<IActionResult> Put(UserUpdateRequest request)
{
try
{
// Check if the user is in Admin role or trying to make
// the operation on his/her own account.
if (!IsOwnAccount(request.Id) && !User.IsInRole("Admin"))
return BadRequest("You are not authorized for this operation!");
// Check if the request model is valid through data annotations
if (ModelState.IsValid)
{
// Send the update request
var response = await _mediator.Send(request);
// If update is successful, return 200 OK with success command response
if (response.IsSuccessful)
{
//return NoContent();
return Ok(response);
}
// If update failed, add error command response message to model state
ModelState.AddModelError("UsersPut", response.Message);
}
// Return 400 Bad Request with all data annotation validation
// error messages and the error command response message if added
// seperated by |
return BadRequest(new CommandResponse(false, string.Join("|",
ModelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage))));
}
catch (Exception exception)
{
// Log the exception
_logger.LogError("UsersPut Exception: " + exception.Message);
// Return 500 Internal Server Error with an error command response
// with message
return StatusCode(StatusCodes.Status500InternalServerError,
new CommandResponse(false, "An exception occured during UsersPut."));
}
}
// DELETE: api/Users/5
[HttpDelete("{id}")]
[Authorize] // Only authenticated users can execute this action.
public async Task<IActionResult> Delete(int id)
{
try
{
// Check if the user is in Admin role or trying to make
// the operation on his/her own account.
if (!IsOwnAccount(id) && !User.IsInRole("Admin"))
return BadRequest("You are not authorized for this operation!");
// Send the delete request
var response = await _mediator.Send(new UserRemoveRequest() { Id = id });
// If delete is successful, return 200 OK with success command response
if (response.IsSuccessful)
{
//return NoContent();
return Ok(response);
}
// If delete failed, add error command response message to model state
ModelState.AddModelError("UsersDelete", response.Message);
// Return 400 Bad Request with the error command response message
return BadRequest(new CommandResponse(false, string.Join("|",
ModelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage))));
}
catch (Exception exception)
{
// Log the exception
_logger.LogError("UsersDelete Exception: " + exception.Message);
// Return 500 Internal Server Error with an error command response
// with message
return StatusCode(StatusCodes.Status500InternalServerError,
new CommandResponse(false, "An exception occured during UsersDelete."));
}
}
/// <summary>
/// For regular users can only make operations on their own accounts.
/// </summary>
/// <param name="id">User ID.</param>
/// <returns>bool</returns>
bool IsOwnAccount(int id) // private is default if not written
{
// getting the authenticated user ID value for the claim type
// "Id" from the user's claims and checking if it matches
// the provided id parameter of a user
return id.ToString() == (User.Claims.SingleOrDefault(
claim => claim.Type == "Id")?.Value ?? string.Empty);
}
}
}