SPB Git

Repository Public

IdentityVerificationView.swift 12.3 KB 299 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : MacLustr Identity9// File             : sdk/swift/Sources/MacLustrIdentityUI/IdentityVerificationView.swift10// Module           : MacLustrIdentityUI11// Repository       : https://git.spboucher.ai/maclustr-identity12// Project Website  : https://identity.spboucher.ai13// Created          : 2026-12-0114// Last Modified    : 2026-12-0115//16// =============================================================================17// AUTHOR & PROFESSIONAL AFFILIATION18// =============================================================================19//20// Author           : Simon-Pierre Boucher21// Position         : Professor of Finance22// Institution      : Université du Québec en Outaouais (UQO)23// Department       : Département des sciences administratives24// Organization     : SP Boucher25//26// Website          : https://spboucher.ai27// Git              : https://git.spboucher.ai28//29// =============================================================================30// OFFICIAL CONTACT DIRECTORY31// =============================================================================32//33// General          : info@spboucher.ai34// Professional     : contact@spboucher.ai35// Direct           : simon@spboucher.ai36// Research         : research@spboucher.ai37// Development      : dev@spboucher.ai38// Support          : support@spboucher.ai39// Security/Admin   : admin@spboucher.ai40// Notifications    : notifications@spboucher.ai41//42// Preferred Contact: admin@spboucher.ai43//44// =============================================================================45// COPYRIGHT & INTELLECTUAL PROPERTY46// =============================================================================47//48// Copyright (c) 202649// Simon-Pierre Boucher50//51// All rights reserved where applicable.52//53// This file is governed by the applicable project license,54// copyright notices, institutional agreements and relevant law.55//56// Unless expressly authorized by the applicable license or57// rights holder, copying, redistribution, sublicensing,58// publication and commercial exploitation are not permitted.59//60// Existing third-party rights and notices remain unaffected.61//62// =============================================================================63// CONFIDENTIALITY & SECURITY64// =============================================================================65//66// Classification   : Public67// Distribution     : Public repository; use is governed by the project license68// Security Contact : admin@spboucher.ai69//70// Access to this source does not independently grant permission71// to redistribute or disclose confidential materials.72//73// Do not embed credentials, private keys, access tokens,74// certificates or confidential personal information.75//76// =============================================================================77// LICENSE & MAINTENANCE78// =============================================================================79//80// License          : None specified (no license file in this repository)81// Maintainer       : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788// Entry points of the native flow.89import SwiftUI90import MacLustrIdentityCore9192/// The complete native verification flow for one session.93///94/// ```swift95/// IdentityVerificationView(session: session) { result in96///     // UX only. Ask your backend for the actual outcome.97/// }98/// ```99/// The host app must declare `NSCameraUsageDescription` in its Info.plist.100public struct IdentityVerificationView: View {101    private let configuration: IdentityConfiguration102    private let onFinish: (IdentityVerificationResult) -> Void103    @StateObject private var flow: VerificationFlowModel104    @State private var confirmLeave = false105    @State private var confirmWithdraw = false106    @State private var finished = false107108    /// - Parameters:109    ///   - session: the session created by your backend (`IdentitySession(url:)` or id + client secret).110    ///   - onFinish: called once, when the flow ends or is left.111    public init(session: IdentitySession, configuration: IdentityConfiguration = IdentityConfiguration(), onFinish: @escaping (IdentityVerificationResult) -> Void) {112        self.configuration = configuration113        self.onFinish = onFinish114        _flow = StateObject(wrappedValue: VerificationFlowModel(client: IdentityClient(session: session, transport: configuration.transport, retryPolicy: configuration.retryPolicy),115                                                                 language: configuration.language))116    }117118    private var accent: Color {119        configuration.accentColor ?? Color(identityHex: flow.state?.application.accent) ?? .accentColor120    }121122    public var body: some View {123        let lang = flow.language124        VStack(spacing: 0) {125            header(lang)126            Divider()127            stepView128                .frame(maxWidth: .infinity, maxHeight: .infinity)129            footer(lang)130        }131        .background(Color.identityBackground.ignoresSafeArea())132        .tint(accent)133        .accentColor(accent)134        .environment(\.identityLanguage, lang)135        .environment(\.locale, Locale(identifier: lang == .fr ? "fr_CA" : "en_CA"))136        .task { if flow.step == .loading { await flow.start() } }137        .onDisappear { flow.stop() }138        .confirmationDialog(IdentityString.leaveConfirmTitle.text(lang), isPresented: $confirmLeave, titleVisibility: .visible) {139            Button(IdentityString.leave.text(lang)) { finish() }140            if flow.canWithdraw {141                // Never destroys anything by itself: it only opens the confirmation below, once this dialog is gone.142                Button(IdentityString.withdrawAction.text(lang), role: .destructive) {143                    DispatchQueue.main.asyncAfter(deadline: .now() + 0.35) { confirmWithdraw = true }144                }145            }146            Button(IdentityString.stay.text(lang), role: .cancel) {}147        } message: {148            Text(IdentityString.leaveConfirmBody.text(lang))149        }150        .confirmationDialog(IdentityString.withdrawConfirmTitle.text(lang), isPresented: $confirmWithdraw, titleVisibility: .visible) {151            Button(IdentityString.withdrawConfirm.text(lang), role: .destructive) { Task { await flow.withdraw() } }152            Button(IdentityString.cancel.text(lang), role: .cancel) {}153        } message: {154            Text(IdentityString.withdrawConfirmBody.text(lang))155        }156        .interactiveDismissDisabled()157    }158159    @ViewBuilder160    private var stepView: some View {161        switch flow.step {162        case .loading:163            ProgressView().controlSize(.large)164        case .intro:165            IntroStepView(flow: flow)166        case .method:167            MethodStepView(flow: flow)168        case .consent(let id):169            ConsentStepView(flow: flow, methodID: id).id(id)170        case .sandbox:171            SandboxStepView(flow: flow)172        case .documentFront:173            DocumentCaptureView(flow: flow, side: .front, configuration: configuration).id("front")174        case .documentBack:175            DocumentCaptureView(flow: flow, side: .back, configuration: configuration).id("back")176        case .selfie:177            SelfieCaptureView(flow: flow)178        case .submitting:179            ProgressStepView(flow: flow, submitting: true, onClose: finish)180        case .processing:181            ProgressStepView(flow: flow, submitting: false, onClose: finish)182        case .result(let status):183            ResultStepView(flow: flow, status: status, onClose: finish)184        case .failed(let error):185            FailedStepView(flow: flow, error: error, onClose: finish)186        }187    }188189    private func header(_ lang: IdentityLanguage) -> some View {190        HStack(spacing: 10) {191            Button(closeLabel(lang)) { close() }192                .accessibilityIdentifier("mlid.close")193            Spacer(minLength: 8)194            if let app = flow.state?.application {195                if let logo = app.logoURL, let url = URL(string: logo), url.scheme == "https" {196                    AsyncImage(url: url) { image in197                        image.resizable().scaledToFit()198                    } placeholder: {199                        Color.clear200                    }201                    .frame(width: 24, height: 24)202                    .clipShape(RoundedRectangle(cornerRadius: 5, style: .continuous))203                    .accessibilityLabel(IdentityString.a11yLogo.text(lang, app.name))204                }205                Text(app.name).font(.subheadline.weight(.semibold)).lineLimit(1)206            }207            Spacer(minLength: 8)208            // Balances the close button so that the name stays centred.209            Button(closeLabel(lang)) {}.hidden().accessibilityHidden(true)210        }211        .padding(.horizontal, 16)212        .padding(.vertical, 10)213    }214215    private func footer(_ lang: IdentityLanguage) -> some View {216        VStack(spacing: 4) {217            if flow.isSandbox {218                Text(IdentityString.sandboxBadge.text(lang))219                    .font(.caption.weight(.semibold))220                    .padding(.horizontal, 10).padding(.vertical, 4)221                    .background(Capsule().fill(Color.orange.opacity(0.18)))222            }223            HStack(spacing: 5) {224                Image(systemName: "lock.shield").accessibilityHidden(true)225                Text(IdentityString.processedBy.text(lang))226            }227            .font(.caption)228            .foregroundStyle(.secondary)229        }230        .frame(maxWidth: .infinity)231        .padding(.vertical, 8)232        .accessibilityElement(children: .combine)233    }234235    private var isTerminal: Bool {236        switch flow.step {237        case .result, .failed, .loading: return true238        default: return false239        }240    }241242    private func closeLabel(_ lang: IdentityLanguage) -> String {243        (isTerminal ? IdentityString.close : IdentityString.cancel).text(lang)244    }245246    private func close() {247        if isTerminal || flow.step == .intro { finish() } else { confirmLeave = true }248    }249250    private func finish() {251        guard !finished else { return }252        finished = true253        let result = flow.resultForDismissal254        flow.stop()255        onFinish(result)256    }257}258259public extension View {260    /// Presents the native verification flow: full screen on iOS, a sheet on macOS.261    /// - Parameters:262    ///   - isPresented: set to true to start; reset to false when the flow ends.263    ///   - session: the session created by your backend. Nothing is presented while it is nil.264    ///   - onFinish: called once with the outcome (UX only: trust your backend for the result).265    func identityVerification(isPresented: Binding<Bool>, session: IdentitySession?, configuration: IdentityConfiguration = IdentityConfiguration(),266                              onFinish: @escaping (IdentityVerificationResult) -> Void) -> some View {267        modifier(IdentityVerificationModifier(isPresented: isPresented, session: session, configuration: configuration, onFinish: onFinish))268    }269}270271private struct IdentityVerificationModifier: ViewModifier {272    @Binding var isPresented: Bool273    let session: IdentitySession?274    let configuration: IdentityConfiguration275    let onFinish: (IdentityVerificationResult) -> Void276277    private var presented: Binding<Bool> {278        Binding(get: { isPresented && session != nil }, set: { isPresented = $0 })279    }280281    @ViewBuilder282    private var flow: some View {283        if let session {284            IdentityVerificationView(session: session, configuration: configuration) { result in285                isPresented = false286                onFinish(result)287            }288        }289    }290291    func body(content: Content) -> some View {292        #if os(iOS)293        content.fullScreenCover(isPresented: presented) { flow }294        #else295        content.sheet(isPresented: presented) { flow.frame(minWidth: 480, idealWidth: 560, minHeight: 640, idealHeight: 760) }296        #endif297    }298}299
Files main
Menu

Theme