Skip to content

Commit

Permalink
Add TRN verification elevation journey
Browse files Browse the repository at this point in the history
  • Loading branch information
gunndabad committed Sep 26, 2023
1 parent 1c4d93e commit 4f6e279
Show file tree
Hide file tree
Showing 35 changed files with 970 additions and 107 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,17 @@ public AuthenticationState(
[JsonInclude]
public bool HaveResumedCompletedJourney { get; private set; }

/// <summary>
/// Whether the signed in user requires elevating to the higher TrnVerificationLevel.
/// </summary>
/// <remarks>
/// This should be set when the user is signed in and remain un-changed for the duration of the journey.
/// The <see cref="TrnVerificationElevationSuccessful"/> property tracks whether elevation has completed, successfully or not.
/// </remarks>
[JsonInclude]
public bool? RequiresTrnVerificationLevelElevation { get; private set; }
public bool? TrnVerificationElevationSuccessful { get; set; }

[JsonIgnore]
public bool EmailAddressSet => EmailAddress is not null;
[JsonIgnore]
Expand Down Expand Up @@ -240,6 +251,8 @@ public void Reset(DateTime utcNow)
InstitutionEmailChosen = default;
PreferredName = default;
HaveResumedCompletedJourney = default;
RequiresTrnVerificationLevelElevation = default;
TrnVerificationElevationSuccessful = default;
}

public void OnEmailSet(string email, bool isInstitutionEmail = false)
Expand Down Expand Up @@ -359,6 +372,7 @@ public void OnTrnLookupCompletedAndUserRegistered(User user)
FirstTimeSignInForEmail = true;
Trn = user.Trn;
TrnLookup = TrnLookupState.Complete;
RequiresTrnVerificationLevelElevation = false;
UserType = user.UserType;
StaffRoles = user.StaffRoles;
TrnLookupStatus = user.TrnLookupStatus;
Expand Down Expand Up @@ -594,6 +608,10 @@ public void OnSignedInUserProvided(User? user)
LastName = user?.LastName;
DateOfBirth = user?.DateOfBirth;
Trn = user?.Trn;
RequiresTrnVerificationLevelElevation =
user is not null && TryGetOAuthState(out var oAuthState) && oAuthState.TrnMatchPolicy == TrnMatchPolicy.Strict ?
user.EffectiveVerificationLevel != TrnVerificationLevel.Medium :
null;
HaveCompletedTrnLookup = user?.CompletedTrnLookup is not null;
TrnLookup = user?.CompletedTrnLookup is not null ? TrnLookupState.Complete : TrnLookupState.None;
UserType = user?.UserType;
Expand All @@ -605,6 +623,7 @@ public void OnTrnTokenProvided(EnhancedTrnToken trnToken)
{
TrnToken = trnToken.TrnToken;
Trn = trnToken.Trn;
RequiresTrnVerificationLevelElevation = false;
TrnLookupStatus = AuthServer.TrnLookupStatus.Found;
FirstName ??= trnToken.FirstName;
MiddleName ??= trnToken.MiddleName;
Expand Down Expand Up @@ -636,6 +655,11 @@ public void OnTrnLookupCompleted(FindTeachersResponseResult? findTeachersResult,
Trn = trn;
TrnLookupStatus = trnLookupStatus;

if (RequiresTrnVerificationLevelElevation == true)
{
TrnVerificationElevationSuccessful = Trn is not null;
}

if (findTeachersResult is not null && !string.IsNullOrEmpty(findTeachersResult.FirstName) && !string.IsNullOrEmpty(findTeachersResult.LastName))
{
DqtFirstName = findTeachersResult.FirstName;
Expand All @@ -652,21 +676,6 @@ public async Task<ClaimsPrincipal> SignIn(HttpContext httpContext)
return await httpContext.SignInCookies(claims, resetIssued: true, AuthCookieLifetime);
}

public enum HasPreviousNameOption
{
Yes,
No,
PreferNotToSay
}

public enum TrnLookupState
{
None = 0,
Complete = 1,
ExistingTrnFound = 3,
EmailOfExistingAccountForTrnVerified = 4
}

private void UpdateAuthenticationStateWithUserDetails(User user)
{
UserId = user.UserId;
Expand All @@ -689,8 +698,30 @@ private void UpdateAuthenticationStateWithUserDetails(User user)
if (HaveCompletedTrnLookup || Trn is not null)
{
TrnLookup = TrnLookupState.Complete;
RequiresTrnVerificationLevelElevation =
TryGetOAuthState(out var oAuthState) && oAuthState.TrnMatchPolicy == TrnMatchPolicy.Strict &&
user.EffectiveVerificationLevel != TrnVerificationLevel.Medium;
}
}
else
{
RequiresTrnVerificationLevelElevation = false;
}
}

public enum HasPreviousNameOption
{
Yes,
No,
PreferNotToSay
}

public enum TrnLookupState
{
None = 0,
Complete = 1,
ExistingTrnFound = 3,
EmailOfExistingAccountForTrnVerified = 4
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ public record User
public required TrnAssociationSource? TrnAssociationSource { get; init; }
public required string[] StaffRoles { get; init; } = Array.Empty<string>();
public required TrnLookupStatus? TrnLookupStatus { get; init; }
public required TrnVerificationLevel? TrnVerificationLevel { get; init; }
public required string? NationalInsuranceNumber { get; init; }

public static User FromModel(Models.User user) => new()
{
Expand All @@ -29,8 +31,10 @@ public record User
StaffRoles = user.StaffRoles,
Trn = user.Trn,
MobileNumber = user.MobileNumber,
NationalInsuranceNumber = user.NationalInsuranceNumber,
TrnAssociationSource = user.TrnAssociationSource,
TrnLookupStatus = user.TrnLookupStatus,
TrnVerificationLevel = user.TrnVerificationLevel,
UserId = user.UserId,
UserType = user.UserType
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,9 @@ public enum UserUpdatedEventChanges
TrnLookupStatus = 1 << 5,
MobileNumber = 1 << 6,
MiddleName = 1 << 7,
PreferredName = 1 << 8
PreferredName = 1 << 8,
TrnVerificationLevel = 1 << 9,
NationalInsuranceNumber = 1 << 10,
}

public enum UserUpdatedEventSource
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,10 @@ protected virtual string Page(string pageName, bool authenticationJourneyRequire

public string RegisterNoAccount() => Page("/SignIn/Register/NoAccount");

public string ElevateLanding() => Page("/SignIn/Elevate/Landing");

public string ElevateCheckAnswers() => Page("/SignIn/Elevate/CheckAnswers");

public string Account(ClientRedirectInfo? clientRedirectInfo) =>
Page("/Account/Index", authenticationJourneyRequired: false)
.SetQueryParam(ClientRedirectInfo.QueryParameterName, clientRedirectInfo);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using TeacherIdentity.AuthServer.Models;
using TeacherIdentity.AuthServer.Oidc;
using TeacherIdentity.AuthServer.Services.BackgroundJobs;
using User = TeacherIdentity.AuthServer.Models.User;
Expand Down Expand Up @@ -57,7 +58,7 @@ await _backgroundJobScheduler.Enqueue<UserHelper>(
AuthenticationState.IttProviderName,
AuthenticationState.StatedTrn,
client.DisplayName,
AuthenticationState.OAuthState.TrnRequirementType == Models.TrnRequirementType.Required));
AuthenticationState.OAuthState.TrnRequirementType == TrnRequirementType.Required));
}
}
}
Expand Down Expand Up @@ -98,6 +99,18 @@ protected override bool IsFinished() =>
AuthenticationState.TrnLookupStatus.HasValue &&
AuthenticationState.TrnLookup == AuthenticationState.TrnLookupState.Complete;

public override bool IsCompleted()
{
var finished = IsFinished();

if (finished && AuthenticationState.RequiresTrnVerificationLevelElevation == true)
{
return false;
}

return finished;
}

public override bool CanAccessStep(string step) => step switch
{
CoreSignInJourney.Steps.CheckAnswers => (AreAllQuestionsAnswered() || FoundATrn) && AuthenticationState.ContactDetailsVerified,
Expand All @@ -113,8 +126,22 @@ protected override bool IsFinished() =>
_ => base.CanAccessStep(step)
};

public override string GetNextStepUrl(string currentStep) =>
currentStep switch
{
ElevateTrnVerificationLevelJourney.Steps.Landing => ElevateTrnVerificationLevelJourney.GetStartStepUrl(LinkGenerator),
_ => base.GetNextStepUrl(currentStep)
};

protected override string? GetNextStep(string currentStep)
{
// If we've signed a user in successfully and the TrnMatchPolicy is Strict
// but the user's TrnVerificationLevel is Low (or null) we need to switch to the 'elevate' journey
if (IsFinished() && AuthenticationState.RequiresTrnVerificationLevelElevation == true)
{
return ElevateTrnVerificationLevelJourney.GetStartStepUrl(LinkGenerator);
}

var shouldCheckAnswers = (AreAllQuestionsAnswered() || FoundATrn) && !AuthenticationState.ExistingAccountFound;

return (currentStep, AuthenticationState) switch
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
using System.Diagnostics;

namespace TeacherIdentity.AuthServer.Journeys;

public class ElevateTrnVerificationLevelJourney : SignInJourney
{
private readonly TrnLookupHelper _trnLookupHelper;

public ElevateTrnVerificationLevelJourney(
TrnLookupHelper trnLookupHelper,
HttpContext httpContext,
IdentityLinkGenerator linkGenerator,
UserHelper userHelper) :
base(httpContext, linkGenerator, userHelper)
{
_trnLookupHelper = trnLookupHelper;
}

public static string GetStartStepUrl(IdentityLinkGenerator linkGenerator) => linkGenerator.ElevateLanding();

public async Task LookupTrn()
{
var trn = await _trnLookupHelper.LookupTrn(AuthenticationState);
Debug.Assert(AuthenticationState.TrnVerificationElevationSuccessful.HasValue);

if (trn is not null)
{
Debug.Assert(AuthenticationState.TrnVerificationElevationSuccessful == true);
await UserHelper.ElevateTrnVerificationLevel(AuthenticationState.UserId!.Value, trn, AuthenticationState.NationalInsuranceNumber!);
}
else
{
Debug.Assert(AuthenticationState.TrnVerificationElevationSuccessful == false);
await UserHelper.SetNationalInsuranceNumber(AuthenticationState.UserId!.Value, AuthenticationState.NationalInsuranceNumber!);
}
}

public override bool CanAccessStep(string step) => step switch
{
Steps.Landing => true,
CoreSignInJourneyWithTrnLookup.Steps.NiNumber => true,
CoreSignInJourneyWithTrnLookup.Steps.Trn => AuthenticationState.HasNationalInsuranceNumber == true,
Steps.CheckAnswers => AuthenticationState.HasNationalInsuranceNumber == true && AuthenticationState.StatedTrn is not null,
_ => false
};

protected override string? GetNextStep(string currentStep) => currentStep switch
{
Steps.Landing => CoreSignInJourneyWithTrnLookup.Steps.NiNumber,
CoreSignInJourneyWithTrnLookup.Steps.NiNumber => CoreSignInJourneyWithTrnLookup.Steps.Trn,
CoreSignInJourneyWithTrnLookup.Steps.Trn => Steps.CheckAnswers,
_ => null
};

protected override string? GetPreviousStep(string currentStep) => currentStep switch
{
CoreSignInJourneyWithTrnLookup.Steps.NiNumber => Steps.Landing,
CoreSignInJourneyWithTrnLookup.Steps.Trn => CoreSignInJourneyWithTrnLookup.Steps.NiNumber,
Steps.CheckAnswers => CoreSignInJourneyWithTrnLookup.Steps.Trn,
_ => null
};

protected override string GetStartStep() => Steps.Landing;

protected override string GetStepUrl(string step) => step switch
{
Steps.Landing => LinkGenerator.ElevateLanding(),
CoreSignInJourneyWithTrnLookup.Steps.NiNumber => LinkGenerator.RegisterNiNumber(),
CoreSignInJourneyWithTrnLookup.Steps.Trn => LinkGenerator.RegisterTrn(),
Steps.CheckAnswers => LinkGenerator.ElevateCheckAnswers(),
_ => throw new ArgumentException($"Unknown step: '{step}'.")
};

// We're done when we've done a lookup, successful or not, using the Strict TrnMatchPolicy
protected override bool IsFinished() => AuthenticationState.TrnVerificationElevationSuccessful.HasValue;

public new static class Steps
{
public const string Landing = $"{nameof(ElevateTrnVerificationLevelJourney)}.{nameof(Landing)}";
public const string CheckAnswers = $"{nameof(ElevateTrnVerificationLevelJourney)}.{nameof(CheckAnswers)}";
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ public static IServiceCollection AddSignInJourneyStateProvider(this IServiceColl
return provider.GetSignInJourney(authenticationState, httpContext);
});

services.AddTransient<ElevateTrnVerificationLevelJourney>(sp => (ElevateTrnVerificationLevelJourney)sp.GetRequiredService<SignInJourney>());

services
.AddTransient<TrnLookupHelper>()
.AddTransient<UserHelper>()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ public virtual string GetNextStepUrl(string currentStep)

if (!CanAccessStep(nextStep))
{
throw new InvalidOperationException($"Next step is not accessible (step: '{nextStep}', EmailAddressVerified: {AuthenticationState.EmailAddressVerified}, MobileNumberVerified: {AuthenticationState.MobileNumberVerified}).");
throw new InvalidOperationException($"Next step is not accessible (step: '{nextStep}').");
}

return GetStepUrl(nextStep);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ public class SignInJourneyProvider
{
public SignInJourney GetSignInJourney(AuthenticationState authenticationState, HttpContext httpContext)
{
var signInJourneyType = typeof(CoreSignInJourney);

if (authenticationState.TryGetOAuthState(out var oAuthState) && authenticationState.UserRequirements.RequiresTrnLookup())
{
#pragma warning disable CS0612 // Type or member is obsolete
Expand All @@ -15,16 +17,16 @@ public SignInJourney GetSignInJourney(AuthenticationState authenticationState, H
}
#pragma warning restore CS0612 // Type or member is obsolete

return authenticationState.HasTrnToken ?
ActivatorUtilities.CreateInstance<TrnTokenSignInJourney>(httpContext.RequestServices, httpContext) :
ActivatorUtilities.CreateInstance<CoreSignInJourneyWithTrnLookup>(httpContext.RequestServices, httpContext);
signInJourneyType = authenticationState.HasTrnToken ? typeof(TrnTokenSignInJourney) :
authenticationState.RequiresTrnVerificationLevelElevation == true ? typeof(ElevateTrnVerificationLevelJourney) :
typeof(CoreSignInJourneyWithTrnLookup);
}

if (authenticationState.UserRequirements.HasFlag(UserRequirements.StaffUserType))
{
return ActivatorUtilities.CreateInstance<StaffSignInJourney>(httpContext.RequestServices, httpContext);
signInJourneyType = typeof(StaffSignInJourney);
}

return ActivatorUtilities.CreateInstance<CoreSignInJourney>(httpContext.RequestServices, httpContext);
return (SignInJourney)ActivatorUtilities.CreateInstance(httpContext.RequestServices, signInJourneyType, httpContext);
}
}
Loading

0 comments on commit 4f6e279

Please sign in to comment.