Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: refactoring of BE #134

Merged
merged 2 commits into from
Dec 13, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 13 additions & 29 deletions src/deskstar-backend/Deskstar/Controllers/BookingController.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
using System.IdentityModel.Tokens.Jwt;
using Deskstar.Core;
using Deskstar.Models;
using Deskstar.Usecases;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Net.Http.Headers;

namespace Deskstar.Controllers;

Expand All @@ -14,11 +13,13 @@ public class BookingController : ControllerBase
{
private readonly IBookingUsecases _bookingUsecases;
private readonly ILogger<BookingController> _logger;
private readonly IAutoMapperConfiguration _autoMapperConfiguration;

public BookingController(ILogger<BookingController> logger, IBookingUsecases bookingUsecases)
public BookingController(ILogger<BookingController> logger, IBookingUsecases bookingUsecases, IAutoMapperConfiguration autoMapperConfiguration)
{
_logger = logger;
_bookingUsecases = bookingUsecases;
_autoMapperConfiguration = autoMapperConfiguration;
}


Expand All @@ -32,8 +33,8 @@ public BookingController(ILogger<BookingController> logger, IBookingUsecases boo
/// </remarks>
///
/// <response code="200">Returns the booking list</response>
/// <response code="500">Internal Server Error</response>
/// <response code="400">Bad Request</response>
/// <response code="500">Internal Server Error</response>
[HttpGet("range")]
[Authorize]
[ProducesResponseType(typeof(List<ExtendedBooking>), StatusCodes.Status200OK)]
Expand All @@ -42,10 +43,7 @@ public BookingController(ILogger<BookingController> logger, IBookingUsecases boo
[Produces("application/json")]
public IActionResult GetBookingsByDirection(int n = int.MaxValue, int skip = 0, string direction = "DESC", long start = 0, long end = 0)
{
var accessToken = Request.Headers[HeaderNames.Authorization].ToString().Replace("Bearer ", string.Empty);
var handler = new JwtSecurityTokenHandler();
var jwtSecurityToken = handler.ReadJwtToken(accessToken);
var userId = new Guid(jwtSecurityToken.Claims.First(claim => claim.Type == JwtRegisteredClaimNames.NameId).Value);
var userId = RequestInteractions.ExtractIdFromRequest(Request);

DateTime startDateTime;
DateTime endDateTime;
Expand Down Expand Up @@ -90,19 +88,10 @@ public IActionResult GetBookingsByDirection(int n = int.MaxValue, int skip = 0,
try
{
var bookings = _bookingUsecases.GetFilteredBookings(userId, n, skip, direction, startDateTime, endDateTime);
var mapped = bookings.Select(
(b) =>
{
ExtendedBooking rb = new ExtendedBooking();
rb.Timestamp = b.Timestamp;
rb.StartTime = b.StartTime;
rb.EndTime = b.EndTime;
rb.BuildingName = b.Desk.Room.Floor.Building.BuildingName;
rb.FloorName = b.Desk.Room.Floor.FloorName;
rb.RoomName = b.Desk.Room.RoomName;
rb.DeskName = b.Desk.DeskName;
return rb;
}).ToList();

var mapper = _autoMapperConfiguration.GetConfiguration().CreateMapper();
var mapped = bookings.Select((b) => mapper.Map<Entities.Booking, ExtendedBooking>(b)).ToList();

return Ok(mapped);
}
catch (Exception e)
Expand Down Expand Up @@ -131,10 +120,7 @@ public IActionResult GetBookingsByDirection(int n = int.MaxValue, int skip = 0,
[Produces("application/json")]
public IActionResult RecentBookings()
{
var accessToken = Request.Headers[HeaderNames.Authorization].ToString().Replace("Bearer ", string.Empty);
var handler = new JwtSecurityTokenHandler();
var jwtSecurityToken = handler.ReadJwtToken(accessToken);
var userId = new Guid(jwtSecurityToken.Claims.First(claim => claim.Type == JwtRegisteredClaimNames.NameId).Value);
var userId = RequestInteractions.ExtractIdFromRequest(Request);
try
{
var bookings = _bookingUsecases.GetRecentBookings(userId);
Expand Down Expand Up @@ -178,10 +164,8 @@ public IActionResult CreateBooking([FromBody] BookingRequest bookingRequest)
return BadRequest("Required fields are missing");
}

var accessToken = Request.Headers[HeaderNames.Authorization].ToString().Replace("Bearer ", string.Empty);
var handler = new JwtSecurityTokenHandler();
var jwtSecurityToken = handler.ReadJwtToken(accessToken);
var userId = new Guid(jwtSecurityToken.Claims.First(claim => claim.Type == JwtRegisteredClaimNames.NameId).Value);
var userId = RequestInteractions.ExtractIdFromRequest(Request);

//ToDo: require Frontend to Use Universaltime
bookingRequest.StartTime = bookingRequest.StartTime.ToLocalTime();
bookingRequest.EndTime = bookingRequest.EndTime.ToLocalTime();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,6 @@ namespace Deskstar.Controllers;
[Produces("text/plain")]
public class HealthCheckController : ControllerBase
{


private readonly ILogger<HealthCheckController> _logger;

public HealthCheckController(ILogger<HealthCheckController> logger)
Expand All @@ -35,7 +33,6 @@ public string Auth()
[Authorize(Policy = "Admin")]
public string Admin()
{

return "you are an admin";
}
}
11 changes: 3 additions & 8 deletions src/deskstar-backend/Deskstar/Controllers/ResourcesController.cs
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
using System.IdentityModel.Tokens.Jwt;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Net.Http.Headers;
using Deskstar.Usecases;
using Deskstar.Models;
using Deskstar.Core;

namespace Deskstar.Controllers;

[ApiController]
[Route("/resources")]
[Produces("text/plain")]
[Produces("application/json")]
public class ResourcesController : ControllerBase
{
private readonly IResourceUsecases _resourceUsecases;
Expand Down Expand Up @@ -39,11 +38,7 @@ public ResourcesController(ILogger<ResourcesController> logger, IResourceUsecase
[Produces("application/json")]
public IActionResult GetAllBuildings()
{
var accessToken = Request.Headers[HeaderNames.Authorization].ToString().Replace("Bearer ", string.Empty);
var handler = new JwtSecurityTokenHandler();
var jwtSecurityToken = handler.ReadJwtToken(accessToken);
var userId =
new Guid(jwtSecurityToken.Claims.First(claim => claim.Type == JwtRegisteredClaimNames.NameId).Value);
var userId = RequestInteractions.ExtractIdFromRequest(Request);
List<CurrentBuilding> buildings;
try
{
Expand Down
79 changes: 57 additions & 22 deletions src/deskstar-backend/Deskstar/Controllers/UserController.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
using Deskstar.Core;
using Deskstar.Entities;
using Deskstar.Models;
using Deskstar.Entities;
using Deskstar.Usecases;
using Microsoft.AspNetCore.Authorization;
using Deskstar.Core.Exceptions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;

namespace Deskstar.Controllers;

Expand Down Expand Up @@ -33,29 +34,30 @@ public UserController(ILogger<UserController> logger, IUserUsecases userUsecases
/// </remarks>
///
/// <response code="200">List of user information in JSON Format</response>
/// <response code="404">Not Found</response>
/// <response code="500">Internal Server Error</response>
/// <response code="400">Bad Request</response>
[HttpGet]
[Authorize(Policy = "Admin")]
[ProducesResponseType(typeof(UserProfileDto), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
[Produces("application/json")]
public IActionResult Get()
{
var userId = RequestInteractions.ExtractIdFromRequest(Request);
var adminId = RequestInteractions.ExtractIdFromRequest(Request);
try
{
var entities = _userUsecases.ReadAllUsers(userId);
var entities = _userUsecases.ReadAllUsers(adminId);

var mapper = _autoMapperConfiguration.GetConfiguration().CreateMapper();
var users = entities.Select<User, UserProfileDto>(user => mapper.Map<User, UserProfileDto>(user)).ToList();

return Ok(users);
}
catch (ArgumentException e)
catch (EntityNotFoundException e)
{
_logger.LogError(e, e.Message);
return Problem(detail: e.Message, statusCode: 400);
return NotFound(e.Message);
}
catch (Exception e)
{
Expand All @@ -73,12 +75,12 @@ public IActionResult Get()
/// </remarks>
///
/// <response code="200">Returns information about the logged in user</response>
/// <response code="404">Not Found</response>
/// <response code="500">Internal Server Error</response>
/// <response code="400">Bad Request</response>
[HttpGet("me")]
[Authorize]
[ProducesResponseType(typeof(UserProfileDto), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
[Produces("application/json")]
public IActionResult GetMe()
Expand All @@ -88,14 +90,16 @@ public IActionResult GetMe()
try
{
var me = _userUsecases.ReadSpecificUser(userId);

var mapper = _autoMapperConfiguration.GetConfiguration().CreateMapper();
var UserProfileDto = mapper.Map<Entities.User, UserProfileDto>(me);

return Ok(UserProfileDto);
}
catch (ArgumentException e)
catch (EntityNotFoundException e)
{
_logger.LogError(e, e.Message);
return Problem(detail: e.Message, statusCode: 400);
return NotFound(e.Message);
}
catch (Exception e)
{
Expand All @@ -114,12 +118,16 @@ public IActionResult GetMe()
/// </remarks>
///
/// <response code="200">Empty Response</response>
/// <response code="500">Internal Server Error</response>
/// <response code="400">Bad Request</response>
/// <response code="403">Forbid</response>
/// <response code="404">Not Found</response>
/// <response code="500">Internal Server Error</response>
[HttpPost("{userId}/approve")]
[Authorize(Policy = "Admin")]
[ProducesResponseType(typeof(void), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status403Forbidden)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public IActionResult ApproveUser(string userId)
{
Expand All @@ -130,10 +138,20 @@ public IActionResult ApproveUser(string userId)
_userUsecases.ApproveUser(adminId, userId);
return Ok();
}
catch (ArgumentException e)
catch (ArgumentInvalidException e)
{
_logger.LogError(e, e.Message);
return BadRequest(e.Message);
}
catch (InsufficientPermissionException e)
{
_logger.LogError(e, e.Message);
return Problem(detail: e.Message, statusCode: 400);
return Forbid(e.Message);
}
catch (EntityNotFoundException e)
{
_logger.LogError(e, e.Message);
return NotFound(e.Message);
}
catch (Exception e)
{
Expand All @@ -152,12 +170,17 @@ public IActionResult ApproveUser(string userId)
/// </remarks>
///
/// <response code="200">Empty Response</response>
/// <response code="500">Internal Server Error</response>
/// <response code="400">Bad Request</response>
/// <response code="403">Forbid</response>
/// <response code="404">Not Found</response>
/// <response code="500">Internal Server Error</response>
[HttpPost("{userId}/decline")]
[Authorize(Policy = "Admin")]
[ProducesResponseType(typeof(void), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status403Forbidden)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public IActionResult DeclineUser(string userId)
{
Expand All @@ -168,10 +191,20 @@ public IActionResult DeclineUser(string userId)
_userUsecases.DeclineUser(adminId, userId);
return Ok();
}
catch (ArgumentException e)
catch (ArgumentInvalidException e)
{
_logger.LogError(e, e.Message);
return Problem(detail: e.Message, statusCode: 400);
return BadRequest(e.Message);
}
catch (InsufficientPermissionException e)
{
_logger.LogError(e, e.Message);
return Forbid(e.Message);
}
catch (EntityNotFoundException e)
{
_logger.LogError(e, e.Message);
return NotFound(e.Message);
}
catch (Exception e)
{
Expand All @@ -189,12 +222,12 @@ public IActionResult DeclineUser(string userId)
/// </remarks>
///
/// <response code="200">Empty Response</response>
/// <response code="404">Not Found</response>
/// <response code="500">Internal Server Error</response>
/// <response code="400">Bad Request</response>
[HttpPost("me")]
[Authorize]
[ProducesResponseType(typeof(void), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public IActionResult UpdateUser(UserProfileDto userDto)
{
Expand All @@ -204,13 +237,15 @@ public IActionResult UpdateUser(UserProfileDto userDto)
{
var mapper = _autoMapperConfiguration.GetConfiguration().CreateMapper();
var user = mapper.Map<UserProfileDto, User>(userDto);

_userUsecases.UpdateUser(user);

return Ok();
}
catch (ArgumentException e)
catch (EntityNotFoundException e)
{
_logger.LogError(e, e.Message);
return Problem(detail: e.Message, statusCode: 400);
return NotFound(e.Message);
}
catch (Exception e)
{
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
namespace Deskstar.Core.Exceptions;

public class ArgumentInvalidException : ArgumentException
{
public ArgumentInvalidException(string message) : base(message) { }
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
namespace Deskstar.Core.Exceptions;

public class EntityNotFoundException : ArgumentException
{
public EntityNotFoundException(string message) : base(message) { }
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
namespace Deskstar.Core.Exceptions;

public class InsufficientPermissionException : ArgumentException
{
public InsufficientPermissionException(string message) : base(message) { }
}
Loading