Commit a71aba2e authored by adnansetiawan's avatar adnansetiawan

add Auth for customer API

parent 75352fa5
Pipeline #26957 passed with stages
in 6 minutes and 57 seconds
......@@ -99,11 +99,11 @@
<Property Name="sonar.java.collectAnalysisErrors">false</Property>
<Property Name="sonar.updatecenter.url">https://update.sonarsource.org/update-center.properties</Property>
<Property Name="sonar.core.id">BF41A1F2-AXE_vdHPrJB8apnk_sSE</Property>
<Property Name="sonar.core.startTime">04/12/2020 10:24:40</Property>
<Property Name="sonar.core.startTime">04/15/2020 13:06:12</Property>
</ServerSettings>
<LocalSettings>
<Property Name="sonar.cs.opencover.reportsPaths">EasyParking.UnitTest/coverage.opencover.xml</Property>
<Property Name="sonar.coverage.exclusions">**Test*.cs</Property>
<Property Name="sonar.coverage.exclusions">**Test*.cs,**Repository.cs</Property>
</LocalSettings>
<AnalyzersSettings>
<AnalyzerSettings>
......
......@@ -2,5 +2,5 @@ projectKey=easyparking
serverUrl=http://localhost:9000
serverVersion=8.2.0.32929
dashboardUrl=http://localhost:9000/dashboard?id=easyparking
ceTaskId=AXFslmgWUgKXJsyHcafh
ceTaskUrl=http://localhost:9000/api/ce/task?id=AXFslmgWUgKXJsyHcafh
ceTaskId=AXF8dgNDO0IRs99adbcc
ceTaskUrl=http://localhost:9000/api/ce/task?id=AXF8dgNDO0IRs99adbcc
......@@ -175,7 +175,7 @@ E4E2718B-9071-47AA-ADCD-2EB385FF562A.sonar.cs.roslyn.reportFilePaths=\
E4E2718B-9071-47AA-ADCD-2EB385FF562A.sonar.working.directory=/Users/adnan/Documents/easy-parking-new/backendApi/easyparking/EasyParking/.sonarqube/out/.sonar/mod3
sonar.cs.opencover.reportsPaths=EasyParking.UnitTest/coverage.opencover.xml
sonar.coverage.exclusions=**Test*.cs
sonar.coverage.exclusions=**Test*.cs,**Repository.cs
sonar.visualstudio.enable=false
sonar.modules=C865F8A4-CB57-4F70-8E26-0717449BCE60,C591D340-97B2-46CF-92E8-A1E717E83600,187EA334-97A4-44E1-8915-736F4EF74702,E4E2718B-9071-47AA-ADCD-2EB385FF562A
......
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using Microsoft.AspNetCore.Mvc;
namespace EasyParking.API.Controllers
{
public class BaseController : ControllerBase
{
protected Guid GetIdFromToken()
{
var memberIdClaim = HttpContext.User?.FindFirst("Id");
if (memberIdClaim == null)
throw new ApplicationException("Id not found, please relogin");
return Guid.Parse(memberIdClaim.Value);
}
protected string GetEmailFromToken()
{
var emailClaim = HttpContext.User?.FindFirst(ClaimTypes.Email);
if (emailClaim == null)
throw new ApplicationException("email not found, please relogin");
return emailClaim.Value;
}
}
}
......@@ -19,12 +19,14 @@ namespace EasyParking.API.Controllers
[ApiController]
[Route("api/booking")]
[Produces("application/json")]
public class BookingController : ControllerBase
public class BookingController : BaseController
{
private readonly BookingService _bookingService;
private readonly CustomerService _customerService;
public BookingController(IBookingRepository bookingRepository, ISlotRepository slotRepository, ICustomerRepository customerRepository)
{
_bookingService = new BookingService(customerRepository, bookingRepository, slotRepository);
_customerService = new CustomerService(customerRepository);
}
/// <summary>
/// Get All Booking
......@@ -61,7 +63,7 @@ namespace EasyParking.API.Controllers
/// <returns></returns>
/// <response code="200">Returns booking</response>
[HttpPost]
[AllowAnonymous]
[Authorize(Roles = "customer")]
[ProducesResponseType(typeof(BookingDetailDto), 200)]
public IActionResult Post(AddNewBookingRequest addNewBookingRequest)
{
......@@ -71,11 +73,12 @@ namespace EasyParking.API.Controllers
try
{
var customerEmail = GetEmailFromToken();
var customer = _customerService.GetByEmail(customerEmail);
var newBooking = new Booking
{
Id = Guid.NewGuid(),
BookedBy = new Customer { Id = addNewBookingRequest.CustomerId },
BookedBy = new Customer { Id = customer.Id },
CreatedDate = DateTime.UtcNow,
LicensePlate = addNewBookingRequest.LicensePlate,
Slot = new Slot { Id = addNewBookingRequest.SlotId },
......@@ -104,7 +107,7 @@ namespace EasyParking.API.Controllers
/// <returns></returns>
/// <response code="200">Returns booking</response>
[HttpPut]
[AllowAnonymous]
[Authorize(Roles = "customer")]
[ProducesResponseType(typeof(BookingDetailDto), 200)]
public IActionResult Post(UpdateBookingRequest updateBookingRequest)
{
......@@ -114,11 +117,13 @@ namespace EasyParking.API.Controllers
try
{
var customerEmail = GetEmailFromToken();
var customer = _customerService.GetByEmail(customerEmail);
var updatedBooking = new Booking
{
Id = updateBookingRequest.BookingId,
BookedBy = new Customer { Id = updateBookingRequest.CustomerId },
BookedBy = new Customer { Id = customer.Id },
LicensePlate = updateBookingRequest.LicensePlate,
Slot = new Slot { Id = updateBookingRequest.SlotId },
StartTime = updateBookingRequest.StartTime,
......
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
......@@ -18,7 +19,7 @@ namespace EasyParking.API.Controllers
[ApiController]
[Route("api/customer")]
[Produces("application/json")]
public class CustomerController : ControllerBase
public class CustomerController : BaseController
{
private readonly CustomerService _customerService;
private readonly IConfiguration _configuration;
......@@ -34,6 +35,7 @@ namespace EasyParking.API.Controllers
/// <response code="200">Returns All Customers </response>
[HttpGet]
[ProducesResponseType(typeof(CustomerDetailDto[]), 200)]
[Authorize(Roles = "Administrator")]
public IActionResult Get()
{
var customers = _customerService.GetCustomers();
......@@ -41,6 +43,22 @@ namespace EasyParking.API.Controllers
return new OkObjectResult(response);
}
/// <summary>
/// Get Customer Info
/// </summary>
/// <returns></returns>
/// <response code="200">Returns Customer </response>
[HttpGet("info")]
[Authorize(Roles = "customer")]
[ProducesResponseType(typeof(CustomerDetailDto), 200)]
public IActionResult GetInfo()
{
var customerEmail = GetEmailFromToken();
var customer = _customerService.GetByEmail(customerEmail);
var response = customer.MapToDetailDto();
return new OkObjectResult(response);
}
/// <summary>
/// Register New Customer
/// </summary>
......@@ -81,7 +99,7 @@ namespace EasyParking.API.Controllers
/// <returns></returns>
/// <response code="200">Returns Customer</response>
[HttpPut]
[AllowAnonymous]
[Authorize(Roles = "customer")]
[ProducesResponseType(typeof(CustomerDetailDto), 200)]
public IActionResult Update(UpdateCustomerRequest updateCustomerRequest)
{
......@@ -91,8 +109,8 @@ namespace EasyParking.API.Controllers
try
{
var updatedCustomer = _customerService.Update(updateCustomerRequest.CustomerId, updateCustomerRequest.Name,
var customerEmail = GetEmailFromToken();
var updatedCustomer = _customerService.Update(customerEmail, updateCustomerRequest.Name,
updateCustomerRequest.PhoneNumber, updateCustomerRequest.Address);
response = updatedCustomer.MapToDetailDto();
}
......@@ -125,14 +143,19 @@ namespace EasyParking.API.Controllers
var jwtSecretKey = _configuration.GetSection("Jwt:SecretKey").Value;
// authentication successful so generate jwt token
var claims = new List<Claim>
{
new Claim(ClaimTypes.Email, loginRequest.Email)
};
claims.Add(new Claim(ClaimTypes.Role, "customer"));
var subject = new ClaimsIdentity(claims);
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes(jwtSecretKey);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new Claim[]
{
new Claim(ClaimTypes.Email, loginRequest.Email)
}),
Subject = subject,
Expires = DateTime.UtcNow.AddDays(7),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
......@@ -170,6 +193,7 @@ namespace EasyParking.API.Controllers
/// <returns></returns>
/// <response code="200">Returns boolean</response>
[HttpPost("logout")]
[Authorize(Roles = "customer")]
[ProducesResponseType(typeof(bool), 200)]
public IActionResult Logout(LogoutRequest logoutRequest)
{
......@@ -178,7 +202,8 @@ namespace EasyParking.API.Controllers
try
{
_customerService.Logout(logoutRequest.Email, logoutRequest.Token);
var customerEmail = GetEmailFromToken();
_customerService.Logout(customerEmail);
}
catch (Exception ex)
{
......
......@@ -18,7 +18,7 @@ namespace EasyParking.API.Controllers
[ApiController]
[Route("api/user")]
[Produces("application/json")]
public class UserController : ControllerBase
public class UserController : BaseController
{
private readonly UserRoleService _userRoleService;
private readonly UserService _userService;
......@@ -34,7 +34,6 @@ namespace EasyParking.API.Controllers
/// </summary>
/// <returns></returns>
/// <response code="200">Returns All Users </response>
[Authorize(Roles = "Administrator")]
[HttpGet]
[ProducesResponseType(typeof(UserDetailDto[]), 200)]
public IActionResult Get()
......@@ -104,7 +103,7 @@ namespace EasyParking.API.Controllers
/// <returns></returns>
/// <response code="200">Returns user</response>
[HttpPut]
[AllowAnonymous]
[Authorize(Roles = "Administrator")]
[ProducesResponseType(typeof(UserDetailDto), 200)]
public IActionResult Update(UpdateUserRequest updateUserRequest)
{
......@@ -141,6 +140,7 @@ namespace EasyParking.API.Controllers
/// <param name="id"></param>
/// <returns></returns>
[HttpDelete("{id}")]
[Authorize(Roles = "Administrator")]
public IActionResult DeleteUser(Guid id)
{
if (ModelState.IsValid)
......@@ -229,14 +229,15 @@ namespace EasyParking.API.Controllers
/// <response code="200">Returns boolean</response>
[HttpPost("logout")]
[ProducesResponseType(typeof(bool), 200)]
public IActionResult Logout(LogoutRequest logoutRequest)
public IActionResult Logout()
{
if (ModelState.IsValid)
{
try
{
_userService.Logout(logoutRequest.Email, logoutRequest.Token);
var userEmail = GetEmailFromToken();
_userService.Logout(userEmail);
}
catch (Exception ex)
{
......@@ -303,6 +304,7 @@ namespace EasyParking.API.Controllers
/// <returns></returns>
/// <response code="200">Returns user role</response>
[HttpPost("role")]
[Authorize(Roles = "Administrator")]
[ProducesResponseType(typeof(UserDetailRoleDto), 200)]
public IActionResult AddUserRole(AddUserRoleRequest addUserRoleRequest)
{
......@@ -336,6 +338,7 @@ namespace EasyParking.API.Controllers
/// <returns></returns>
/// <response code="200">Returns User Role</response>
[HttpPut("role")]
[Authorize(Roles = "Administrator")]
[ProducesResponseType(typeof(UserDetailRoleDto), 200)]
public IActionResult UpdateUserRole(UpdateLocationRequest updateUserRoleRequest)
{
......@@ -368,6 +371,7 @@ namespace EasyParking.API.Controllers
/// <param name="id"></param>
/// <returns></returns>
[HttpDelete("role/{id}")]
[Authorize(Roles = "Administrator")]
public IActionResult DeleteUserRole(Guid id)
{
if (ModelState.IsValid)
......
......@@ -8,8 +8,6 @@ namespace EasyParking.API.Dtos.Request
[Required]
public Guid SlotId { get; set; }
[Required]
public Guid CustomerId { get; set; }
[Required]
public string LicensePlate { get; set; }
[Required]
public DateTime StartTime { get; set; }
......@@ -23,8 +21,6 @@ namespace EasyParking.API.Dtos.Request
[Required]
public Guid SlotId { get; set; }
[Required]
public Guid CustomerId { get; set; }
[Required]
public string LicensePlate { get; set; }
[Required]
public DateTime StartTime { get; set; }
......
......@@ -5,12 +5,6 @@ namespace EasyParking.API.Dtos.Request
{
public class LogoutRequest
{
[Required]
[DataType(DataType.EmailAddress)]
[EmailAddress]
public string Email { get; set; }
[Required]
public string Token { get; set; }
}
}
......@@ -5,8 +5,6 @@ namespace EasyParking.API.Dtos.Request
{
public class UpdateCustomerRequest
{
[Required]
public Guid CustomerId { get; set; }
[Required]
public string Name { get; set; }
public string PhoneNumber { get; set; }
......
......@@ -12,6 +12,7 @@ namespace EasyParking.API.Dtos.Response
public DateTime EndTime { get; set; }
public DateTime CreatedDate { get; set; }
public DateTime? ModifiedDate { get; set; }
public Decimal TotalPayment { get; set; }
}
}
......@@ -15,7 +15,9 @@ namespace EasyParking.API.Mapper
Slot = booking.Slot?.MapToDto(),
BookedBy = booking.BookedBy?.MapToDto(),
CreatedDate = booking.CreatedDate,
ModifiedDate = booking.ModifiedDate
ModifiedDate = booking.ModifiedDate,
TotalPayment = booking.TotalPayment
};
}
......
......@@ -11,6 +11,13 @@ namespace EasyParking.Core
public DateTime EndTime { get; set; }
public DateTime CreatedDate { get; set; }
public DateTime? ModifiedDate { get; set; }
public decimal TotalPayment
{
get
{
return (decimal)(EndTime.Subtract(StartTime).TotalHours * 5000) + 5000;
}
}
}
}
......@@ -32,9 +32,9 @@ namespace EasyParking.Core
return newCustomer;
}
public Customer Update(Guid customerId, string name, string phoneNumber, string address)
public Customer Update(string email, string name, string phoneNumber, string address)
{
var existingCustomerByEmail = _customerRepository.GetByCustomerId(customerId);
var existingCustomerByEmail = _customerRepository.GetByEmail(email);
if (existingCustomerByEmail == null)
throw new Core.Exceptions.CustomerNotFoundExeption();
existingCustomerByEmail.Name = name;
......@@ -48,6 +48,13 @@ namespace EasyParking.Core
{
return _customerRepository.GetAll();
}
public Customer GetByEmail(string email)
{
var customer = _customerRepository.GetByEmail(email);
if (customer == null)
throw new Core.Exceptions.CustomerNotFoundExeption();
return customer;
}
public Customer Login(string email, string password, string token)
{
var existingCustomer = _customerRepository.GetByEmail(email);
......@@ -61,7 +68,7 @@ namespace EasyParking.Core
}
public void Logout(string email, string token)
public void Logout(string email)
{
var existingCustomer = _customerRepository.GetByEmail(email);
if (existingCustomer == null)
......
......@@ -79,7 +79,7 @@ namespace EasyParking.Core
return existingUser;
}
public void Logout(string email, string token)
public void Logout(string email)
{
var existingUser = _userRepository.GetByEmail(email);
if (existingUser == null)
......
......@@ -113,6 +113,7 @@ namespace EasyParking.Infrastructure.Mapper
ModifiedDate = customer.ModifiedDate,
};
}
}
......
......@@ -10,5 +10,6 @@ namespace EasyParking.Infrastructure.Repositories
public DateTime EndTime { get; set; }
public virtual Customer BookedBy { get; set; }
public virtual Slot Slot { get; set; }
public decimal TotalPayment { get; set; }
}
}
......@@ -25,7 +25,8 @@ namespace EasyParking.Infrastructure.Repositories
SlotId = booking.Slot.Id,
LicensePlate = booking.LicensePlate,
StartTime = booking.StartTime,
EndTime = booking.EndTime
EndTime = booking.EndTime,
TotalPayment = booking.TotalPayment
});
_dbContext.SaveChanges();
}
......@@ -55,6 +56,7 @@ namespace EasyParking.Infrastructure.Repositories
existingBooking.StartTime = booking.StartTime;
existingBooking.EndTime = booking.EndTime;
existingBooking.ModifiedDate = DateTime.UtcNow;
existingBooking.TotalPayment = booking.TotalPayment;
_dbContext.Bookings.Update(existingBooking);
_dbContext.SaveChanges();
}
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment