Skip to content

Commit

Permalink
Add functionality to select the party you want to represent in LocalT…
Browse files Browse the repository at this point in the history
…est (#9567)

Co-authored-by: Ivar <[email protected]>
  • Loading branch information
ivarne and ivarne authored Jan 19, 2023
1 parent 68fc9b7 commit 3fc0c79
Show file tree
Hide file tree
Showing 3 changed files with 80 additions and 33 deletions.
95 changes: 66 additions & 29 deletions src/Controllers/HomeController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ public class HomeController : Controller
private readonly IUserProfiles _userProfileService;
private readonly IAuthentication _authenticationService;
private readonly IApplicationRepository _applicationRepository;
private readonly IParties _partiesService;
private readonly IClaims _claimsService;
private readonly ILocalApp _localApp;
private readonly TestDataService _testDataService;
Expand All @@ -41,6 +42,7 @@ public HomeController(
IUserProfiles userProfileService,
IAuthentication authenticationService,
IApplicationRepository applicationRepository,
IParties partiesService,
IClaims claimsService,
ILocalApp localApp,
TestDataService testDataService)
Expand All @@ -50,6 +52,7 @@ public HomeController(
_userProfileService = userProfileService;
_authenticationService = authenticationService;
_applicationRepository = applicationRepository;
_partiesService = partiesService;
_claimsService = claimsService;
_localApp = localApp;
_testDataService = testDataService;
Expand Down Expand Up @@ -144,7 +147,7 @@ public async Task<ActionResult> LogInTestUser(StartAppModel startAppModel)
int authenticationLevel = Convert.ToInt32(startAppModel.AuthenticationLevel);

string token = await _authenticationService.GenerateTokenForProfile(profile, authenticationLevel);
CreateJwtCookieAndAppendToResponse(token);
CreateJwtCookieAndAppendToResponse(token, startAppModel.PartyId);
}

if (startAppModel.AppPathSelection?.Equals("accessmanagement") == true)
Expand All @@ -157,33 +160,26 @@ public async Task<ActionResult> LogInTestUser(StartAppModel startAppModel)
// Ensure that the documentstorage in LocalTestingStorageBasePath is updated with the most recent app data
await _applicationRepository.Update(app);

if(_localPlatformSettings.LocalAppMode == "http")
if (_localPlatformSettings.LocalAppMode == "http")
{
// Instantiate a prefill if a file attachment exists.
var prefill = Request.Form.Files.FirstOrDefault();
if (prefill != null)
{
var instance = new Instance{
var instance = new Instance
{
AppId = app.Id,
Org = app.Org,
InstanceOwner = new(),
DataValues = new(),
InstanceOwner = new()
{
PartyId = startAppModel.PartyId.ToString(),
},
DataValues = new()
{
{ "PrefillFilename", prefill.FileName }
},
};

var owner = prefill.FileName.Split(".")[0];
if (owner.Length == 9)
{
instance.InstanceOwner.OrganisationNumber = owner;
}
else if (owner.Length == 12)
{
instance.InstanceOwner.PersonNumber = owner;
}
else
{
throw new Exception($"instance owner must be specified as part of the prefill filename. 9 digigts for OrganisationNumber, 12 for PersonNumber (eg 897069631.xml, not {prefill.FileName})");
}

var xmlDataId = app.DataTypes.First(dt => dt.AppLogic is not null).Id;

using var reader = new StreamReader(prefill.OpenReadStream());
Expand Down Expand Up @@ -303,18 +299,41 @@ public ActionResult FrontendVersion(FrontendVersion frontendVersion)
private async Task<IEnumerable<SelectListItem>> GetTestUsersForList()
{
var data = await _testDataService.GetTestData();
List<SelectListItem> userItems = new List<SelectListItem>();
var userItems = new List<SelectListItem>();

foreach (UserProfile profile in data.Profile.User.Values)
{
var properProfile = await _userProfileService.GetUser(profile.UserId);
SelectListItem item = new SelectListItem()

var group = new SelectListGroup()
{
Value = properProfile.UserId.ToString(),
Text = properProfile.Party.Person.Name
Name = properProfile.Party.Person.Name,
};
var userParties = await _partiesService.GetParties(properProfile.UserId);

userItems.Add(item);
if (userParties.Count == 1)
{
// Don't add singe party users to a group
var party = userParties.First();
userItems.Add(new()
{
Value = properProfile.UserId + "." + party.PartyId,
Text = party.Name,
});
}
else
{
// When a user represents multiple parties, add it to a group, so that it stands out visually
foreach (var party in userParties)
{
userItems.Add(new()
{
Value = properProfile.UserId + "." + party.PartyId,
Text = $"{party.Name} ({party.PartyTypeName})",
Group = group,
});
}
}
}

return userItems;
Expand Down Expand Up @@ -403,8 +422,11 @@ private static SelectListItem GetSelectItem(Application app, string path)
/// Creates a session cookie meant to be used to hold the generated JSON Web Token and appends it to the response.
/// </summary>
/// <param name="cookieValue">The cookie value.</param>
private void CreateJwtCookieAndAppendToResponse(string cookieValue)
private void CreateJwtCookieAndAppendToResponse(string identityCookie, int altinnPartyId)
{
ICookieManager cookieManager = new ChunkingCookieManager();

// Add cookie proving the users identity
CookieBuilder cookieBuilder = new RequestPathBaseCookieBuilder
{
Name = "AltinnStudioRuntime",
Expand All @@ -415,15 +437,30 @@ private void CreateJwtCookieAndAppendToResponse(string cookieValue)
Domain = _generalSettings.Hostname,
Expiration = new TimeSpan(0, 1337, 0)
};

CookieOptions cookieOptions = cookieBuilder.Build(HttpContext);

ICookieManager cookieManager = new ChunkingCookieManager();
cookieManager.AppendResponseCookie(
HttpContext,
cookieBuilder.Name,
cookieValue,
identityCookie,
cookieOptions);

// Add cookie about users prefered party (for creating new instances)
CookieBuilder partyCookieBuilder = new RequestPathBaseCookieBuilder
{
Name = "AltinnPartyId",
SameSite = SameSiteMode.Lax,
HttpOnly = false,
SecurePolicy = CookieSecurePolicy.None,
IsEssential = true,
Domain = _generalSettings.Hostname,
Expiration = new TimeSpan(0, 1337, 0)
};
CookieOptions partyCookieOptions = cookieBuilder.Build(HttpContext);
cookieManager.AppendResponseCookie(
HttpContext,
partyCookieBuilder.Name,
altinnPartyId.ToString(),
partyCookieOptions);
}
}
}
14 changes: 12 additions & 2 deletions src/Models/StartAppModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -55,9 +55,19 @@ public class StartAppModel
public HttpRequestException HttpException { get; set; }

/// <summary>
/// Selected userId
/// Selected User and party separated by "."
/// </summary>
public int UserId { get; set; }
public string UserSelect { get; set; }

/// <summary>
/// The userId part of <see cref="UserSelect" />
/// </summary>
public int UserId => int.TryParse(UserSelect?.Split(".").First(), out int result) ? result : 0;

/// <summary>
/// The partyId part of <see cref="UserSelect" />
/// </summary>
public int PartyId => int.TryParse(UserSelect?.Split(".").Last(), out int result) ? result : 0;

/// <summary>
/// Path for the selected app
Expand Down
4 changes: 2 additions & 2 deletions src/Views/Home/Index.cshtml
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@
@Html.AntiForgeryToken();
<div class="form-group">
<label for="exampleInputEmail1">Select test users</label>
@Html.DropDownListFor(model => model.UserId, Model.TestUsers, new { Class = "form-control" })
@Html.DropDownListFor(model => model.UserSelect, Model.TestUsers, new { Class = "form-control" })
</div>
@if(!Model.AppModeIsHttp)
{
Expand All @@ -87,7 +87,7 @@
@if(Model.AppModeIsHttp)
{
<div class="form-group">
<label for="prefill">Prefill xml. The first part of the filename must be "[orgnr]." or "[fnr]." (eg. "897069631.xml" or "897069631.TST-2345.xml")</label>
<label for="prefill">Prefill xml (use this to copy all the values from a <a href="/LocalPlatformStorage/blobs/@(Model.Org)/@(Model.App)">previous instance</a>)</label>
<input class="form-control" type="file" id="prefill" name="prefill" accept=".xml"/>
</div>
}
Expand Down

0 comments on commit 3fc0c79

Please sign in to comment.