Outline

Solution: Add CurrentUserAsync

In the Conduit.Api Project

Modify the UserController (notice the singular "User")
  • Add the following method
    • Name: CurrentUserAsync
    • Return Type: IActionResult
    • Parameters: n/a
Add the following Attributes to the method
  • HttpGet
  • Authorize (bring in the namespace Microsoft.AspNetCore.Authorization)
Add the following code to the body of the method
User user = await AccountRepo.GetCurrentuserAsync();
return Ok(new { user });
Finally
  • Resolve any namespace errors you're seeing
  • Implement Exception Handling
  • Wrap the code in the body of the method with a try…catch block

Here's the code for the UserController.cs file:

using Conduit.Models.Exceptions;
using Conduit.Models.Responses;
using Conduit.Repositories;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Threading.Tasks;

namespace Conduit.Api.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class UserController : ControllerBase
    {
        private IAccountRepository AccountRepo;
        private ILogger<UserController> Logger;

        [HttpGet]
        [Authorize]
        public async Task<IActionResult> CurrentUserAsync()
        {
            try
            {
                User user = await AccountRepo.GetCurrentUserAsync();
                return Ok(new { user });
            }
            catch (InvalidCredentialsException e)
            {
                Logger.LogWarning(e.Message, e);
                return StatusCode(422, e.ToDictionary());
            }
            catch (Exception ex)
            {
                Logger.LogError(ex.Message, ex);
                return StatusCode(500, ex.Message);
            }
        }

        public UserController(IAccountRepository accountRepo, ILogger<UserController> logger)
        {
            AccountRepo = accountRepo;
            Logger = logger;
        }
    }
}
 

I finished! On to the next chapter