99 lines
3.0 KiB
C#

namespace AAIntegration.SimmonsBank.API.Controllers;
using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using AAIntegration.SimmonsBank.API.Models.Accounts;
using AAIntegration.SimmonsBank.API.Services;
using AAIntegration.SimmonsBank.API.Config;
using System.Collections.Generic;
using AAIntegration.SimmonsBank.API.Entities;
using Microsoft.AspNetCore.Authorization;
using System.Security.Claims;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
[Authorize]
[ApiController]
[Route("[controller]")]
public class AccountsController : ControllerBase
{
private IAccountService _accountService;
private IUserService _userService;
private IMapper _mapper;
private readonly AppSettings _appSettings;
private readonly ILogger<AccountsController> _logger;
private IPuppeteerService _puppeteerService;
public AccountsController(
IAccountService accountService,
IUserService userService,
IMapper mapper,
IOptions<AppSettings> appSettings,
ILogger<AccountsController> logger,
IPuppeteerService puppeteerService)
{
_accountService = accountService;
_userService = userService;
_mapper = mapper;
_appSettings = appSettings.Value;
_logger = logger;
_puppeteerService = puppeteerService;
}
[HttpGet]
public async Task<IActionResult> GetAllAsync()
{
List<AccountDTO> accounts = await _puppeteerService.GetAccounts(_userService.GetUser(User.FindFirstValue(ClaimTypes.NameIdentifier)));
return Ok(accounts);
/*List<AccountDTO> accountDtos = new List<AccountDTO>();
foreach (Account acc in _accountService.GetAll(GetCurrentUserId()))
accountDtos.Add(_mapper.Map<Account, AccountDTO>(acc));
return Ok(accountDtos);*/
}
[HttpGet("{id}")]
public IActionResult GetById(int id)
{
Account account = _accountService.GetById(id, GetCurrentUserId());
return Ok(_mapper.Map<Account, AccountDTO>(account));
}
[HttpPost]
public IActionResult Create([FromBody]AccountCreateRequest model)
{
_accountService.Create(model, GetCurrentUserId());
return Ok(new { message = "account created" });
}
[HttpPut("{id}")]
public IActionResult Update(int id, [FromBody]AccountUpdateRequest model)
{
_accountService.Update(id, model, GetCurrentUserId());
return Ok(new { message = "account updated" });
}
[HttpDelete("{id}")]
public IActionResult Delete(int id)
{
_accountService.Delete(id, GetCurrentUserId());
return Ok(new { message = "account deleted" });
}
// Helpers
private int GetCurrentUserId()
{
string apiKey = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (apiKey is null)
_logger.LogInformation($"ApiKey: is null");
_logger.LogInformation($"apiKey: {apiKey}");
return _userService.GetUser(apiKey).Id;
}
}