SPB Git

Repository Public

IdentityDemoApp.swift 8.1 KB 202 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : MacLustr Identity9// File             : sdk/swift/Examples/IdentityDemo/Sources/IdentityDemoApp.swift10// Module           : sdk11// 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// Demo app: paste a hosted URL, or fetch one from a demo backend, then run the native or the web flow.89import MacLustrIdentity90import SwiftUI9192@main93struct IdentityDemoApp: App {94    var body: some Scene {95        WindowGroup { DemoView() }96    }97}9899struct DemoView: View {100    @AppStorage("demoBackendURL") private var backendURL = "http://127.0.0.1:8899"101    @State private var hostedURL = ""102    @State private var session: IdentitySession?103    @State private var presenting = false104    @State private var message = ""105    @State private var backendStatus = ""106    @State private var busy = false107108    var body: some View {109        Form {110            Section("1. Session") {111                TextField("Hosted URL (https://…/verify/vs_…#vsc_…)", text: $hostedURL, axis: .vertical)112                    .autocorrectionDisabled()113                    #if os(iOS)114                    .textInputAutocapitalization(.never)115                    .keyboardType(.URL)116                    #endif117                TextField("Demo backend URL", text: $backendURL)118                    .autocorrectionDisabled()119                    #if os(iOS)120                    .textInputAutocapitalization(.never)121                    .keyboardType(.URL)122                    #endif123                Button("Fetch a session from the demo backend") { Task { await fetchSession() } }124                    .disabled(busy)125            }126            Section("2. Flow") {127                Button("Start the native flow") { start(native: true) }128                Button("Start the web flow") { start(native: false) }129            }130            Section("Outcome reported by the SDK (UX only)") {131                Text(message.isEmpty ? "Nothing yet" : message)132                if !backendStatus.isEmpty {133                    Text("Backend says: \(backendStatus)").font(.headline)134                }135                Text("An app must trust only its own backend (webhook or GET /v1/verifications/{id}), never this callback.")136                    .font(.footnote)137                    .foregroundStyle(.secondary)138            }139        }140        .formStyle(.grouped)141        .onAppear {142            // Launch arguments for automation: -hostedURL <url> [-autostart YES]143            if let url = UserDefaults.standard.string(forKey: "hostedURL"), hostedURL.isEmpty {144                hostedURL = url145                if UserDefaults.standard.bool(forKey: "autostart") { start(native: true) }146            }147        }148        .identityVerification(isPresented: $presenting, session: session) { result in149            switch result {150            case .completed(let status): message = "completed: \(status.rawValue)"151            case .canceled: message = "canceled"152            case .failed(let error): message = "failed: \(error)"153            }154            Task { await fetchResult() }155        }156    }157158    private func start(native: Bool) {159        do {160            let s = try IdentitySession(urlString: hostedURL)161            session = s162            backendStatus = ""163            if native {164                presenting = true165            } else {166                IdentityWebFlow.start(session: s) { result in167                    message = "web flow: \(result)"168                    Task { await fetchResult() }169                }170            }171        } catch {172            message = "This is not a valid hosted URL."173        }174    }175176    /// Asks the demo backend (which holds the API key) for a new session.177    private func fetchSession() async {178        busy = true179        defer { busy = false }180        struct Created: Decodable { let url: String }181        guard let url = URL(string: backendURL + "/session") else { return }182        var request = URLRequest(url: url)183        request.httpMethod = "POST"184        do {185            let (data, _) = try await URLSession.shared.data(for: request)186            hostedURL = try JSONDecoder().decode(Created.self, from: data).url187            message = "Session created by the demo backend."188        } catch {189            message = "The demo backend did not answer. See Examples/demo-backend/server.py."190        }191    }192193    /// Asks the demo backend for the actual status: this is the value an app should act on.194    private func fetchResult() async {195        struct Result: Decodable { let status: String }196        guard let id = session?.id, let url = URL(string: backendURL + "/result/" + id),197              let (data, _) = try? await URLSession.shared.data(from: url),198              let r = try? JSONDecoder().decode(Result.self, from: data) else { return }199        backendStatus = r.status200    }201}202
Files main
Menu

Theme