SPB Git

Repository Public

SecurityScreens.swift 11.9 KB 231 lines swift

1// SP Notes iOS2// File: Features/Settings/SecurityScreens.swift3// Description: The passkeys of the account (list, add, rename, delete — never the last one) and the open sessions (revoke one,4//              revoke the others). Both need the server: offline they say so instead of showing stale data.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import SPNotesCore9import SwiftUI1011/// Why an online-only screen has nothing to show.12private struct OnlineOnlyNotice: View {13    @Environment(AppModel.self) private var app14    let what: LocalizedStringKey1516    var body: some View {17        if app.session != .signedIn {18            EmptyStateView(symbol: "person.crop.circle.badge.exclamationmark", title: "Session terminée", message: "Reconnecte-toi depuis les réglages pour gérer \(Text(what)).")19        } else {20            EmptyStateView(symbol: "wifi.slash", title: "Hors ligne", message: "La gestion de \(Text(what)) se fait sur le serveur : elle sera disponible au retour du réseau.")21        }22    }23}2425struct PasskeysScreen: View {26    @Environment(AppModel.self) private var app27    @State private var passkeys: [PasskeyInfo] = []28    @State private var loaded = false29    @State private var isWorking = false30    @State private var message: String?31    @State private var showsAdd = false32    @State private var newLabel = ""33    @State private var renaming: PasskeyInfo?34    @State private var renameLabel = ""35    @State private var deleting: PasskeyInfo?3637    private var available: Bool { app.session == .signedIn && app.network.isOnline }3839    var body: some View {40        Group {41            if !available {42                OnlineOnlyNotice(what: "tes clés d’accès")43            } else {44                List {45                    Section {46                        ForEach(passkeys) { passkey in47                            VStack(alignment: .leading, spacing: 3) {48                                HStack {49                                    Text(passkey.label?.isEmpty == false ? passkey.label! : String(localized: "Clé d’accès")).foregroundStyle(Color.spText)50                                    if passkey.current == true { Text("Utilisée pour cette session").font(.caption).foregroundStyle(Color.spSuccess) }51                                }52                                Text(PasskeyText.detail(passkey)).font(.footnote).foregroundStyle(Color.spTextSecondary)53                            }54                            .padding(.vertical, 2)55                            .swipeActions(edge: .trailing, allowsFullSwipe: false) {56                                if passkeys.count > 1 {57                                    Button(role: .destructive) { deleting = passkey } label: { Label("Supprimer", systemImage: "trash") }58                                }59                                Button { renameLabel = passkey.label ?? ""; renaming = passkey } label: { Label("Renommer", systemImage: "pencil") }.tint(.indigo)60                            }61                            .contextMenu {62                                Button { renameLabel = passkey.label ?? ""; renaming = passkey } label: { Label("Renommer", systemImage: "pencil") }63                                Button(role: .destructive) { deleting = passkey } label: { Label("Supprimer", systemImage: "trash") }.disabled(passkeys.count <= 1)64                            }65                        }66                        if !loaded { HStack { Spacer(); ProgressView(); Spacer() } }67                    } footer: {68                        if passkeys.count == 1 { Text("C’est la seule clé d’accès du compte : elle ne peut pas être supprimée. Ajoutes-en une autre avant de la retirer.") }69                    }70                    Section {71                        Button {72                            newLabel = UIDevice.current.name73                            showsAdd = true74                        } label: { Label("Ajouter une clé d’accès sur cet appareil", systemImage: "plus") }75                        .disabled(isWorking)76                        .accessibilityIdentifier("add-passkey")77                    } footer: {78                        if let message { Text(message).foregroundStyle(Color.spDanger) }79                        else { Text("Ajouter ou supprimer une clé demande de confirmer avec une clé existante.") }80                    }81                }82                .refreshable { await load() }83            }84        }85        .navigationTitle("Clés d’accès")86        .navigationBarTitleDisplayMode(.inline)87        .task(id: available) { if available { await load() } }88        .alert("Nouvelle clé d’accès", isPresented: $showsAdd) {89            TextField("Nom (ex. iPhone de Simon)", text: $newLabel)90            Button("Créer") { run { _ = try await app.auth.addPasskey(label: String(newLabel.trimmingCharacters(in: .whitespaces).prefix(60)).nilIfEmpty) } }91            Button("Annuler", role: .cancel) {}92        } message: { Text("Elle sera enregistrée dans le trousseau de cet appareil.") }93        .alert("Renommer la clé d’accès", isPresented: Binding(get: { renaming != nil }, set: { if !$0 { renaming = nil } }), presenting: renaming) { passkey in94            TextField("Nom", text: $renameLabel)95            Button("Renommer") {96                let label = String(renameLabel.trimmingCharacters(in: .whitespaces).prefix(60))97                guard !label.isEmpty else { return }98                let api = app.api99                run { try await api.renamePasskey(id: passkey.id, label: label) }100            }101            Button("Annuler", role: .cancel) {}102        }103        .confirmationDialog("Supprimer cette clé d’accès ?", isPresented: Binding(get: { deleting != nil }, set: { if !$0 { deleting = nil } }), titleVisibility: .visible, presenting: deleting) { passkey in104            Button("Supprimer", role: .destructive) {105                let api = app.api, auth = app.auth, id = passkey.id106                run { try await auth.withFreshSession { try await api.deletePasskey(id: id) } }107            }108            Button("Annuler", role: .cancel) {}109        } message: { _ in Text("Elle ne pourra plus ouvrir de session. Les sessions déjà ouvertes avec elle restent actives jusqu’à leur révocation.") }110    }111112    private func load() async {113        do { passkeys = try await app.api.passkeys(); message = nil } catch { message = SignInFailure(error).message }114        loaded = true115    }116117    private func run(_ work: @escaping @MainActor () async throws -> Void) {118        Task {119            isWorking = true120            defer { isWorking = false }121            do { try await work(); message = nil } catch { message = SignInFailure(error).message }122            await load()123        }124    }125}126127enum PasskeyText {128    static func detail(_ passkey: PasskeyInfo) -> String {129        var parts: [String] = []130        if let created = passkey.createdAt { parts.append(String(localized: "Créée le \(created.formatted(date: .abbreviated, time: .omitted))")) }131        if let used = passkey.lastUsedAt { parts.append(String(localized: "utilisée \(used.formatted(.relative(presentation: .named)))")) }132        if passkey.synced == true || passkey.multiDevice == true { parts.append(String(localized: "synchronisée entre appareils")) }133        return parts.isEmpty ? String(localized: "Aucun détail") : parts.joined(separator: " · ")134    }135}136137private extension String {138    var nilIfEmpty: String? { isEmpty ? nil : self }139}140141struct SessionsScreen: View {142    @Environment(AppModel.self) private var app143    @State private var sessions: [SessionInfo] = []144    @State private var loaded = false145    @State private var message: String?146    @State private var confirmRevokeOthers = false147148    private var available: Bool { app.session == .signedIn && app.network.isOnline }149150    var body: some View {151        Group {152            if !available {153                OnlineOnlyNotice(what: "tes sessions")154            } else {155                List {156                    Section {157                        ForEach(sessions) { session in158                            HStack {159                                VStack(alignment: .leading, spacing: 3) {160                                    Text(session.label?.isEmpty == false ? session.label! : String(localized: "Session")).foregroundStyle(Color.spText)161                                    Text(SessionText.detail(session)).font(.footnote).foregroundStyle(Color.spTextSecondary)162                                }163                                Spacer()164                                if session.current { Text("Cet appareil").font(.caption.weight(.semibold)).foregroundStyle(Color.spSuccess) }165                            }166                            .padding(.vertical, 2)167                            .swipeActions(edge: .trailing, allowsFullSwipe: false) {168                                if !session.current {169                                    Button(role: .destructive) { revoke(session) } label: { Label("Révoquer", systemImage: "xmark.circle") }170                                }171                            }172                            .contextMenu {173                                if !session.current { Button(role: .destructive) { revoke(session) } label: { Label("Révoquer", systemImage: "xmark.circle") } }174                            }175                        }176                        if !loaded { HStack { Spacer(); ProgressView(); Spacer() } }177                    } footer: {178                        if let message { Text(message).foregroundStyle(Color.spDanger) }179                        else { Text("Balaye une session pour la révoquer : l’appareil concerné devra se reconnecter.") }180                    }181                    if sessions.contains(where: { !$0.current }) {182                        Section {183                            Button("Révoquer toutes les autres sessions", role: .destructive) { confirmRevokeOthers = true }184                                .accessibilityIdentifier("revoke-others")185                        } footer: { Text("Demande une confirmation avec ta clé d’accès.") }186                    }187                }188                .refreshable { await load() }189            }190        }191        .navigationTitle("Sessions ouvertes")192        .navigationBarTitleDisplayMode(.inline)193        .task(id: available) { if available { await load() } }194        .confirmationDialog("Révoquer toutes les autres sessions ?", isPresented: $confirmRevokeOthers, titleVisibility: .visible) {195            Button("Révoquer", role: .destructive) {196                let api = app.api, auth = app.auth197                run { _ = try await auth.withFreshSession { try await api.revokeAllSessions(includeCurrent: false) } }198            }199            Button("Annuler", role: .cancel) {}200        } message: { Text("Cet appareil reste connecté.") }201    }202203    private func revoke(_ session: SessionInfo) {204        let api = app.api, auth = app.auth, id = session.id205        run { _ = try await auth.withFreshSession { try await api.revokeSession(id: id) } }206    }207208    private func load() async {209        do { sessions = try await app.api.sessions().sorted { ($0.current ? 1 : 0, $0.lastSeenAt ?? $0.createdAt) > ($1.current ? 1 : 0, $1.lastSeenAt ?? $1.createdAt) }; message = nil }210        catch { message = SignInFailure(error).message }211        loaded = true212    }213214    private func run(_ work: @escaping @MainActor () async throws -> Void) {215        Task {216            do { try await work(); message = nil } catch { message = SignInFailure(error).message }217            await load()218        }219    }220}221222enum SessionText {223    static func detail(_ session: SessionInfo) -> String {224        var parts: [String] = []225        if let seen = session.lastSeenAt { parts.append(String(localized: "Active \(seen.formatted(.relative(presentation: .named)))")) }226        else { parts.append(String(localized: "Ouverte le \(session.createdAt.formatted(date: .abbreviated, time: .omitted))")) }227        if let ip = session.ip, !ip.isEmpty { parts.append(ip) }228        return parts.joined(separator: " · ")229    }230}231
Files main
Menu

Theme