Add App Lock settings screen (#1917)

This commit is contained in:
Doug
2023-10-19 12:26:34 +01:00
committed by GitHub
parent 99c28784a9
commit ebd9f4c916
36 changed files with 777 additions and 78 deletions
@@ -425,6 +425,7 @@ class AppCoordinator: AppCoordinatorProtocol, AuthenticationCoordinatorDelegate,
let navigationSplitCoordinator = NavigationSplitCoordinator(placeholderCoordinator: PlaceholderScreenCoordinator())
let userSessionFlowCoordinator = UserSessionFlowCoordinator(userSession: userSession,
navigationSplitCoordinator: navigationSplitCoordinator,
appLockService: appLockFlowCoordinator.appLockService,
bugReportService: ServiceLocator.shared.bugReportService,
roomTimelineControllerFactory: RoomTimelineControllerFactory(),
appSettings: appSettings,
@@ -25,6 +25,7 @@ enum UserSessionFlowCoordinatorAction {
class UserSessionFlowCoordinator: FlowCoordinatorProtocol {
private let userSession: UserSessionProtocol
private let navigationSplitCoordinator: NavigationSplitCoordinator
private let appLockService: AppLockServiceProtocol
private let bugReportService: BugReportServiceProtocol
private let roomTimelineControllerFactory: RoomTimelineControllerFactoryProtocol
private let appSettings: AppSettings
@@ -48,6 +49,7 @@ class UserSessionFlowCoordinator: FlowCoordinatorProtocol {
init(userSession: UserSessionProtocol,
navigationSplitCoordinator: NavigationSplitCoordinator,
appLockService: AppLockServiceProtocol,
bugReportService: BugReportServiceProtocol,
roomTimelineControllerFactory: RoomTimelineControllerFactoryProtocol,
appSettings: AppSettings,
@@ -55,6 +57,7 @@ class UserSessionFlowCoordinator: FlowCoordinatorProtocol {
stateMachine = UserSessionFlowCoordinatorStateMachine()
self.userSession = userSession
self.navigationSplitCoordinator = navigationSplitCoordinator
self.appLockService = appLockService
self.bugReportService = bugReportService
self.roomTimelineControllerFactory = roomTimelineControllerFactory
self.appSettings = appSettings
@@ -328,6 +331,7 @@ class UserSessionFlowCoordinator: FlowCoordinatorProtocol {
let parameters = SettingsScreenCoordinatorParameters(navigationStackCoordinator: settingsNavigationStackCoordinator,
userIndicatorController: userIndicatorController,
userSession: userSession,
appLockService: appLockService,
bugReportService: bugReportService,
notificationSettings: userSession.clientProxy.notificationSettings,
appSettings: appSettings)
@@ -10,8 +10,26 @@ import Foundation
// swiftlint:disable explicit_type_interface function_parameter_count identifier_name line_length
// swiftlint:disable nesting type_body_length type_name vertical_whitespace_opening_braces
public enum UntranslatedL10n {
/// Screen lock
public static var commonScreenLock: String { return UntranslatedL10n.tr("Untranslated", "common_screen_lock") }
/// Unlock
public static var commonUnlock: String { return UntranslatedL10n.tr("Untranslated", "common_unlock") }
/// Change PIN code
public static var screenAppLockSettingsChangePin: String { return UntranslatedL10n.tr("Untranslated", "screen_app_lock_settings_change_pin") }
/// Allow biometric unlock
public static var screenAppLockSettingsEnableBiometricUnlock: String { return UntranslatedL10n.tr("Untranslated", "screen_app_lock_settings_enable_biometric_unlock") }
/// Allow Face ID
public static var screenAppLockSettingsEnableFaceIdIos: String { return UntranslatedL10n.tr("Untranslated", "screen_app_lock_settings_enable_face_id_ios") }
/// Allow Optic ID
public static var screenAppLockSettingsEnableOpticIdIos: String { return UntranslatedL10n.tr("Untranslated", "screen_app_lock_settings_enable_optic_id_ios") }
/// Allow Touch ID
public static var screenAppLockSettingsEnableTouchIdIos: String { return UntranslatedL10n.tr("Untranslated", "screen_app_lock_settings_enable_touch_id_ios") }
/// Remove PIN
public static var screenAppLockSettingsRemovePin: String { return UntranslatedL10n.tr("Untranslated", "screen_app_lock_settings_remove_pin") }
/// Are you sure you want to remove PIN?
public static var screenAppLockSettingsRemovePinAlertMessage: String { return UntranslatedL10n.tr("Untranslated", "screen_app_lock_settings_remove_pin_alert_message") }
/// Remove PIN?
public static var screenAppLockSettingsRemovePinAlertTitle: String { return UntranslatedL10n.tr("Untranslated", "screen_app_lock_settings_remove_pin_alert_title") }
/// %@ is locked
public static func screenAppLockTitle(_ p1: Any) -> String {
return UntranslatedL10n.tr("Untranslated", "screen_app_lock_title", String(describing: p1))
@@ -2,11 +2,12 @@
// DO NOT EDIT
// swiftlint:disable all
import AnalyticsEvents
import Combine
import Foundation
import SwiftUI
import AnalyticsEvents
import LocalAuthentication
import MatrixRustSDK
import SwiftUI
class AnalyticsClientMock: AnalyticsClientProtocol {
var isRunning: Bool {
get { return underlyingIsRunning }
@@ -115,6 +116,128 @@ class AnalyticsClientMock: AnalyticsClientProtocol {
updateUserPropertiesClosure?(userProperties)
}
}
class AppLockServiceMock: AppLockServiceProtocol {
var isEnabled: Bool {
get { return underlyingIsEnabled }
set(value) { underlyingIsEnabled = value }
}
var underlyingIsEnabled: Bool!
var biometryType: LABiometryType {
get { return underlyingBiometryType }
set(value) { underlyingBiometryType = value }
}
var underlyingBiometryType: LABiometryType!
var biometricUnlockEnabled: Bool {
get { return underlyingBiometricUnlockEnabled }
set(value) { underlyingBiometricUnlockEnabled = value }
}
var underlyingBiometricUnlockEnabled: Bool!
//MARK: - setupPINCode
var setupPINCodeCallsCount = 0
var setupPINCodeCalled: Bool {
return setupPINCodeCallsCount > 0
}
var setupPINCodeReceivedPinCode: String?
var setupPINCodeReceivedInvocations: [String] = []
var setupPINCodeReturnValue: Result<Void, AppLockServiceError>!
var setupPINCodeClosure: ((String) -> Result<Void, AppLockServiceError>)?
func setupPINCode(_ pinCode: String) -> Result<Void, AppLockServiceError> {
setupPINCodeCallsCount += 1
setupPINCodeReceivedPinCode = pinCode
setupPINCodeReceivedInvocations.append(pinCode)
if let setupPINCodeClosure = setupPINCodeClosure {
return setupPINCodeClosure(pinCode)
} else {
return setupPINCodeReturnValue
}
}
//MARK: - disable
var disableCallsCount = 0
var disableCalled: Bool {
return disableCallsCount > 0
}
var disableClosure: (() -> Void)?
func disable() {
disableCallsCount += 1
disableClosure?()
}
//MARK: - applicationDidEnterBackground
var applicationDidEnterBackgroundCallsCount = 0
var applicationDidEnterBackgroundCalled: Bool {
return applicationDidEnterBackgroundCallsCount > 0
}
var applicationDidEnterBackgroundClosure: (() -> Void)?
func applicationDidEnterBackground() {
applicationDidEnterBackgroundCallsCount += 1
applicationDidEnterBackgroundClosure?()
}
//MARK: - computeNeedsUnlock
var computeNeedsUnlockWillEnterForegroundAtCallsCount = 0
var computeNeedsUnlockWillEnterForegroundAtCalled: Bool {
return computeNeedsUnlockWillEnterForegroundAtCallsCount > 0
}
var computeNeedsUnlockWillEnterForegroundAtReceivedDate: Date?
var computeNeedsUnlockWillEnterForegroundAtReceivedInvocations: [Date] = []
var computeNeedsUnlockWillEnterForegroundAtReturnValue: Bool!
var computeNeedsUnlockWillEnterForegroundAtClosure: ((Date) -> Bool)?
func computeNeedsUnlock(willEnterForegroundAt date: Date) -> Bool {
computeNeedsUnlockWillEnterForegroundAtCallsCount += 1
computeNeedsUnlockWillEnterForegroundAtReceivedDate = date
computeNeedsUnlockWillEnterForegroundAtReceivedInvocations.append(date)
if let computeNeedsUnlockWillEnterForegroundAtClosure = computeNeedsUnlockWillEnterForegroundAtClosure {
return computeNeedsUnlockWillEnterForegroundAtClosure(date)
} else {
return computeNeedsUnlockWillEnterForegroundAtReturnValue
}
}
//MARK: - unlock
var unlockWithCallsCount = 0
var unlockWithCalled: Bool {
return unlockWithCallsCount > 0
}
var unlockWithReceivedPinCode: String?
var unlockWithReceivedInvocations: [String] = []
var unlockWithReturnValue: Bool!
var unlockWithClosure: ((String) -> Bool)?
func unlock(with pinCode: String) -> Bool {
unlockWithCallsCount += 1
unlockWithReceivedPinCode = pinCode
unlockWithReceivedInvocations.append(pinCode)
if let unlockWithClosure = unlockWithClosure {
return unlockWithClosure(pinCode)
} else {
return unlockWithReturnValue
}
}
//MARK: - unlockWithBiometrics
var unlockWithBiometricsCallsCount = 0
var unlockWithBiometricsCalled: Bool {
return unlockWithBiometricsCallsCount > 0
}
var unlockWithBiometricsReturnValue: Bool!
var unlockWithBiometricsClosure: (() -> Bool)?
func unlockWithBiometrics() -> Bool {
unlockWithBiometricsCallsCount += 1
if let unlockWithBiometricsClosure = unlockWithBiometricsClosure {
return unlockWithBiometricsClosure()
} else {
return unlockWithBiometricsReturnValue
}
}
}
class AudioConverterMock: AudioConverterProtocol {
//MARK: - convertToOpusOgg
@@ -47,8 +47,7 @@ struct AppLockScreen: View {
// Add TestablePreview conformance once we have designs.
struct AppLockScreen_Previews: PreviewProvider {
static let viewModel = AppLockScreenViewModel(appLockService: AppLockService(keychainController: KeychainControllerMock(),
appSettings: ServiceLocator.shared.settings))
static let viewModel = AppLockScreenViewModel(appLockService: AppLockServiceMock.mock())
static var previews: some View {
NavigationStack {
@@ -0,0 +1,62 @@
//
// Copyright 2022 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Combine
import SwiftUI
struct AppLockSettingsScreenCoordinatorParameters {
let appLockService: AppLockServiceProtocol
}
enum AppLockSettingsScreenCoordinatorAction {
case done
}
final class AppLockSettingsScreenCoordinator: CoordinatorProtocol {
private let parameters: AppLockSettingsScreenCoordinatorParameters
private var viewModel: AppLockSettingsScreenViewModelProtocol
private let actionsSubject: PassthroughSubject<AppLockSettingsScreenCoordinatorAction, Never> = .init()
private var cancellables = Set<AnyCancellable>()
var actions: AnyPublisher<AppLockSettingsScreenCoordinatorAction, Never> {
actionsSubject.eraseToAnyPublisher()
}
init(parameters: AppLockSettingsScreenCoordinatorParameters) {
self.parameters = parameters
viewModel = AppLockSettingsScreenViewModel(appLockService: parameters.appLockService)
}
func start() {
viewModel.actions.sink { [weak self] action in
MXLog.info("Coordinator: received view model action: \(action)")
guard let self else { return }
switch action {
case .changePINCode:
break
case .done:
self.actionsSubject.send(.done)
}
}
.store(in: &cancellables)
}
func toPresentable() -> AnyView {
AnyView(AppLockSettingsScreen(context: viewModel.context))
}
}
@@ -0,0 +1,66 @@
//
// Copyright 2022 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
import LocalAuthentication
enum AppLockSettingsScreenViewModelAction {
/// The user would like to enter new PIN code.
case changePINCode
case done
}
struct AppLockSettingsScreenViewState: BindableState {
let biometryType: LABiometryType
var bindings: AppLockSettingsScreenViewStateBindings
var supportsBiometry: Bool { biometryType != .none }
var enableBiometryTitle: String {
switch biometryType {
case .none:
return L10n.commonError
case .touchID:
return UntranslatedL10n.screenAppLockSettingsEnableTouchIdIos
case .faceID:
return UntranslatedL10n.screenAppLockSettingsEnableFaceIdIos
// Requires Xcode 15:
// case .opticID:
// UntranslatedL10n.screenAppLockSettingsEnableOpticIdIos
@unknown default:
return UntranslatedL10n.screenAppLockSettingsEnableBiometricUnlock
}
}
}
struct AppLockSettingsScreenViewStateBindings {
var enableBiometrics: Bool
var alertInfo: AlertInfo<AppLockSettingsScreenAlertType>?
}
enum AppLockSettingsScreenAlertType {
/// The alert shown to confirm the user would like to remove their PIN.
case confirmRemovePINCode
}
enum AppLockSettingsScreenViewAction {
/// The user would like to enter a new PIN code.
case changePINCode
/// The user would like to disable the App Lock feature.
case disable
/// The user has toggled the biometrics setting.
case enableBiometricsChanged
case done
}
@@ -0,0 +1,69 @@
//
// Copyright 2022 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Combine
import SwiftUI
typealias AppLockSettingsScreenViewModelType = StateStoreViewModel<AppLockSettingsScreenViewState, AppLockSettingsScreenViewAction>
class AppLockSettingsScreenViewModel: AppLockSettingsScreenViewModelType, AppLockSettingsScreenViewModelProtocol {
private let appLockService: AppLockServiceProtocol
private var actionsSubject: PassthroughSubject<AppLockSettingsScreenViewModelAction, Never> = .init()
var actions: AnyPublisher<AppLockSettingsScreenViewModelAction, Never> {
actionsSubject.eraseToAnyPublisher()
}
init(appLockService: AppLockServiceProtocol) {
self.appLockService = appLockService
super.init(initialViewState: AppLockSettingsScreenViewState(biometryType: appLockService.biometryType,
bindings: .init(enableBiometrics: appLockService.biometricUnlockEnabled)))
}
// MARK: - Public
override func process(viewAction: AppLockSettingsScreenViewAction) {
MXLog.info("View model: received view action: \(viewAction)")
switch viewAction {
case .changePINCode:
actionsSubject.send(.changePINCode)
case .disable:
showRemovePINAlert()
case .enableBiometricsChanged:
appLockService.biometricUnlockEnabled = state.bindings.enableBiometrics
case .done:
actionsSubject.send(.done)
}
}
// MARK: - Private
/// Shows a confirmation alert to the user before removing their PIN code.
private func showRemovePINAlert() {
state.bindings.alertInfo = .init(id: .confirmRemovePINCode,
title: UntranslatedL10n.screenAppLockSettingsRemovePinAlertTitle,
message: UntranslatedL10n.screenAppLockSettingsRemovePinAlertMessage,
primaryButton: .init(title: L10n.actionYes) { self.completeRemovePIN() },
secondaryButton: .init(title: L10n.actionCancel, role: .cancel, action: nil))
}
/// Removes the user's PIN code, disabling the App Lock feature.
private func completeRemovePIN() {
appLockService.disable()
actionsSubject.send(.done)
}
}
@@ -0,0 +1,23 @@
//
// Copyright 2022 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Combine
@MainActor
protocol AppLockSettingsScreenViewModelProtocol {
var actions: AnyPublisher<AppLockSettingsScreenViewModelAction, Never> { get }
var context: AppLockSettingsScreenViewModelType.Context { get }
}
@@ -0,0 +1,72 @@
//
// Copyright 2022 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Compound
import SwiftUI
struct AppLockSettingsScreen: View {
@ObservedObject var context: AppLockSettingsScreenViewModel.Context
var body: some View {
Form {
Section {
ListRow(label: .plain(title: UntranslatedL10n.screenAppLockSettingsChangePin),
kind: .button { context.send(viewAction: .changePINCode) })
ListRow(label: .plain(title: UntranslatedL10n.screenAppLockSettingsRemovePin, role: .destructive),
kind: .button { context.send(viewAction: .disable) })
}
if context.viewState.supportsBiometry {
Section {
ListRow(label: .plain(title: context.viewState.enableBiometryTitle),
kind: .toggle($context.enableBiometrics))
.onChange(of: context.enableBiometrics) { _ in
context.send(viewAction: .enableBiometricsChanged)
}
}
}
}
.compoundList()
.navigationTitle(UntranslatedL10n.commonScreenLock)
.navigationBarTitleDisplayMode(.inline)
.alert(item: $context.alertInfo)
}
}
// MARK: - Previews
struct AppLockSettingsScreen_Previews: PreviewProvider, TestablePreview {
static let faceIDViewModel = AppLockSettingsScreenViewModel(appLockService: AppLockServiceMock.mock(biometryType: .faceID))
static let touchIDViewModel = AppLockSettingsScreenViewModel(appLockService: AppLockServiceMock.mock(biometryType: .touchID))
static let biometricsUnavailableViewModel = AppLockSettingsScreenViewModel(appLockService: AppLockServiceMock.mock(biometryType: .none))
static var previews: some View {
NavigationStack {
AppLockSettingsScreen(context: faceIDViewModel.context)
}
.previewDisplayName("Face ID")
NavigationStack {
AppLockSettingsScreen(context: touchIDViewModel.context)
}
.previewDisplayName("Touch ID")
NavigationStack {
AppLockSettingsScreen(context: biometricsUnavailableViewModel.context)
}
.previewDisplayName("No Biometrics")
}
}
@@ -21,6 +21,7 @@ struct SettingsScreenCoordinatorParameters {
weak var navigationStackCoordinator: NavigationStackCoordinator?
weak var userIndicatorController: UserIndicatorControllerProtocol?
let userSession: UserSessionProtocol
let appLockService: AppLockServiceProtocol
let bugReportService: BugReportServiceProtocol
let notificationSettings: NotificationSettingsProxyProtocol
let appSettings: AppSettings
@@ -48,7 +49,7 @@ final class SettingsScreenCoordinator: CoordinatorProtocol {
init(parameters: SettingsScreenCoordinatorParameters) {
self.parameters = parameters
viewModel = SettingsScreenViewModel(userSession: parameters.userSession, appSettings: ServiceLocator.shared.settings)
viewModel = SettingsScreenViewModel(userSession: parameters.userSession, appSettings: parameters.appSettings)
viewModel.actions
.sink { [weak self] action in
@@ -63,6 +64,8 @@ final class SettingsScreenCoordinator: CoordinatorProtocol {
presentAccountProfileURL()
case .analytics:
presentAnalyticsScreen()
case .appLock:
presentAppLockSettingsScreen()
case .reportBug:
presentBugReportScreen()
case .about:
@@ -133,11 +136,16 @@ final class SettingsScreenCoordinator: CoordinatorProtocol {
}
private func presentAnalyticsScreen() {
let coordinator = AnalyticsSettingsScreenCoordinator(parameters: .init(appSettings: ServiceLocator.shared.settings,
let coordinator = AnalyticsSettingsScreenCoordinator(parameters: .init(appSettings: parameters.appSettings,
analytics: ServiceLocator.shared.analytics))
parameters.navigationStackCoordinator?.push(coordinator)
}
private func presentAppLockSettingsScreen() {
let coordinator = AppLockSettingsScreenCoordinator(parameters: .init(appLockService: parameters.appLockService))
parameters.navigationStackCoordinator?.push(coordinator)
}
private func presentBugReportScreen() {
let params = BugReportScreenCoordinatorParameters(bugReportService: parameters.bugReportService,
userID: parameters.userSession.userID,
@@ -22,6 +22,7 @@ enum SettingsScreenViewModelAction {
case userDetails
case accountProfile
case analytics
case appLock
case reportBug
case about
case sessionVerification
@@ -40,6 +41,7 @@ struct SettingsScreenViewState: BindableState {
var userAvatarURL: URL?
var userDisplayName: String?
var showSessionVerificationSection: Bool
var showAppLockSettings: Bool
var showDeveloperOptions: Bool
/// The presentation anchor used to display the OIDC account URL.
@@ -51,6 +53,7 @@ enum SettingsScreenViewAction {
case userDetails
case accountProfile
case analytics
case appLock
case reportBug
case about
case sessionVerification
@@ -43,6 +43,7 @@ class SettingsScreenViewModel: SettingsScreenViewModelType, SettingsScreenViewMo
accountProfileURL: userSession.clientProxy.accountURL(action: .profile),
accountSessionsListURL: userSession.clientProxy.accountURL(action: .sessionsList),
showSessionVerificationSection: showSessionVerificationSection,
showAppLockSettings: appSettings.appLockFlowEnabled,
showDeveloperOptions: appSettings.canShowDeveloperOptions),
imageProvider: userSession.mediaProvider)
@@ -55,6 +56,10 @@ class SettingsScreenViewModel: SettingsScreenViewModelType, SettingsScreenViewMo
.receive(on: DispatchQueue.main)
.weakAssign(to: \.state.userDisplayName, on: self)
.store(in: &cancellables)
appSettings.$appLockFlowEnabled
.weakAssign(to: \.state.showAppLockSettings, on: self)
.store(in: &cancellables)
Task {
await userSession.clientProxy.loadUserAvatarURL()
@@ -86,6 +91,8 @@ class SettingsScreenViewModel: SettingsScreenViewModelType, SettingsScreenViewMo
actionsSubject.send(.accountProfile)
case .analytics:
actionsSubject.send(.analytics)
case .appLock:
actionsSubject.send(.appLock)
case .reportBug:
actionsSubject.send(.reportBug)
case .about:
@@ -118,6 +118,15 @@ struct SettingsScreen: View {
})
.accessibilityIdentifier(A11yIdentifiers.settingsScreen.analytics)
if context.viewState.showAppLockSettings {
ListRow(label: .default(title: UntranslatedL10n.commonScreenLock,
systemIcon: .lock),
kind: .navigationLink {
context.send(viewAction: .appLock)
})
.accessibilityIdentifier(A11yIdentifiers.settingsScreen.analytics)
}
ListRow(label: .default(title: L10n.commonReportABug,
systemIcon: .ladybug),
kind: .navigationLink {
@@ -16,40 +16,6 @@
import LocalAuthentication
enum AppLockServiceError: Error {
/// The operation failed to access the keychain.
case keychainError
/// The PIN code was rejected because it isn't long enough, or contains invalid characters.
case invalidPIN
/// The PIN code was rejected as an insecure choice.
case weakPIN
}
@MainActor
protocol AppLockServiceProtocol {
/// The app has been configured to automatically lock with a PIN code.
var isEnabled: Bool { get }
/// The type of biometric authentication supported by the device.
var biometryType: LABiometryType { get }
/// Whether or not the user has enabled unlock via TouchID, FaceID or (possibly) OpticID.
var biometricUnlockEnabled: Bool { get set }
/// Sets the user's PIN code used to unlock the app.
func setupPINCode(_ pinCode: String) -> Result<Void, AppLockServiceError>
/// Disables the App Lock feature, removing the user's stored PIN code.
func disable()
/// Informs the service that the app has entered the background.
func applicationDidEnterBackground()
/// Decides whether the app should be unlocked with a PIN code/biometrics on foregrounding.
func computeNeedsUnlock(willEnterForegroundAt date: Date) -> Bool
/// Attempt to unlock the app with the supplied PIN code.
func unlock(with pinCode: String) -> Bool
/// Attempt to unlock the app using FaceID or TouchID.
func unlockWithBiometrics() -> Bool
}
/// The service responsible for locking and unlocking the app.
class AppLockService: AppLockServiceProtocol {
private let keychainController: KeychainControllerProtocol
@@ -76,6 +42,8 @@ class AppLockService: AppLockServiceProtocol {
self.keychainController = keychainController
self.appSettings = appSettings
timer = AppLockTimer(gracePeriod: appSettings.appLockGracePeriod)
configureBiometrics()
}
func setupPINCode(_ pinCode: String) -> Result<Void, AppLockServiceError> {
@@ -116,6 +84,16 @@ class AppLockService: AppLockServiceProtocol {
// MARK: - Private
/// Queries the context for supported biometrics.
private func configureBiometrics() {
var error: NSError?
context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error)
if let error {
MXLog.error("Biometrics error: \(error)")
}
}
/// Ensures that a provided PIN code is long enough and only contains digits.
private func validate(_ pinCode: String) -> Bool {
pinCode.count == 4 && pinCode.allSatisfy(\.isNumber)
@@ -0,0 +1,65 @@
//
// Copyright 2023 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import LocalAuthentication
enum AppLockServiceError: Error {
/// The operation failed to access the keychain.
case keychainError
/// The PIN code was rejected because it isn't long enough, or contains invalid characters.
case invalidPIN
/// The PIN code was rejected as an insecure choice.
case weakPIN
}
@MainActor
protocol AppLockServiceProtocol: AnyObject {
/// The app has been configured to automatically lock with a PIN code.
var isEnabled: Bool { get }
/// The type of biometric authentication supported by the device.
var biometryType: LABiometryType { get }
/// Whether or not the user has enabled unlock via TouchID, FaceID or (possibly) OpticID.
var biometricUnlockEnabled: Bool { get set }
/// Sets the user's PIN code used to unlock the app.
func setupPINCode(_ pinCode: String) -> Result<Void, AppLockServiceError>
/// Disables the App Lock feature, removing the user's stored PIN code.
func disable()
/// Informs the service that the app has entered the background.
func applicationDidEnterBackground()
/// Decides whether the app should be unlocked with a PIN code/biometrics on foregrounding.
func computeNeedsUnlock(willEnterForegroundAt date: Date) -> Bool
/// Attempt to unlock the app with the supplied PIN code.
func unlock(with pinCode: String) -> Bool
/// Attempt to unlock the app using FaceID or TouchID.
func unlockWithBiometrics() -> Bool
}
// sourcery: AutoMockable
extension AppLockServiceProtocol { }
extension AppLockServiceMock {
static func mock(pinCode: String? = "2023", biometryType: LABiometryType = .faceID) -> AppLockServiceMock {
let mock = AppLockServiceMock()
mock.isEnabled = pinCode != nil
mock.underlyingBiometryType = biometryType
mock.underlyingBiometricUnlockEnabled = biometryType != .none
mock.unlockWithClosure = { $0 == pinCode }
return mock
}
}
@@ -161,6 +161,12 @@ class MockScreen: Identifiable {
let appLockService = AppLockService(keychainController: KeychainControllerMock(), appSettings: ServiceLocator.shared.settings)
let coordinator = AppLockScreenCoordinator(parameters: .init(appLockService: appLockService))
return coordinator
case .appLockSettingsScreen:
let navigationStackCoordinator = NavigationStackCoordinator()
let appLockService = AppLockServiceMock.mock(biometryType: .faceID)
let coordinator = AppLockSettingsScreenCoordinator(parameters: .init(appLockService: appLockService))
navigationStackCoordinator.setRootCoordinator(coordinator)
return navigationStackCoordinator
case .home:
let navigationStackCoordinator = NavigationStackCoordinator()
let session = MockUserSession(clientProxy: MockClientProxy(userID: "@mock:matrix.org"),
@@ -178,7 +184,11 @@ class MockScreen: Identifiable {
let clientProxy = MockClientProxy(userID: "@mock:client.com")
let coordinator = SettingsScreenCoordinator(parameters: .init(navigationStackCoordinator: navigationStackCoordinator,
userIndicatorController: nil,
userSession: MockUserSession(clientProxy: clientProxy, mediaProvider: MockMediaProvider(), voiceMessageMediaManager: VoiceMessageMediaManagerMock()),
userSession: MockUserSession(clientProxy: clientProxy,
mediaProvider: MockMediaProvider(),
voiceMessageMediaManager: VoiceMessageMediaManagerMock()),
appLockService: AppLockService(keychainController: KeychainControllerMock(),
appSettings: ServiceLocator.shared.settings),
bugReportService: BugReportServiceMock(),
notificationSettings: NotificationSettingsProxyMock(with: .init()),
appSettings: ServiceLocator.shared.settings))
@@ -444,6 +454,8 @@ class MockScreen: Identifiable {
let coordinator = UserSessionFlowCoordinator(userSession: MockUserSession(clientProxy: clientProxy, mediaProvider: MockMediaProvider(), voiceMessageMediaManager: VoiceMessageMediaManagerMock()),
navigationSplitCoordinator: navigationSplitCoordinator,
appLockService: AppLockService(keychainController: KeychainControllerMock(),
appSettings: ServiceLocator.shared.settings),
bugReportService: BugReportServiceMock(),
roomTimelineControllerFactory: MockRoomTimelineControllerFactory(),
appSettings: appSettings,
@@ -30,6 +30,7 @@ enum UITestsScreenIdentifier: String {
case migration
case templateScreen
case appLockScreen
case appLockSettingsScreen
case home
case settings
case bugReport