namespace AAIntegration.SimmonsBank.API.Controllers; using AutoMapper; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Options; using AAIntegration.SimmonsBank.API.Models.Users; using AAIntegration.SimmonsBank.API.Services; using AAIntegration.SimmonsBank.API.Config; using System; using System.Security.Claims; using Microsoft.AspNetCore.Authorization; [Authorize] [ApiController] [Route("[controller]")] public class ApiKeyController : ControllerBase { private IApiKeyService _apiKeyService; private IMapper _mapper; private readonly AppSettings _appSettings; private readonly ILogger _logger; private IUserService _userService; public ApiKeyController( IApiKeyService apiKeyService, IMapper mapper, IOptions appSettings, ILogger logger, IUserService userService) { _apiKeyService = apiKeyService; _mapper = mapper; _appSettings = appSettings.Value; _logger = logger; _userService = userService; } [HttpGet] public IActionResult GetApiKey() { string apiKey = _userService.GetUserApiKey(this.GetCurrentUserId()); string[] apiKeys = { apiKey }; Console.WriteLine($"User API Key Got: " + apiKey); return Ok(new { keys = apiKeys }); } /*[HttpGet("{id}")] public IActionResult GetById(int id) { var user = _apiKeyService.GetById(id); return Ok(user); }*/ [HttpGet("CreateNew")] public IActionResult CreateNewApiKey() { string apiKey = _userService.CreateUserApiKey(this.GetCurrentUserId()); return Ok(new { message = "API Key created", key = apiKey }); } [HttpDelete("{apiKey}")] public IActionResult Delete(string apiKey) { _userService.InvalidateApiKey(apiKey); return Ok(new { message = "API Key deleted" }); } // Helpers private int GetCurrentUserId() { string nameIdentifier = User.FindFirstValue(ClaimTypes.NameIdentifier); if (nameIdentifier is null) _logger.LogInformation($"Name Identifier: is null"); _logger.LogInformation($"Name Identifier: {nameIdentifier}"); Console.WriteLine($"User Id: " + nameIdentifier); return Convert.ToInt32(nameIdentifier); } }