yubioath-flutter/lib/oath/views/add_account_page.dart

405 lines
14 KiB
Dart
Raw Normal View History

2022-03-22 17:16:52 +03:00
import 'dart:convert';
2022-04-14 10:08:33 +03:00
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:logging/logging.dart';
import '../../app/logging.dart';
2022-03-25 17:43:32 +03:00
import '../../app/message.dart';
import '../../app/models.dart';
2022-04-14 10:08:33 +03:00
import '../../app/state.dart';
import '../../cancellation_exception.dart';
2022-06-13 17:45:26 +03:00
import '../../desktop/models.dart';
2022-09-01 11:14:59 +03:00
import '../../widgets/choice_filter_chip.dart';
2022-03-23 12:46:35 +03:00
import '../../widgets/file_drop_target.dart';
import '../../widgets/responsive_dialog.dart';
2022-07-06 16:22:15 +03:00
import '../../widgets/utf8_utils.dart';
2022-03-15 20:04:26 +03:00
import '../models.dart';
2021-12-02 16:20:05 +03:00
import '../state.dart';
import 'utils.dart';
final _log = Logger('oath.view.add_account_page');
final _secretFormatterPattern =
RegExp('[abcdefghijklmnopqrstuvwxyz234567 ]', caseSensitive: false);
enum _QrScanState { none, scanning, success, failed }
2022-03-15 20:04:26 +03:00
class OathAddAccountPage extends ConsumerStatefulWidget {
final DevicePath devicePath;
final OathState state;
final bool openQrScanner;
const OathAddAccountPage(this.devicePath, this.state,
2022-05-12 10:56:55 +03:00
{super.key, required this.openQrScanner});
2021-12-02 16:20:05 +03:00
@override
2022-03-15 20:04:26 +03:00
ConsumerState<ConsumerStatefulWidget> createState() =>
_OathAddAccountPageState();
2021-12-02 16:20:05 +03:00
}
2022-03-15 20:04:26 +03:00
class _OathAddAccountPageState extends ConsumerState<OathAddAccountPage> {
final _issuerController = TextEditingController();
final _accountController = TextEditingController();
final _secretController = TextEditingController();
final _periodController = TextEditingController(text: '$defaultPeriod');
2021-12-02 16:20:05 +03:00
bool _touch = false;
OathType _oathType = defaultOathType;
HashAlgorithm _hashAlgorithm = defaultHashAlgorithm;
int _digits = defaultDigits;
bool _validateSecretLength = false;
_QrScanState _qrState = _QrScanState.none;
bool _isObscure = true;
List<int> _periodValues = [20, 30, 45, 60];
List<int> _digitsValues = [6, 8];
_scanQrCode(QrScanner qrScanner) async {
try {
setState(() {
// If we have a previous scan result stored, clear it
if (_qrState == _QrScanState.success) {
_issuerController.text = '';
_accountController.text = '';
_secretController.text = '';
_oathType = defaultOathType;
_hashAlgorithm = defaultHashAlgorithm;
_periodController.text = '$defaultPeriod';
_digits = defaultDigits;
}
_qrState = _QrScanState.scanning;
});
2022-03-29 14:57:08 +03:00
final otpauth = await qrScanner.scanQr();
2022-06-13 17:45:26 +03:00
if (otpauth == null) {
if (!mounted) return;
showMessage(context, 'No QR code found');
setState(() {
_qrState = _QrScanState.failed;
});
} else {
final data = CredentialData.fromUri(Uri.parse(otpauth));
_loadCredentialData(data);
}
} catch (e) {
2022-06-13 17:45:26 +03:00
final String errorMessage;
// TODO: Make this cleaner than importing desktop specific RpcError.
if (e is RpcError) {
errorMessage = e.message;
} else {
errorMessage = e.toString();
}
showMessage(
context,
'Failed reading QR code: $errorMessage',
duration: const Duration(seconds: 4),
);
setState(() {
_qrState = _QrScanState.failed;
});
}
}
_loadCredentialData(CredentialData data) {
setState(() {
_issuerController.text = data.issuer ?? '';
_accountController.text = data.name;
_secretController.text = data.secret;
_oathType = data.oathType;
_hashAlgorithm = data.hashAlgorithm;
_periodValues = [data.period];
_periodController.text = '${data.period}';
_digitsValues = [data.digits];
_digits = data.digits;
_isObscure = true;
_qrState = _QrScanState.success;
});
}
@override
void initState() {
super.initState();
final qrScanner = ref.read(qrScannerProvider);
if (qrScanner != null && widget.openQrScanner) {
WidgetsBinding.instance.addPostFrameCallback((_) {
_scanQrCode(qrScanner);
});
}
}
@override
2021-12-02 16:20:05 +03:00
Widget build(BuildContext context) {
final period = int.tryParse(_periodController.text) ?? -1;
final remaining = getRemainingKeySpace(
oathType: _oathType,
period: period,
issuer: _issuerController.text,
name: _accountController.text,
);
final issuerRemaining = remaining.first;
final nameRemaining = remaining.second;
final secret = _secretController.text.replaceAll(' ', '');
final secretLengthValid = secret.length * 5 % 8 < 5;
final isValid = _accountController.text.isNotEmpty &&
secret.isNotEmpty &&
issuerRemaining >= -1 &&
nameRemaining >= 0 &&
period > 0;
final qrScanner = ref.watch(qrScannerProvider);
void submit() async {
if (secretLengthValid) {
final issuer = _issuerController.text;
final cred = CredentialData(
issuer: issuer.isEmpty ? null : issuer,
name: _accountController.text,
secret: secret,
oathType: _oathType,
hashAlgorithm: _hashAlgorithm,
digits: _digits,
period: period,
);
try {
await ref
.read(credentialListProvider(widget.devicePath).notifier)
.addAccount(cred.toUri(), requireTouch: _touch);
if (!mounted) return;
Navigator.of(context).pop();
showMessage(context, 'Account added');
2022-06-20 10:47:34 +03:00
} on CancellationException catch (_) {
// ignored
} catch (e) {
_log.error('Failed to add account', e);
2022-06-13 17:45:26 +03:00
final String errorMessage;
// TODO: Make this cleaner than importing desktop specific RpcError.
if (e is RpcError) {
errorMessage = e.message;
} else {
errorMessage = e.toString();
}
showMessage(
context,
'Failed adding account: $errorMessage',
duration: const Duration(seconds: 4),
);
}
} else {
setState(() {
_validateSecretLength = true;
});
}
}
2022-03-15 20:04:26 +03:00
return ResponsiveDialog(
title: const Text('Add account'),
2022-05-12 09:34:51 +03:00
actions: [
TextButton(
onPressed: isValid ? submit : null,
2022-05-12 09:34:51 +03:00
child: const Text('Save', key: Key('save_btn')),
),
],
2022-03-23 12:46:35 +03:00
child: FileDropTarget(
onFileDropped: (fileData) async {
if (qrScanner != null) {
final b64Image = base64Encode(fileData);
final otpauth = await qrScanner.scanQr(b64Image);
2022-06-13 17:45:26 +03:00
if (otpauth == null) {
if (!mounted) return;
showMessage(context, 'No QR code found');
} else {
final data = CredentialData.fromUri(Uri.parse(otpauth));
_loadCredentialData(data);
}
2022-03-23 12:46:35 +03:00
}
},
child: Column(
2022-03-22 17:16:52 +03:00
crossAxisAlignment: CrossAxisAlignment.start,
children: [
TextField(
2022-04-14 10:08:33 +03:00
key: const Key('issuer'),
2022-03-22 17:16:52 +03:00
controller: _issuerController,
2022-08-05 15:04:04 +03:00
autofocus: !widget.openQrScanner,
2022-03-22 17:16:52 +03:00
enabled: issuerRemaining > 0,
maxLength: max(issuerRemaining, 1),
inputFormatters: [limitBytesLength(issuerRemaining)],
2022-07-06 16:22:15 +03:00
buildCounter: buildByteCounterFor(_issuerController.text),
2022-03-22 17:16:52 +03:00
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: 'Issuer (optional)',
helperText: '', // Prevents dialog resizing when enabled = false
prefixIcon: Icon(Icons.business_outlined),
2022-03-15 20:04:26 +03:00
),
textInputAction: TextInputAction.next,
2022-03-22 17:16:52 +03:00
onChanged: (value) {
setState(() {
// Update maxlengths
});
},
onSubmitted: (_) {
if (isValid) submit();
},
2022-03-15 20:04:26 +03:00
),
2022-03-22 17:16:52 +03:00
TextField(
2022-04-14 10:08:33 +03:00
key: const Key('name'),
2022-03-22 17:16:52 +03:00
controller: _accountController,
maxLength: max(nameRemaining, 1),
2022-07-06 16:22:15 +03:00
buildCounter: buildByteCounterFor(_accountController.text),
inputFormatters: [limitBytesLength(nameRemaining)],
2022-03-22 17:16:52 +03:00
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: 'Account name',
helperText: '', // Prevents dialog resizing when enabled = false
2022-06-13 09:16:09 +03:00
prefixIcon: Icon(Icons.person_outline),
2021-12-02 16:20:05 +03:00
),
textInputAction: TextInputAction.next,
2022-03-22 17:16:52 +03:00
onChanged: (value) {
setState(() {
// Update maxlengths
});
},
onSubmitted: (_) {
if (isValid) submit();
},
2022-03-22 17:16:52 +03:00
),
TextField(
2022-04-14 10:08:33 +03:00
key: const Key('secret'),
2022-03-22 17:16:52 +03:00
controller: _secretController,
obscureText: _isObscure,
2022-03-22 17:16:52 +03:00
inputFormatters: <TextInputFormatter>[
FilteringTextInputFormatter.allow(_secretFormatterPattern)
],
decoration: InputDecoration(
2022-04-04 13:09:34 +03:00
suffixIcon: IconButton(
icon: Icon(
_isObscure ? Icons.visibility : Icons.visibility_off,
color: IconTheme.of(context).color,
2022-04-04 13:09:34 +03:00
),
onPressed: () {
setState(() {
_isObscure = !_isObscure;
2022-04-04 13:09:34 +03:00
});
},
),
2022-03-22 17:16:52 +03:00
border: const OutlineInputBorder(),
prefixIcon: const Icon(Icons.key_outlined),
2022-03-22 17:16:52 +03:00
labelText: 'Secret key',
errorText: _validateSecretLength && !secretLengthValid
? 'Invalid length'
: null),
readOnly: _qrState == _QrScanState.success,
textInputAction: TextInputAction.done,
2022-03-22 17:16:52 +03:00
onChanged: (value) {
setState(() {
_validateSecretLength = false;
});
},
onSubmitted: (_) {
if (isValid) submit();
},
2022-03-22 17:16:52 +03:00
),
if (qrScanner != null)
Padding(
padding: const EdgeInsets.only(top: 16.0),
child: ActionChip(
autofocus: true,
avatar: _qrState != _QrScanState.scanning
? (_qrState == _QrScanState.success
? const Icon(Icons.qr_code)
: const Icon(Icons.qr_code_scanner_outlined))
: const CircularProgressIndicator(strokeWidth: 2.0),
label: _qrState == _QrScanState.success
? const Text('Scanned QR code')
: const Text('Scan QR code'),
onPressed: () {
_scanQrCode(qrScanner);
}),
2021-12-02 16:20:05 +03:00
),
2022-03-22 17:16:52 +03:00
const Divider(),
Wrap(
crossAxisAlignment: WrapCrossAlignment.center,
spacing: 4.0,
runSpacing: 8.0,
children: [
if (widget.state.version.isAtLeast(4, 2))
FilterChip(
label: const Text('Require touch'),
selected: _touch,
onSelected: (value) {
setState(() {
_touch = value;
});
},
),
2022-09-01 11:14:59 +03:00
ChoiceFilterChip<OathType>(
items: OathType.values,
value: _oathType,
selected: _oathType != defaultOathType,
2022-09-01 11:14:59 +03:00
itemBuilder: (value) => Text(value.displayName),
onChanged: _qrState != _QrScanState.success
? (value) {
setState(() {
_oathType = value;
});
}
: null,
),
2022-09-01 11:14:59 +03:00
ChoiceFilterChip<HashAlgorithm>(
items: HashAlgorithm.values,
value: _hashAlgorithm,
selected: _hashAlgorithm != defaultHashAlgorithm,
2022-09-01 11:14:59 +03:00
itemBuilder: (value) => Text(value.displayName),
onChanged: _qrState != _QrScanState.success
? (value) {
setState(() {
_hashAlgorithm = value;
});
}
: null,
),
2022-03-22 17:16:52 +03:00
if (_oathType == OathType.totp)
2022-09-01 11:14:59 +03:00
ChoiceFilterChip<int>(
items: _periodValues,
value:
int.tryParse(_periodController.text) ?? defaultPeriod,
selected:
int.tryParse(_periodController.text) != defaultPeriod,
2022-09-01 11:14:59 +03:00
itemBuilder: ((value) => Text('$value sec')),
onChanged: _qrState != _QrScanState.success
? (period) {
setState(() {
_periodController.text = '$period';
});
}
: null,
2022-03-15 20:04:26 +03:00
),
2022-09-01 11:14:59 +03:00
ChoiceFilterChip<int>(
items: _digitsValues,
value: _digits,
selected: _digits != defaultDigits,
2022-09-01 11:14:59 +03:00
itemBuilder: (value) => Text('$value digits'),
onChanged: _qrState != _QrScanState.success
? (digits) {
setState(() {
_digits = digits;
});
}
: null,
),
2022-03-22 17:16:52 +03:00
],
),
]
.map((e) => Padding(
padding: const EdgeInsets.symmetric(vertical: 8.0),
child: e,
))
.toList(),
2022-03-23 12:46:35 +03:00
),
),
);
}
}