move auth feature from container to profile

This commit is contained in:
Fabian Freund
2026-02-12 10:25:44 +01:00
parent 9f7637dd06
commit 45f54ef092
28 changed files with 903 additions and 455 deletions
@@ -0,0 +1,70 @@
/*
* Copyright (c) 2024-2026 Fabian Freund.
*
* This file is part of WebLibre
* (see https://weblibre.eu).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import 'package:copy_with_extension/copy_with_extension.dart';
import 'package:fast_equatable/fast_equatable.dart';
import 'package:json_annotation/json_annotation.dart';
part 'auth_settings.g.dart';
enum AutoLockMode { background, timeout }
@CopyWith()
@JsonSerializable()
class AuthSettings with FastEquatable {
final bool authenticationRequired;
final AutoLockMode autoLockMode;
final Duration timeout;
AuthSettings({
required this.authenticationRequired,
required this.autoLockMode,
required this.timeout,
});
AuthSettings.withDefaults({
bool? authenticationRequired,
AutoLockMode? autoLockMode,
Duration? timeout,
}) : this(
authenticationRequired: authenticationRequired ?? false,
autoLockMode: autoLockMode ?? AutoLockMode.background,
timeout: timeout ?? const Duration(minutes: 5),
);
AuthSettings withBackgroundLock() {
return copyWith(autoLockMode: AutoLockMode.background);
}
AuthSettings withTimeoutLock(Duration value) {
return copyWith(autoLockMode: AutoLockMode.timeout, timeout: value);
}
factory AuthSettings.fromJson(Map<String, dynamic> json) =>
_$AuthSettingsFromJson(json);
Map<String, dynamic> toJson() => _$AuthSettingsToJson(this);
@override
List<Object?> get hashParameters => [
authenticationRequired,
autoLockMode,
timeout,
];
}
@@ -0,0 +1,108 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'auth_settings.dart';
// **************************************************************************
// CopyWithGenerator
// **************************************************************************
abstract class _$AuthSettingsCWProxy {
AuthSettings authenticationRequired(bool authenticationRequired);
AuthSettings autoLockMode(AutoLockMode autoLockMode);
AuthSettings timeout(Duration timeout);
/// Creates a new instance with the provided field values.
/// Passing `null` to a nullable field nullifies it, while `null` for a non-nullable field is ignored. To update a single field use `AuthSettings(...).copyWith.fieldName(value)`.
///
/// Example:
/// ```dart
/// AuthSettings(...).copyWith(id: 12, name: "My name")
/// ```
AuthSettings call({
bool authenticationRequired,
AutoLockMode autoLockMode,
Duration timeout,
});
}
/// Callable proxy for `copyWith` functionality.
/// Use as `instanceOfAuthSettings.copyWith(...)` or call `instanceOfAuthSettings.copyWith.fieldName(value)` for a single field.
class _$AuthSettingsCWProxyImpl implements _$AuthSettingsCWProxy {
const _$AuthSettingsCWProxyImpl(this._value);
final AuthSettings _value;
@override
AuthSettings authenticationRequired(bool authenticationRequired) =>
call(authenticationRequired: authenticationRequired);
@override
AuthSettings autoLockMode(AutoLockMode autoLockMode) =>
call(autoLockMode: autoLockMode);
@override
AuthSettings timeout(Duration timeout) => call(timeout: timeout);
@override
/// Creates a new instance with the provided field values.
/// Passing `null` to a nullable field nullifies it, while `null` for a non-nullable field is ignored. To update a single field use `AuthSettings(...).copyWith.fieldName(value)`.
///
/// Example:
/// ```dart
/// AuthSettings(...).copyWith(id: 12, name: "My name")
/// ```
AuthSettings call({
Object? authenticationRequired = const $CopyWithPlaceholder(),
Object? autoLockMode = const $CopyWithPlaceholder(),
Object? timeout = const $CopyWithPlaceholder(),
}) {
return AuthSettings(
authenticationRequired:
authenticationRequired == const $CopyWithPlaceholder() ||
authenticationRequired == null
? _value.authenticationRequired
// ignore: cast_nullable_to_non_nullable
: authenticationRequired as bool,
autoLockMode:
autoLockMode == const $CopyWithPlaceholder() || autoLockMode == null
? _value.autoLockMode
// ignore: cast_nullable_to_non_nullable
: autoLockMode as AutoLockMode,
timeout: timeout == const $CopyWithPlaceholder() || timeout == null
? _value.timeout
// ignore: cast_nullable_to_non_nullable
: timeout as Duration,
);
}
}
extension $AuthSettingsCopyWith on AuthSettings {
/// Returns a callable class used to build a new instance with modified fields.
/// Example: `instanceOfAuthSettings.copyWith(...)` or `instanceOfAuthSettings.copyWith.fieldName(...)`.
// ignore: library_private_types_in_public_api
_$AuthSettingsCWProxy get copyWith => _$AuthSettingsCWProxyImpl(this);
}
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
AuthSettings _$AuthSettingsFromJson(Map<String, dynamic> json) => AuthSettings(
authenticationRequired: json['authenticationRequired'] as bool,
autoLockMode: $enumDecode(_$AutoLockModeEnumMap, json['autoLockMode']),
timeout: Duration(microseconds: (json['timeout'] as num).toInt()),
);
Map<String, dynamic> _$AuthSettingsToJson(AuthSettings instance) =>
<String, dynamic>{
'authenticationRequired': instance.authenticationRequired,
'autoLockMode': _$AutoLockModeEnumMap[instance.autoLockMode]!,
'timeout': instance.timeout.inMicroseconds,
};
const _$AutoLockModeEnumMap = {
AutoLockMode.background: 'background',
AutoLockMode.timeout: 'timeout',
};
@@ -27,20 +27,82 @@ import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:weblibre/core/filesystem.dart';
import 'package:weblibre/core/routing/routes.dart';
import 'package:weblibre/domain/entities/profile.dart';
import 'package:weblibre/features/settings/presentation/widgets/sections.dart';
import 'package:weblibre/features/user/data/models/auth_settings.dart';
import 'package:weblibre/features/user/domain/presentation/dialogs/delete_profile_dialog.dart';
import 'package:weblibre/features/user/domain/presentation/utils/profile_switch_handler.dart';
import 'package:weblibre/features/user/domain/providers/profile_auth.dart';
import 'package:weblibre/features/user/domain/repositories/profile.dart';
import 'package:weblibre/features/user/domain/services/local_authentication.dart';
import 'package:weblibre/utils/form_validators.dart';
const _timeoutOptions = <DropdownMenuItem<Duration?>>[
DropdownMenuItem(value: Duration(minutes: 1), child: Text('1 minute')),
DropdownMenuItem(value: Duration(minutes: 5), child: Text('5 minutes')),
DropdownMenuItem(value: Duration(minutes: 15), child: Text('15 minutes')),
DropdownMenuItem(value: Duration(hours: 1), child: Text('1 hour')),
];
class ProfileEditScreen extends HookConsumerWidget {
final Profile? profile;
const ProfileEditScreen({required this.profile});
Future<void> _handleSave(
BuildContext context,
WidgetRef ref,
GlobalKey<FormState> formKey,
String name,
AuthSettings authSettings,
) async {
if (!(formKey.currentState?.validate() ?? false)) {
return;
}
// Require biometric confirmation when enabling/changing auth
if (profile != null &&
(profile!.authSettings.authenticationRequired ||
authSettings.authenticationRequired)) {
final authResult = await ref
.read(localAuthenticationServiceProvider.notifier)
.authenticate(
authKey: profileAccessAuthKey(profile!.id),
localizedReason: 'Require authentication for profile',
);
if (!authResult) {
return;
}
}
if (profile != null) {
await ref
.read(profileRepositoryProvider.notifier)
.updateProfileMetadata(
profile!.copyWith(name: name, authSettings: authSettings),
);
if (context.mounted) {
context.pop();
}
} else {
await ref
.read(profileRepositoryProvider.notifier)
.createProfile(name: name, authSettings: authSettings);
if (context.mounted) {
context.pop();
}
}
}
@override
Widget build(BuildContext context, WidgetRef ref) {
final formKey = useMemoized(() => GlobalKey<FormState>());
final nameTextController = useTextEditingController(text: profile?.name);
final authSettings = useState(
profile?.authSettings ?? AuthSettings.withDefaults(),
);
return Scaffold(
appBar: AppBar(
@@ -50,27 +112,13 @@ class ProfileEditScreen extends HookConsumerWidget {
actions: [
IconButton(
onPressed: () async {
if (formKey.currentState?.validate() ?? false) {
if (profile != null) {
await ref
.read(profileRepositoryProvider.notifier)
.updateProfileMetadata(
profile!.copyWith.name(nameTextController.text),
);
if (context.mounted) {
context.pop();
}
} else {
await ref
.read(profileRepositoryProvider.notifier)
.createProfile(name: nameTextController.text);
if (context.mounted) {
context.pop();
}
}
}
await _handleSave(
context,
ref,
formKey,
nameTextController.text,
authSettings.value,
);
},
icon: const Icon(Icons.check),
),
@@ -78,77 +126,191 @@ class ProfileEditScreen extends HookConsumerWidget {
),
body: Form(
key: formKey,
child: Padding(
child: ListView(
padding: const EdgeInsets.symmetric(horizontal: 12.0),
child: ListView(
children: [
TextFormField(
controller: nameTextController,
decoration: const InputDecoration(
label: Text('Name'),
floatingLabelBehavior: FloatingLabelBehavior.always,
),
validator: validateProfileName,
children: [
TextFormField(
controller: nameTextController,
decoration: const InputDecoration(
label: Text('Name'),
floatingLabelBehavior: FloatingLabelBehavior.always,
),
const SizedBox(height: 16),
if (profile != null) ...[
SizedBox(
width: double.infinity,
child: OutlinedButton.icon(
label: const Text('Backup'),
icon: const Icon(MdiIcons.safe),
onPressed: () async {
await BackupProfileRoute(
profile: jsonEncode(profile!.toJson()),
).push(context);
},
),
),
const SizedBox(height: 16),
if (filesystem.selectedProfile != profile!.uuidValue)
SizedBox(
width: double.infinity,
child: OutlinedButton.icon(
label: const Text('Switch to this Profile'),
icon: const Icon(MdiIcons.accountSwitch),
onPressed: () async {
await handleSwitchProfile(context, ref, profile!);
},
),
),
const SizedBox(height: 16),
SizedBox(
width: double.infinity,
child: OutlinedButton.icon(
style: OutlinedButton.styleFrom(
side: BorderSide(
color: Theme.of(context).colorScheme.error,
),
foregroundColor: Theme.of(context).colorScheme.error,
iconColor: Theme.of(context).colorScheme.error,
),
label: const Text('Delete'),
icon: const Icon(Icons.delete),
onPressed: () async {
final result = await showDeleteProfileDialog(context);
if (result == true) {
await ref
.read(profileRepositoryProvider.notifier)
.deleteProfile(profile!.uuidValue.uuid);
if (context.mounted) {
context.pop();
}
}
},
),
),
],
],
),
validator: validateProfileName,
),
const SizedBox(height: 24),
_AuthSection(
authSettings: authSettings.value,
onAuthSettingsChanged: (newSettings) {
authSettings.value = newSettings;
},
),
const SizedBox(height: 24),
if (profile != null) ...[_ProfileActionsSection(profile: profile!)],
],
),
),
);
}
}
class _AuthSection extends StatelessWidget {
final AuthSettings authSettings;
final ValueChanged<AuthSettings> onAuthSettingsChanged;
const _AuthSection({
required this.authSettings,
required this.onAuthSettingsChanged,
});
@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const SettingSection(name: 'Authentication'),
SwitchListTile.adaptive(
value: authSettings.authenticationRequired,
title: const Text('Require Authentication'),
subtitle: const Text(
'Lock this profile when switching away from the app',
),
secondary: const Icon(MdiIcons.fingerprint),
contentPadding: EdgeInsets.zero,
onChanged: (value) {
onAuthSettingsChanged(
authSettings.copyWith.authenticationRequired(value),
);
},
),
if (authSettings.authenticationRequired) ...[
const SizedBox(height: 8),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const ListTile(
title: Text('Auto-lock Behavior'),
subtitle: Text('Choose when to lock the profile'),
contentPadding: EdgeInsets.zero,
leading: Icon(MdiIcons.lockClock),
),
RadioGroup<AutoLockMode>(
groupValue: authSettings.autoLockMode,
onChanged: (value) {
if (value != null) {
onAuthSettingsChanged(
authSettings.copyWith.autoLockMode(value),
);
}
},
child: const Column(
children: [
RadioListTile.adaptive(
value: AutoLockMode.background,
title: Text('Lock on Background'),
subtitle: Text(
'Lock immediately when app goes to background',
),
),
RadioListTile.adaptive(
value: AutoLockMode.timeout,
title: Text('Lock After Timeout'),
subtitle: Text('Lock after a period of inactivity'),
),
],
),
),
],
),
),
if (authSettings.autoLockMode == AutoLockMode.timeout)
ListTile(
title: const Text('Timeout Duration'),
subtitle: const Text('How long to wait before locking'),
leading: const Icon(MdiIcons.timerOutline),
contentPadding: const EdgeInsets.symmetric(horizontal: 16.0),
trailing: DropdownButton<Duration?>(
value: authSettings.timeout,
items: _timeoutOptions,
underline: const SizedBox.shrink(),
onChanged: (Duration? value) {
if (value != null) {
onAuthSettingsChanged(authSettings.copyWith.timeout(value));
}
},
),
),
],
],
);
}
}
class _ProfileActionsSection extends ConsumerWidget {
final Profile profile;
const _ProfileActionsSection({required this.profile});
@override
Widget build(BuildContext context, WidgetRef ref) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const SettingSection(name: 'Profile Actions'),
const SizedBox(height: 8),
SizedBox(
width: double.infinity,
child: OutlinedButton.icon(
label: const Text('Backup'),
icon: const Icon(MdiIcons.safe),
onPressed: () async {
await BackupProfileRoute(
profile: jsonEncode(profile.toJson()),
).push(context);
},
),
),
const SizedBox(height: 12),
if (filesystem.selectedProfile != profile.uuidValue)
SizedBox(
width: double.infinity,
child: OutlinedButton.icon(
label: const Text('Switch to this Profile'),
icon: const Icon(MdiIcons.accountSwitch),
onPressed: () async {
await handleSwitchProfile(context, ref, profile);
},
),
),
if (filesystem.selectedProfile != profile.uuidValue)
const SizedBox(height: 12),
SizedBox(
width: double.infinity,
child: OutlinedButton.icon(
style: OutlinedButton.styleFrom(
side: BorderSide(color: Theme.of(context).colorScheme.error),
foregroundColor: Theme.of(context).colorScheme.error,
iconColor: Theme.of(context).colorScheme.error,
),
label: const Text('Delete'),
icon: const Icon(Icons.delete),
onPressed: () async {
final result = await showDeleteProfileDialog(context);
if (result == true) {
await ref
.read(profileRepositoryProvider.notifier)
.deleteProfile(profile.uuidValue.uuid);
if (context.mounted) {
context.pop();
}
}
},
),
),
],
);
}
}
@@ -0,0 +1,81 @@
/*
* Copyright (c) 2024-2026 Fabian Freund.
*
* This file is part of WebLibre
* (see https://weblibre.eu).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:flutter_material_design_icons/flutter_material_design_icons.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:weblibre/features/user/domain/providers/profile_auth.dart';
import 'package:weblibre/presentation/hooks/on_initialization.dart';
class LockScreen extends HookConsumerWidget {
const LockScreen();
@override
Widget build(BuildContext context, WidgetRef ref) {
final isAuthenticating = useState(false);
final didAutoAuthenticate = useRef(false);
Future<void> authenticate() async {
if (isAuthenticating.value) return;
isAuthenticating.value = true;
try {
await ref.read(profileAuthStateProvider.notifier).authenticate();
} finally {
if (context.mounted) {
isAuthenticating.value = false;
}
}
}
useOnInitialization(() {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!didAutoAuthenticate.value) {
didAutoAuthenticate.value = true;
unawaited(authenticate());
}
});
return null;
});
return Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Icon(MdiIcons.lock, size: 64),
const SizedBox(height: 16),
const Text('Profile is locked'),
const SizedBox(height: 16),
FilledButton.icon(
style: FilledButton.styleFrom(minimumSize: const Size(160, 40)),
icon: const Icon(MdiIcons.fingerprint),
label: Text(isAuthenticating.value ? 'Unlocking...' : 'Unlock'),
onPressed: isAuthenticating.value ? null : authenticate,
),
],
),
),
);
}
}
@@ -0,0 +1,114 @@
/*
* Copyright (c) 2024-2026 Fabian Freund.
*
* This file is part of WebLibre
* (see https://weblibre.eu).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import 'package:flutter/foundation.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:weblibre/features/user/domain/providers.dart';
import 'package:weblibre/features/user/domain/services/local_authentication.dart';
part 'profile_auth.g.dart';
String profileAccessAuthKey(String profileId) => 'profile_access::$profileId';
@Riverpod(keepAlive: true)
class ProfileAuthState extends _$ProfileAuthState {
bool _bootstrapped = false;
Future<void> bootstrapFromProfile() async {
if (_bootstrapped) return;
final profile = await ref.read(selectedProfileProvider.future);
if (!ref.mounted) return;
_bootstrapped = true;
if (!profile.authSettings.authenticationRequired) {
_unlock();
}
}
Future<bool> authenticate() async {
final profile = await ref.read(selectedProfileProvider.future);
if (!ref.mounted) return false;
if (!profile.authSettings.authenticationRequired) {
_unlock();
return true;
}
final result = await ref
.read(localAuthenticationServiceProvider.notifier)
.authenticate(
authKey: profileAccessAuthKey(profile.id),
localizedReason: 'Unlock profile',
settings: profile.authSettings,
useAuthCache: true,
);
if (!ref.mounted) return false;
state = result;
return result;
}
Future<void> revalidateAfterResume() async {
if (!state) return;
final profile = await ref.read(selectedProfileProvider.future);
if (!ref.mounted || !profile.authSettings.authenticationRequired) return;
final cached = ref
.read(localAuthenticationServiceProvider.notifier)
.isCached(profileAccessAuthKey(profile.id));
if (!cached && ref.mounted) {
_lock();
}
}
void _lock() {
state = false;
}
void _unlock() {
state = true;
}
@override
bool build() {
return false;
}
}
@Riverpod(keepAlive: true)
Raw<ProfileAuthNotifier> profileAuthNotifier(Ref ref) {
final notifier = ProfileAuthNotifier();
ref.listen<bool>(profileAuthStateProvider, (_, _) {
notifier.notify();
});
ref.onDispose(notifier.dispose);
return notifier;
}
class ProfileAuthNotifier extends ChangeNotifier {
void notify() => notifyListeners();
}
@@ -0,0 +1,110 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'profile_auth.dart';
// **************************************************************************
// RiverpodGenerator
// **************************************************************************
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint, type=warning
@ProviderFor(ProfileAuthState)
final profileAuthStateProvider = ProfileAuthStateProvider._();
final class ProfileAuthStateProvider
extends $NotifierProvider<ProfileAuthState, bool> {
ProfileAuthStateProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'profileAuthStateProvider',
isAutoDispose: false,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$profileAuthStateHash();
@$internal
@override
ProfileAuthState create() => ProfileAuthState();
/// {@macro riverpod.override_with_value}
Override overrideWithValue(bool value) {
return $ProviderOverride(
origin: this,
providerOverride: $SyncValueProvider<bool>(value),
);
}
}
String _$profileAuthStateHash() => r'9eb65fdb76baa0b088fc12a8063ea4ee63d54ac4';
abstract class _$ProfileAuthState extends $Notifier<bool> {
bool build();
@$mustCallSuper
@override
void runBuild() {
final ref = this.ref as $Ref<bool, bool>;
final element =
ref.element
as $ClassProviderElement<
AnyNotifier<bool, bool>,
bool,
Object?,
Object?
>;
element.handleCreate(ref, build);
}
}
@ProviderFor(profileAuthNotifier)
final profileAuthProvider = ProfileAuthNotifierProvider._();
final class ProfileAuthNotifierProvider
extends
$FunctionalProvider<
Raw<ProfileAuthNotifier>,
Raw<ProfileAuthNotifier>,
Raw<ProfileAuthNotifier>
>
with $Provider<Raw<ProfileAuthNotifier>> {
ProfileAuthNotifierProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'profileAuthProvider',
isAutoDispose: false,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$profileAuthNotifierHash();
@$internal
@override
$ProviderElement<Raw<ProfileAuthNotifier>> $createElement(
$ProviderPointer pointer,
) => $ProviderElement(pointer);
@override
Raw<ProfileAuthNotifier> create(Ref ref) {
return profileAuthNotifier(ref);
}
/// {@macro riverpod.override_with_value}
Override overrideWithValue(Raw<ProfileAuthNotifier> value) {
return $ProviderOverride(
origin: this,
providerOverride: $SyncValueProvider<Raw<ProfileAuthNotifier>>(value),
);
}
}
String _$profileAuthNotifierHash() =>
r'795f47b1494e4a9cdd74f5ff22d431b2bc59ffbd';
@@ -20,8 +20,8 @@
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:uuid/uuid.dart';
import 'package:weblibre/core/filesystem.dart';
import 'package:weblibre/domain/entities/profile.dart';
import 'package:weblibre/features/user/data/models/auth_settings.dart';
part 'profile.g.dart';
@@ -40,8 +40,11 @@ class ProfileRepository extends _$ProfileRepository {
await filesystem.setStartupProfile(UuidValue.withValidation(id));
}
Future<Profile> createProfile({required String name}) async {
final profile = Profile.create(name: name);
Future<Profile> createProfile({
required String name,
AuthSettings? authSettings,
}) async {
final profile = Profile.create(name: name, authSettings: authSettings);
if (!await filesystem.createNewProfile(profile)) {
throw Exception('Could not create profile');
}
@@ -33,7 +33,7 @@ final class ProfileRepositoryProvider
ProfileRepository create() => ProfileRepository();
}
String _$profileRepositoryHash() => r'e925dba74b0f15244fea8fff8391b5b67509be09';
String _$profileRepositoryHash() => r'c17702af1e59727ab3fec26e9ca659048e92c8bb';
abstract class _$ProfileRepository extends $AsyncNotifier<List<Profile>> {
FutureOr<List<Profile>> build();
@@ -22,46 +22,50 @@ import 'dart:async';
import 'package:local_auth/local_auth.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:weblibre/core/logger.dart';
import 'package:weblibre/features/geckoview/features/tabs/data/models/container_data.dart';
import 'package:weblibre/features/user/data/models/auth_settings.dart';
part 'local_authentication.g.dart';
@Riverpod(keepAlive: true)
class LocalAuthenticationService extends _$LocalAuthenticationService {
final _auth = LocalAuthentication();
final _cache = <String, (DateTime, ContainerAuthSettings)>{};
bool _cacheAuth(String authKey) {
final auth = _cache[authKey];
if (auth != null && auth.$2.lockTimeout != null) {
return DateTime.now().difference(auth.$1) < auth.$2.lockTimeout!;
}
return false;
}
final _cache = <String, (DateTime, AuthSettings)>{};
void evictCacheOnBackground() {
_cache.removeWhere((key, value) => value.$2.lockOnAppBackground);
_cache.removeWhere(
(key, value) => value.$2.autoLockMode == AutoLockMode.background,
);
}
bool isCached(String authKey) {
final auth = _cache[authKey];
if (auth == null) return false;
if (auth.$2.autoLockMode == AutoLockMode.timeout) {
return DateTime.now().difference(auth.$1) < auth.$2.timeout;
}
// Background mode cache stays valid until app background eviction.
return true;
}
Future<bool> authenticate({
required String authKey,
required String localizedReason,
ContainerAuthSettings? settings,
AuthSettings? settings,
bool useAuthCache = false,
}) async {
try {
var result = useAuthCache && _cacheAuth(authKey);
final useCache = useAuthCache && isCached(authKey);
final success =
useCache ||
await _auth.authenticate(localizedReason: localizedReason);
if (!result) {
result = await _auth.authenticate(localizedReason: localizedReason);
}
if (result && settings != null) {
if (success && settings != null) {
_cache[authKey] = (DateTime.now(), settings);
}
return result;
return success;
} on LocalAuthException catch (e, s) {
logger.e('Could not authenticate', error: e, stackTrace: s);
return false;
@@ -35,7 +35,7 @@ final class LocalAuthenticationServiceProvider
}
String _$localAuthenticationServiceHash() =>
r'1aab9214af5487dc770658c7be6f66083f5d6931';
r'0f4b2b47e94b2426a2219eca4eb2258bf683ab7c';
abstract class _$LocalAuthenticationService extends $AsyncNotifier<bool> {
FutureOr<bool> build();