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

Added new method to fetch UserProfile by userUuid #122

Merged
merged 10 commits into from
Jan 17, 2024
Merged
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
2 changes: 1 addition & 1 deletion src/Altinn.Profile/Altinn.Profile.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

<ItemGroup>
<PackageReference Include="Altinn.Common.AccessToken" Version="3.0.3" />
<PackageReference Include="Altinn.Platform.Models" Version="1.2.0" />
<PackageReference Include="Altinn.Platform.Models" Version="1.3.0" />
<PackageReference Include="Azure.Extensions.AspNetCore.Configuration.Secrets" Version="1.3.0" />
<PackageReference Include="Azure.Identity" Version="1.10.4" />
<PackageReference Include="Azure.Security.KeyVault.Secrets" Version="4.5.0" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,9 @@ public UserProfileInternalController(IUserProfiles userProfilesWrapper)
/// <summary>
/// Gets the user profile for a given user identified by one of the available types of user identifiers:
/// UserId (from Altinn 2 Authn UserProfile)
/// UserUuid (from Altinn 2 Authn UserProfile)
/// Username (from Altinn 2 Authn UserProfile)
/// SSN/Dnr (from Freg)
/// Uuid (from Altinn 2 Party/UserProfile implementation will be added later)
/// </summary>
/// <param name="userProfileLookup">Input model for providing one of the supported lookup parameters</param>
/// <returns>User profile of the given user</returns>
Expand All @@ -47,6 +47,10 @@ public async Task<ActionResult<UserProfile>> Get([FromBody] UserProfileLookup us
{
result = await _userProfilesWrapper.GetUser(userProfileLookup.UserId);
}
else if (userProfileLookup?.UserUuid != null)
{
result = await _userProfilesWrapper.GetUserByUuid(userProfileLookup.UserUuid.Value);
}
else if (!string.IsNullOrWhiteSpace(userProfileLookup?.Username))
{
result = await _userProfilesWrapper.GetUserByUsername(userProfileLookup.Username);
Expand Down
23 changes: 22 additions & 1 deletion src/Altinn.Profile/Controllers/UsersController.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using System;
using System.Linq;
using System.Threading.Tasks;

Expand Down Expand Up @@ -37,7 +38,7 @@ public UsersController(IUserProfiles userProfilesWrapper)
/// </summary>
/// <param name="userID">The user id</param>
/// <returns>The information about a given user</returns>
[HttpGet("{userID}")]
[HttpGet("{userID:int}")]
[Authorize(Policy = "PlatformAccess")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
Expand All @@ -52,6 +53,26 @@ public async Task<ActionResult<UserProfile>> Get(int userID)
return Ok(result);
}

/// <summary>
/// Gets the user profile for a given user uuid
/// </summary>
/// <param name="userUuid">The user uuid</param>
/// <returns>The information about a given user</returns>
[HttpGet("{userUuid:Guid}")]
[Authorize(Policy = "PlatformAccess")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<ActionResult<UserProfile>> Get(Guid userUuid)
{
UserProfile result = await _userProfilesWrapper.GetUserByUuid(userUuid);
if (result == null)
{
return NotFound();
}

return Ok(result);
}

/// <summary>
/// Gets the current user based on the request context
/// </summary>
Expand Down
9 changes: 8 additions & 1 deletion src/Altinn.Profile/Models/UserProfileLookup.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
namespace Altinn.Profile.Models
using System;

namespace Altinn.Profile.Models
{
/// <summary>
/// Input model for internal UserProfile lookup requests, where one of the lookup identifiers available must be set for performing the lookup request:
Expand All @@ -13,6 +15,11 @@ public class UserProfileLookup
/// Gets or sets the users UserId if the lookup is to be performed based on this identifier
/// </summary>
public int UserId { get; set; }

/// <summary>
/// Gets or sets the users UserUuid if the lookup is to be performed based on this identifier
/// </summary>
public Guid? UserUuid { get; set; }

/// <summary>
/// Gets or sets the users Username if the lookup is to be performed based on this identifier
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,26 @@ public async Task<UserProfile> GetUser(string ssn)
return user;
}

/// <inheritdoc/>
public async Task<UserProfile> GetUserByUuid(Guid userUuid)
{
string uniqueCacheKey = $"User:UserUuid:{userUuid}";

if (_memoryCache.TryGetValue(uniqueCacheKey, out UserProfile user))
{
return user;
}

user = await _decoratedService.GetUserByUuid(userUuid);

if (user != null)
{
_memoryCache.Set(uniqueCacheKey, user, _cacheOptions);
}

return user;
}

/// <inheritdoc/>
public async Task<UserProfile> GetUserByUsername(string username)
{
Expand Down
19 changes: 19 additions & 0 deletions src/Altinn.Profile/Services/Implementation/UserProfilesWrapper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,25 @@ public async Task<UserProfile> GetUser(string ssn)
return user;
}

/// <inheritdoc />
public async Task<UserProfile> GetUserByUuid(Guid userUuid)
{
Uri endpointUrl = new Uri($"{_generalSettings.BridgeApiEndpoint}users?useruuid={userUuid}");

HttpResponseMessage response = await _client.GetAsync(endpointUrl);

if (!response.IsSuccessStatusCode)
{
_logger.LogError("Getting user {userUuid} failed with {statusCode}", userUuid, response.StatusCode);
return null;
}

string content = await response.Content.ReadAsStringAsync();
UserProfile user = JsonSerializer.Deserialize<UserProfile>(content, _serializerOptions);

return user;
}

/// <inheritdoc />
public async Task<UserProfile> GetUserByUsername(string username)
{
Expand Down
8 changes: 8 additions & 0 deletions src/Altinn.Profile/Services/Interfaces/IUserProfiles.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using System;
using System.Threading.Tasks;

using Altinn.Platform.Profile.Models;
Expand All @@ -23,6 +24,13 @@ public interface IUserProfiles
/// <returns>User profile connected to given ssn.</returns>
Task<UserProfile> GetUser(string ssn);

/// <summary>
/// Method that fetches a user based on a user uuid
/// </summary>
/// <param name="userUuid">The user uuid</param>
/// <returns>User profile with given user id.</returns>
Task<UserProfile> GetUserByUuid(Guid userUuid);

/// <summary>
/// Method that fetches a user based on username.
/// </summary>
Expand Down
101 changes: 101 additions & 0 deletions test/Altinn.Profile.Tests/IntegrationTests/UserProfileInternalTests.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using System;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
Expand Down Expand Up @@ -76,6 +77,46 @@ public async Task GetUserById_SblBridgeFindsProfile_ResponseOk_ReturnsUserProfil
Assert.Equal("nb", actualUser.ProfileSettingPreference.Language);
}

[Fact]
public async Task GetUserByUuid_SblBridgeFindsProfile_ResponseOk_ReturnsUserProfile()
{
// Arrange
Guid userUuid = new("cc86d2c7-1695-44b0-8e82-e633243fdf31");

HttpRequestMessage sblRequest = null;
DelegatingHandlerStub messageHandler = new(async (request, token) =>
{
sblRequest = request;

UserProfile userProfile = await TestDataLoader.Load<UserProfile>(userUuid.ToString());
return new HttpResponseMessage() { Content = JsonContent.Create(userProfile) };
});
_webApplicationFactorySetup.SblBridgeHttpMessageHandler = messageHandler;

HttpRequestMessage httpRequestMessage = CreatePostRequest($"/profile/api/v1/internal/user/", new UserProfileLookup { UserUuid = userUuid });

HttpClient client = _webApplicationFactorySetup.GetTestServerClient();

// Act
HttpResponseMessage response = await client.SendAsync(httpRequestMessage);

// Assert
Assert.NotNull(sblRequest);
Assert.Equal(HttpMethod.Get, sblRequest.Method);
Assert.EndsWith($"sblbridge/profile/api/users?useruuid={userUuid}", sblRequest.RequestUri.ToString());

string responseContent = await response.Content.ReadAsStringAsync();

UserProfile actualUser = JsonSerializer.Deserialize<UserProfile>(
responseContent, serializerOptionsCamelCase);

// These asserts check that deserializing with camel casing was successful.
Assert.Equal(userUuid, actualUser.UserUuid);
Assert.Equal("LEO WILHELMSEN", actualUser.Party.Name);
Assert.Equal("LEO", actualUser.Party.Person.FirstName);
Assert.Equal("nb", actualUser.ProfileSettingPreference.Language);
}

[Fact]
public async Task GetUserById_SblBridgeReturnsNotFound_ResponseNotFound()
{
Expand Down Expand Up @@ -106,6 +147,36 @@ public async Task GetUserById_SblBridgeReturnsNotFound_ResponseNotFound()
Assert.EndsWith($"sblbridge/profile/api/users/{UserId}", sblRequest.RequestUri.ToString());
}

[Fact]
public async Task GetUserByUuid_SblBridgeReturnsNotFound_ResponseNotFound()
{
// Arrange
Guid userUuid = new("cc86d2c7-1695-44b0-8e82-e633243fdf31");

HttpRequestMessage sblRequest = null;
DelegatingHandlerStub messageHandler = new(async (request, token) =>
{
sblRequest = request;

return await Task.FromResult(new HttpResponseMessage() { StatusCode = HttpStatusCode.NotFound });
});
_webApplicationFactorySetup.SblBridgeHttpMessageHandler = messageHandler;

HttpRequestMessage httpRequestMessage = CreatePostRequest($"/profile/api/v1/internal/user/", new UserProfileLookup { UserUuid = userUuid });

HttpClient client = _webApplicationFactorySetup.GetTestServerClient();

// Act
HttpResponseMessage response = await client.SendAsync(httpRequestMessage);

// Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);

Assert.NotNull(sblRequest);
Assert.Equal(HttpMethod.Get, sblRequest.Method);
Assert.EndsWith($"sblbridge/profile/api/users?useruuid={userUuid}", sblRequest.RequestUri.ToString());
}

[Fact]
public async Task GetUserById_SblBridgeReturnsUnavailable_ResponseNotFound()
{
Expand Down Expand Up @@ -136,6 +207,36 @@ public async Task GetUserById_SblBridgeReturnsUnavailable_ResponseNotFound()
Assert.EndsWith($"sblbridge/profile/api/users/{UserId}", sblRequest.RequestUri.ToString());
}

[Fact]
public async Task GetUserByUuid_SblBridgeReturnsUnavailable_ResponseNotFound()
{
// Arrange
Guid userUuid = new("cc86d2c7-1695-44b0-8e82-e633243fdf31");

HttpRequestMessage sblRequest = null;
DelegatingHandlerStub messageHandler = new(async (request, token) =>
{
sblRequest = request;

return await Task.FromResult(new HttpResponseMessage() { StatusCode = HttpStatusCode.ServiceUnavailable });
});
_webApplicationFactorySetup.SblBridgeHttpMessageHandler = messageHandler;

HttpRequestMessage httpRequestMessage = CreatePostRequest($"/profile/api/v1/internal/user/", new UserProfileLookup { UserUuid = userUuid });

HttpClient client = _webApplicationFactorySetup.GetTestServerClient();

// Act
HttpResponseMessage response = await client.SendAsync(httpRequestMessage);

// Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);

Assert.NotNull(sblRequest);
Assert.Equal(HttpMethod.Get, sblRequest.Method);
Assert.EndsWith($"sblbridge/profile/api/users?useruuid={userUuid}", sblRequest.RequestUri.ToString());
}

[Fact]
public async Task GetUserBySsn_SblBridgeFindsProfile_ReturnsUserProfile()
{
Expand Down
Loading
Loading