Add Email/Terms/ReCaptcha into the Authentication flow

Replace ReCaptcha navigation delegate with a WKUserContentController.
Move callback property closures onto the MainActor.
Show a loading indicator whilst waiting for the authentication service to start.
Move nextUncompletedStage into FlowResult.
Handle text field actions during authentication.
Remove scroll view tweaks in server selection screen following EMS banner removal.
This commit is contained in:
Doug
2022-05-12 17:40:36 +01:00
committed by Doug
parent 02e5f0bf2e
commit 1b74f87b35
42 changed files with 635 additions and 263 deletions
@@ -138,7 +138,8 @@ class AuthenticationService: NSObject {
registrationWizard = nil
// The previously used homeserver is re-used as `startFlow` will be called again a replace it anyway.
self.state = AuthenticationState(flow: .login, homeserverAddress: state.homeserver.address)
let address = state.homeserver.addressFromUser ?? state.homeserver.address
self.state = AuthenticationState(flow: .login, homeserverAddress: address)
}
/// Create a session after a SSO successful login
@@ -101,6 +101,14 @@ struct AuthenticationParameters: Codable {
}
}
/// The result from a registration screen's coordinator
enum AuthenticationRegistrationStageResult {
/// The screen completed with the associated registration result.
case completed(RegistrationResult)
/// The user would like to cancel the registration.
case cancel
}
/// The result from a response of a registration flow step.
enum RegistrationResult {
/// Registration has completed, creating an `MXSession` for the account.
@@ -119,30 +127,73 @@ struct FlowResult {
/// A stage in the authentication flow.
enum Stage {
/// The stage with the type `m.login.recaptcha`.
case reCaptcha(mandatory: Bool, publicKey: String)
case reCaptcha(isMandatory: Bool, siteKey: String)
/// The stage with the type `m.login.email.identity`.
case email(mandatory: Bool)
case email(isMandatory: Bool)
/// The stage with the type `m.login.msisdn`.
case msisdn(mandatory: Bool)
case msisdn(isMandatory: Bool)
/// The stage with the type `m.login.dummy`.
///
/// This stage can be mandatory if there is no other stages. In this case the account cannot
/// be created by just sending a username and a password, the dummy stage has to be completed.
case dummy(mandatory: Bool)
case dummy(isMandatory: Bool)
/// The stage with the type `m.login.terms`.
case terms(mandatory: Bool, policies: [AnyHashable: Any])
case terms(isMandatory: Bool, terms: MXLoginTerms?)
/// A stage of an unknown type.
case other(mandatory: Bool, type: String, params: [AnyHashable: Any])
case other(isMandatory: Bool, type: String, params: [AnyHashable: Any])
/// Whether the stage is a dummy stage that is also mandatory.
var isDummyAndMandatory: Bool {
guard case let .dummy(isMandatory) = self else { return false }
return isMandatory
/// Whether the stage is mandatory.
var isMandatory: Bool {
switch self {
case .reCaptcha(let isMandatory, _):
return isMandatory
case .email(let isMandatory):
return isMandatory
case .msisdn(let isMandatory):
return isMandatory
case .dummy(let isMandatory):
return isMandatory
case .terms(let isMandatory, _):
return isMandatory
case .other(let isMandatory, _, _):
return isMandatory
}
}
/// Whether the stage is the dummy stage.
var isDummy: Bool {
guard case .dummy = self else { return false }
return true
}
}
/// Determines the next stage to be completed in the flow.
var nextUncompletedStage: Stage? {
if let emailStage = missingStages.first(where: { if case .email = $0 { return true } else { return false } }) {
return emailStage
}
if let termsStage = missingStages.first(where: { if case .terms = $0 { return true } else { return false } }) {
return termsStage
}
if let reCaptchaStage = missingStages.first(where: { if case .reCaptcha = $0 { return true } else { return false } }) {
return reCaptchaStage
}
if let msisdnStage = missingStages.first(where: { if case .msisdn = $0 { return true } else { return false } }) {
return msisdnStage
}
MXLog.failure("[FlowResult.Stage] nextUncompletedStage: The dummy stage should be handled silently and any other stages should trigger the fallback flow.")
return missingStages.first
}
var needsFallback : Bool {
missingStages.filter { $0.isMandatory }.contains { stage in
if case .other = stage { return true } else { return false }
}
}
}
@@ -150,7 +201,7 @@ struct FlowResult {
extension MXAuthenticationSession {
/// The flows from the session mapped as a `FlowResult` value.
var flowResult: FlowResult {
let allFlowTypes = Set(flows.flatMap { $0.stages ?? [] })
let allFlowTypes = Set(flows.flatMap { $0.stages ?? [] }) // Using a Set here loses the order, but an order is forced during presentation anyway.
var missingStages = [FlowResult.Stage]()
var completedStages = [FlowResult.Stage]()
@@ -162,19 +213,20 @@ extension MXAuthenticationSession {
case kMXLoginFlowTypeRecaptcha:
let parameters = params[flow] as? [AnyHashable: Any]
let publicKey = parameters?["public_key"] as? String
stage = .reCaptcha(mandatory: isMandatory, publicKey: publicKey ?? "")
stage = .reCaptcha(isMandatory: isMandatory, siteKey: publicKey ?? "")
case kMXLoginFlowTypeDummy:
stage = .dummy(mandatory: isMandatory)
stage = .dummy(isMandatory: isMandatory)
case kMXLoginFlowTypeTerms:
let parameters = params[flow] as? [AnyHashable: Any]
stage = .terms(mandatory: isMandatory, policies: parameters ?? [:])
let terms = MXLoginTerms(fromJSON: parameters)
stage = .terms(isMandatory: isMandatory, terms: terms)
case kMXLoginFlowTypeMSISDN:
stage = .msisdn(mandatory: isMandatory)
stage = .msisdn(isMandatory: isMandatory)
case kMXLoginFlowTypeEmailIdentity:
stage = .email(mandatory: isMandatory)
stage = .email(isMandatory: isMandatory)
default:
let parameters = params[flow] as? [AnyHashable: Any]
stage = .other(mandatory: isMandatory, type: flow, params: parameters ?? [:])
stage = .other(isMandatory: isMandatory, type: flow, params: parameters ?? [:])
}
if let completed = completed, completed.contains(flow) {
@@ -186,13 +238,4 @@ extension MXAuthenticationSession {
return FlowResult(missingStages: missingStages, completedStages: completedStages)
}
/// Determines the next stage to be completed in the flow.
func nextUncompletedStage(flowIndex: Int = 0) -> String? {
guard flows.count < flowIndex else { return nil }
return flows[flowIndex].stages.first {
guard let completed = completed else { return false }
return !completed.contains($0)
}
}
}
@@ -144,7 +144,7 @@ class RegistrationWizard {
/// Perform the "m.login.email.identity" or "m.login.msisdn" stage.
///
/// - Parameter threePID the threePID to add to the account. If this is an email, the homeserver will send an email
/// - Parameter threePID: the threePID to add to the account. If this is an email, the homeserver will send an email
/// to validate it. For a msisdn a SMS will be sent.
func addThreePID(threePID: RegisterThreePID) async throws -> RegistrationResult {
state.currentThreePIDData = nil
@@ -168,15 +168,19 @@ class RegistrationWizard {
/// Useful to poll the homeserver when waiting for the email to be validated by the user.
/// Once the email is validated, this method will return successfully.
/// - Parameter delay How long to wait before sending the request.
func checkIfEmailHasBeenValidated(delay: TimeInterval) async throws -> RegistrationResult {
MXLog.failure("The delay on this method is no longer available. Move this to the object handling the polling.")
func checkIfEmailHasBeenValidated() async throws -> RegistrationResult {
guard let parameters = state.currentThreePIDData?.registrationParameters else {
MXLog.error("[RegistrationWizard] checkIfEmailHasBeenValidated: The current 3pid data hasn't been stored in the state.")
throw RegistrationError.missingThreePIDData
}
return try await performRegistrationRequest(parameters: parameters)
do {
return try await performRegistrationRequest(parameters: parameters)
} catch {
// An unauthorized error indicates that the user hasn't tapped the link yet.
guard isUnauthorized(error) else { throw error }
throw RegistrationError.waitingForThreePIDValidation
}
}
// MARK: - Private
@@ -237,8 +241,14 @@ class RegistrationWizard {
state.currentThreePIDData = ThreePIDData(threePID: threePID, registrationResponse: response, registrationParameters: parameters)
// Send the session id for the first time
return try await performRegistrationRequest(parameters: parameters)
do {
// Send the session id for the first time
return try await performRegistrationRequest(parameters: parameters)
} catch {
// An unauthorized error means that it was accepted and is awaiting validation.
guard isUnauthorized(error) else { throw error }
throw RegistrationError.waitingForThreePIDValidation
}
}
private func performRegistrationRequest(parameters: RegistrationParameters, isCreatingAccount: Bool = false) async throws -> RegistrationResult {
@@ -268,7 +278,13 @@ class RegistrationWizard {
/// Checks for a mandatory dummy stage and handles it automatically when possible.
private func handleMandatoryDummyStage(flowResult: FlowResult) async throws -> RegistrationResult {
// If the dummy stage is mandatory, do the dummy stage now
guard flowResult.missingStages.contains(where: { $0.isDummyAndMandatory }) else { return .flowResponse(flowResult) }
guard flowResult.missingStages.contains(where: { $0.isDummy && $0.isMandatory }) else { return .flowResponse(flowResult) }
return try await dummy()
}
/// Checks whether an error is an `M_UNAUTHORIZED` for handling third party ID responses.
private func isUnauthorized(_ error: Error) -> Bool {
guard let mxError = MXError(nsError: error) else { return false }
return mxError.errcode == kMXErrCodeStringUnauthorized
}
}