using AutoMapper; using Diligent.WebAPI.Business.Services; using Diligent.WebAPI.Data.Entities; using Diligent.WebAPI.Host.DTOs.Customer; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; namespace Diligent.WebAPI.Host.Controllers { [ApiVersion("1.0")] [ApiController] [Route("v{version:apiVersion}/[controller]")] public class CustomerController : ControllerBase { // sifra za svakog od user-a je "Nekasifra123!" private readonly UserManager _customerManager; private readonly RoleManager _roleManager; private readonly IAuthenticationService _authenticationService; private readonly IMapper _mapper; public CustomerController(UserManager customerManager, RoleManager roleManager,IAuthenticationService authenticationService, IMapper mapper) { _customerManager = customerManager; _roleManager = roleManager; _authenticationService = authenticationService; _mapper = mapper; } [HttpPost("login")] public async Task> Login(CustomerLoginDTO customerLoginDTO) { if (!await _authenticationService.ValidateCustomer(customerLoginDTO.Username, customerLoginDTO.Password)) return BadRequest("Authentication failed.Wrong Username or password"); Customer customer = await _authenticationService.GetCustomer(customerLoginDTO.Username); var customerReadDTO = _mapper.Map(customer); customerReadDTO.Token = await _authenticationService.GenerateToken(); customerReadDTO.Roles = (List)await _customerManager.GetRolesAsync(customer); return customerReadDTO; } [HttpPost("addRole")] public async Task CreateRole(string name) { IdentityResult result = await _roleManager.CreateAsync(new Roles() { Name = name }); if (!result.Succeeded) { foreach (IdentityError error in result.Errors) ModelState.AddModelError("", error.Description); return BadRequest(ModelState); } return StatusCode(201); } [HttpPost("register")] public async Task> Register(CustomerCreateDTO customerCreateDTO) { Customer customer = new() { FirstName = customerCreateDTO.FirstName, LastName = customerCreateDTO.LastName, Email = customerCreateDTO.Email, UserName = customerCreateDTO.Username }; var result = await _customerManager.CreateAsync(customer, customerCreateDTO.Password); await _customerManager.AddToRoleAsync(customer, "Customer"); if (!result.Succeeded) { foreach (IdentityError error in result.Errors) ModelState.AddModelError("", error.Description); return BadRequest(ModelState); } await _authenticationService.ValidateCustomer(customer.UserName,customerCreateDTO.Password); var customerReadDTO = _mapper.Map(customer); customerReadDTO.Token = await _authenticationService.GenerateToken(); customerReadDTO.Roles = (List)await _customerManager.GetRolesAsync(customer); return customerReadDTO; } } }