Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

IDAM-000 Spike - Profile controller for the profile page #119

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using NICE.Identity.Authentication.Sdk.Extensions;
using NICE.Identity.Authorisation.WebAPI.Services;
using System;
using System.Linq;
using System.Threading.Tasks;
using User = NICE.Identity.Authorisation.WebAPI.ApiModels.User;

namespace NICE.Identity.Authorisation.WebAPI.Controllers
{
[Route("api/[controller]")]
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)] //can't add the UserAdministration policy at this level as the find users and find roles actions don't need it.
[ApiController]
public class UserProfileController : ControllerBase
{
private readonly ILogger<UsersController> _logger;
private readonly IUsersService _usersService;

public UserProfileController(IUsersService usersService, ILogger<UsersController> logger)
{
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
_usersService = usersService ?? throw new ArgumentNullException(nameof(usersService));
}

private string GetNameIdentifierFromUser()
{
var claimsPrincipal = HttpContext?.User; //todo: switch to using httpcontextaccessor..

return claimsPrincipal.Claims.FirstOrDefault(c => c.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier")?.Value;
}

/// <summary>
/// gets own profile details
/// </summary>
/// <returns></returns>
[HttpGet("")]
[ProducesResponseType(typeof(User), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
[Produces("application/json")]
public IActionResult GetOwnUserProfile()
{
try
{
var nameIdentifier = GetNameIdentifierFromUser();
if (nameIdentifier == null)
{
return StatusCode(500, new ProblemDetails { Status = 500, Title = $"Unable to get name identifier when retrieving own profile" });
}
return Ok(_usersService.GetUser(nameIdentifier));
}
catch (Exception e)
{
return StatusCode(500, new ProblemDetails { Status = 500, Title = $"{e.Message}" });
}
}

/// <summary>
/// updates user details
/// </summary>
/// <returns></returns>
[HttpPost("")]
[ProducesResponseType(typeof(User), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
[Produces("application/json")]
public async Task<IActionResult> GetOwnUserProfile(string nameIdentifier, string firstName, string lastName, string emailAddress)
{
try
{
if (string.IsNullOrEmpty(nameIdentifier))
return StatusCode(500, new ProblemDetails { Status = 500, Title = $"Invalid identifier" });

if (string.IsNullOrEmpty(firstName))
return StatusCode(500, new ProblemDetails { Status = 500, Title = $"Invalid firstName" });

if (string.IsNullOrEmpty(lastName))
return StatusCode(500, new ProblemDetails { Status = 500, Title = $"Invalid lastName" });

if (string.IsNullOrEmpty(emailAddress))
return StatusCode(500, new ProblemDetails { Status = 500, Title = $"Invalid emailAddress" });


var nameIdentifierFromToken = GetNameIdentifierFromUser();

if (string.IsNullOrEmpty(nameIdentifierFromToken) || !nameIdentifier.Equals(nameIdentifierFromToken, StringComparison.OrdinalIgnoreCase))
{
return StatusCode(500, new ProblemDetails { Status = 500, Title = $"Invalid user" });
}

var userToUpdate = _usersService.GetUser(nameIdentifier);
if (userToUpdate == null)
{
return StatusCode(500, new ProblemDetails { Status = 500, Title = $"Unable to get user when updating own profile" });
}

userToUpdate.FirstName = firstName;
userToUpdate.LastName = lastName;
userToUpdate.EmailAddress = emailAddress;

var updatedUser = await _usersService.UpdateUser(userToUpdate.UserId.Value, userToUpdate);
return Ok(updatedUser);
}
catch (Exception e)
{
return StatusCode(500, new ProblemDetails { Status = 500, Title = $"{e.Message}" });
}
}
}
}
9 changes: 8 additions & 1 deletion NICE.Identity.Authorisation.WebAPI/Services/UsersService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ public interface IUsersService
{
User CreateUser(User user);
User GetUser(int userId);
User GetUser(string nameIdentifier);
IList<User> GetUsers(string filter);
IList<UserDetails> FindUsers(IEnumerable<string> nameIdentifiers);
Dictionary<string, IEnumerable<string>> FindRoles(IEnumerable<string> nameIdentifiers, string host);
Expand Down Expand Up @@ -84,7 +85,13 @@ public User GetUser(int userId)
return user != null ? new User(user) : null;
}

public IList<User> GetUsers(string filter = null)
public User GetUser(string nameIdentifier)
{
var user = _context.Users.Where((u => u.NameIdentifier.Equals(nameIdentifier))).FirstOrDefault();
return user != null ? new User(user) : null;
}

public IList<User> GetUsers(string filter = null)
{
if (!string.IsNullOrEmpty(filter))
{
Expand Down
5 changes: 5 additions & 0 deletions NICE.Identity.Test/Infrastructure/MockUserService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,11 @@ public User GetUser(int userId)
throw new NotImplementedException();
}

public User GetUser(string nameIdentifier)
{
throw new NotImplementedException();
}

public IList<User> GetUsers(string filter)
{
throw new NotImplementedException();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,9 @@ public class HomeController : Controller
private readonly IHttpClientFactory _clientFactory;
private readonly IAPIService _apiService;
private readonly IApiToken _apiToken;
private readonly ApiTokenClient _apiTokenClient;
private readonly IApiTokenClient _apiTokenClient;

public HomeController(IConfiguration configuration, IHttpClientFactory clientFactory, IAPIService apiService, IApiToken apiToken, ApiTokenClient apiTokenClient)
public HomeController(IConfiguration configuration, IHttpClientFactory clientFactory, IAPIService apiService, IApiToken apiToken, IApiTokenClient apiTokenClient)
{
_configuration = configuration;
_clientFactory = clientFactory;
Expand Down