CW-266 verbose access controls for TOTP 2FA (#967)

* chore: Setup

* feat: Verbose controls for TOTP 2FA WIP [skip-ci]

* feat: Implement verbose controls for sends to contact, non contacts and internal wallets

* feat: Implement verbose 2FA control for exchanges to internal wallets [skip-ci]

* Implement verbose controls

* chore: PR cleanup

* fix: Implement fixes and recommendations on verbose controls

* feat: Localization for verbose controls settings

* fix: disable pin when 2fa is not activated

* fix: Naming error

* chore: Reformat code with linelength of 100

* fix: Wallet type page and type bug when creating wallet

* fix: add new values to be stored in local storage to both reload function and import/export functions in back_service.dart

* fix: White spaces with localization files

* fix: Switch observers in modify_2fa page to individual observer

* chore: Switch custom tab widget to reusable SettingsChoicesCell widget

* chore: Remove unneeded argument in create wallet entrypoint

* fix: Switch type for selectedCakePreference when importing preferences from backup file

* fix: Await all values being saved to local storage

---------

Co-authored-by: David Adegoke <blazebrain@Davids-MacBook-Pro.local>
This commit is contained in:
Adegoke David
2023-08-04 16:49:26 +03:00
committed by GitHub
co-authored by David Adegoke
parent e9df03b49b
commit 4120394121
52 changed files with 1974 additions and 832 deletions
+137 -132
View File
@@ -1,3 +1,4 @@
import 'package:cake_wallet/core/auth_service.dart';
import 'package:cake_wallet/entities/contact_base.dart';
import 'package:cake_wallet/entities/contact_record.dart';
import 'package:cake_wallet/utils/show_bar.dart';
@@ -15,9 +16,10 @@ import 'package:cake_wallet/view_model/contact_list/contact_list_view_model.dart
import 'package:cake_wallet/src/widgets/collapsible_standart_list.dart';
class ContactListPage extends BasePage {
ContactListPage(this.contactListViewModel);
ContactListPage(this.contactListViewModel, this.authService);
final ContactListViewModel contactListViewModel;
final AuthService authService;
@override
String get title => S.current.address_book;
@@ -26,95 +28,99 @@ class ContactListPage extends BasePage {
Widget? trailing(BuildContext context) {
return MergeSemantics(
child: Container(
width: 32.0,
height: 32.0,
decoration: BoxDecoration(
shape: BoxShape.circle,
color: Theme.of(context)
.accentTextTheme!
.bodySmall!
.color!),
child: Stack(
alignment: Alignment.center,
children: <Widget>[
Icon(Icons.add,
color: Theme.of(context).primaryTextTheme!.titleLarge!.color!,
size: 22.0),
ButtonTheme(
minWidth: 32.0,
height: 32.0,
child: Semantics(
label: S.of(context).add,
child: TextButton(
// FIX-ME: Style
//shape: CircleBorder(),
onPressed: () async {
await Navigator.of(context)
.pushNamed(Routes.addressBookAddContact);
},
child: Offstage()),
),
)
],
)),
width: 32.0,
height: 32.0,
decoration: BoxDecoration(
shape: BoxShape.circle,
color: Theme.of(context).accentTextTheme!.bodySmall!.color!),
child: Stack(
alignment: Alignment.center,
children: <Widget>[
Icon(
Icons.add,
color: Theme.of(context).primaryTextTheme.titleLarge!.color!,
size: 22.0,
),
ButtonTheme(
minWidth: 32.0,
height: 32.0,
child: TextButton(
// FIX-ME: Style
//shape: CircleBorder(),
onPressed: () async {
if (contactListViewModel
.shouldRequireTOTP2FAForAddingContacts) {
authService.authenticateAction(
context,
route: Routes.addressBookAddContact,
conditionToDetermineIfToUse2FA: contactListViewModel
.shouldRequireTOTP2FAForAddingContacts,
);
} else {
await Navigator.of(context)
.pushNamed(Routes.addressBookAddContact);
}
},
child: Offstage()),
)
],
),
),
);
}
@override
Widget body(BuildContext context) {
return Container(
padding: EdgeInsets.only(top: 20.0, bottom: 20.0),
child: Observer(
builder: (_) {
child: Observer(builder: (_) {
final contacts = contactListViewModel.contactsToShow;
final walletContacts = contactListViewModel.walletContactsToShow;
return CollapsibleSectionList(
context: context,
sectionCount: 2,
themeColor: Theme.of(context).primaryTextTheme!.titleLarge!.color!,
dividerThemeColor:
Theme.of(context).primaryTextTheme!.bodySmall!.decorationColor!,
sectionTitleBuilder: (_, int sectionIndex) {
var title = S.current.contact_list_contacts;
context: context,
sectionCount: 2,
themeColor: Theme.of(context).primaryTextTheme.titleLarge!.color!,
dividerThemeColor:
Theme.of(context).primaryTextTheme.bodySmall!.decorationColor!,
sectionTitleBuilder: (_, int sectionIndex) {
var title = S.current.contact_list_contacts;
if (sectionIndex == 0) {
title = S.current.contact_list_wallets;
}
if (sectionIndex == 0) {
title = S.current.contact_list_wallets;
}
return Container(
padding: EdgeInsets.only(bottom: 10),
child: Text(title, style: TextStyle(fontSize: 36)));
},
itemCounter: (int sectionIndex) => sectionIndex == 0
? walletContacts.length
: contacts.length,
itemBuilder: (_, sectionIndex, index) {
if (sectionIndex == 0) {
final walletInfo = walletContacts[index];
return generateRaw(context, walletInfo);
}
return Container(
padding: EdgeInsets.only(bottom: 10),
child: Text(title, style: TextStyle(fontSize: 36)));
},
itemCounter: (int sectionIndex) =>
sectionIndex == 0 ? walletContacts.length : contacts.length,
itemBuilder: (_, sectionIndex, index) {
if (sectionIndex == 0) {
final walletInfo = walletContacts[index];
return generateRaw(context, walletInfo);
}
final contact = contacts[index];
final content = generateRaw(context, contact);
return contactListViewModel.isEditable
? Slidable(
key: Key('${contact.key}'),
endActionPane: _actionPane(context, contact),
child: content,
)
: content;
},
);})
);
final contact = contacts[index];
final content = generateRaw(context, contact);
return contactListViewModel.isEditable
? Slidable(
key: Key('${contact.key}'),
endActionPane: _actionPane(context, contact),
child: content,
)
: content;
},
);
}));
}
Widget generateRaw(BuildContext context, ContactBase contact) {
final image = contact.type.iconPath;
final currencyIcon = image != null ? Image.asset(image, height: 24, width: 24)
final currencyIcon = image != null
? Image.asset(image, height: 24, width: 24)
: const SizedBox(height: 24, width: 24);
return GestureDetector(
onTap: () async {
if (!contactListViewModel.isEditable) {
@@ -128,30 +134,28 @@ class ContactListPage extends BasePage {
if (isCopied) {
await Clipboard.setData(ClipboardData(text: contact.address));
await showBar<void>(context, S.of(context).copied_to_clipboard);
}
},
child: Container(
color: Colors.transparent,
padding:
const EdgeInsets.only(top: 16, bottom: 16, right: 24),
padding: const EdgeInsets.only(top: 16, bottom: 16, right: 24),
child: Row(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
currencyIcon,
Expanded(
child: Padding(
padding: EdgeInsets.only(left: 12),
child: Text(
contact.name,
style: TextStyle(
fontSize: 14,
fontWeight: FontWeight.normal,
color: Theme.of(context).primaryTextTheme!.titleLarge!.color!),
child: Padding(
padding: EdgeInsets.only(left: 12),
child: Text(
contact.name,
style: TextStyle(
fontSize: 14,
fontWeight: FontWeight.normal,
color: Theme.of(context).primaryTextTheme.titleLarge!.color!,
),
)
)
),
))
],
),
),
@@ -160,60 +164,61 @@ class ContactListPage extends BasePage {
Future<bool> showAlertDialog(BuildContext context) async {
return await showPopUp<bool>(
context: context,
builder: (BuildContext context) {
return AlertWithTwoActions(
alertTitle: S.of(context).address_remove_contact,
alertContent: S.of(context).address_remove_content,
rightButtonText: S.of(context).remove,
leftButtonText: S.of(context).cancel,
actionRightButton: () => Navigator.of(context).pop(true),
actionLeftButton: () => Navigator.of(context).pop(false));
}) ?? false;
context: context,
builder: (BuildContext context) {
return AlertWithTwoActions(
alertTitle: S.of(context).address_remove_contact,
alertContent: S.of(context).address_remove_content,
rightButtonText: S.of(context).remove,
leftButtonText: S.of(context).cancel,
actionRightButton: () => Navigator.of(context).pop(true),
actionLeftButton: () => Navigator.of(context).pop(false));
}) ??
false;
}
Future<bool> showNameAndAddressDialog(
BuildContext context, String name, String address) async {
return await showPopUp<bool>(
context: context,
builder: (BuildContext context) {
return AlertWithTwoActions(
alertTitle: name,
alertContent: address,
rightButtonText: S.of(context).copy,
leftButtonText: S.of(context).cancel,
actionRightButton: () => Navigator.of(context).pop(true),
actionLeftButton: () => Navigator.of(context).pop(false));
}) ?? false;
context: context,
builder: (BuildContext context) {
return AlertWithTwoActions(
alertTitle: name,
alertContent: address,
rightButtonText: S.of(context).copy,
leftButtonText: S.of(context).cancel,
actionRightButton: () => Navigator.of(context).pop(true),
actionLeftButton: () => Navigator.of(context).pop(false));
}) ??
false;
}
ActionPane _actionPane(BuildContext context, ContactRecord contact) => ActionPane(
motion: const ScrollMotion(),
extentRatio: 0.4,
children: [
SlidableAction(
onPressed: (_) async => await Navigator.of(context)
.pushNamed(Routes.addressBookAddContact,
arguments: contact),
backgroundColor: Colors.blue,
foregroundColor: Colors.white,
icon: Icons.edit,
label: S.of(context).edit,
),
SlidableAction(
onPressed: (_) async {
final isDelete =
await showAlertDialog(context);
ActionPane _actionPane(BuildContext context, ContactRecord contact) =>
ActionPane(
motion: const ScrollMotion(),
extentRatio: 0.4,
children: [
SlidableAction(
onPressed: (_) async => await Navigator.of(context)
.pushNamed(Routes.addressBookAddContact, arguments: contact),
backgroundColor: Colors.blue,
foregroundColor: Colors.white,
icon: Icons.edit,
label: S.of(context).edit,
),
SlidableAction(
onPressed: (_) async {
final isDelete = await showAlertDialog(context);
if (isDelete) {
await contactListViewModel.delete(contact);
}
},
backgroundColor: Colors.red,
foregroundColor: Colors.white,
icon: CupertinoIcons.delete,
label: S.of(context).delete,
),
],
);
if (isDelete) {
await contactListViewModel.delete(contact);
}
},
backgroundColor: Colors.red,
foregroundColor: Colors.white,
icon: CupertinoIcons.delete,
label: S.of(context).delete,
),
],
);
}
@@ -156,15 +156,29 @@ class _DesktopWalletSelectionDropDownState extends State<DesktopWalletSelectionD
} catch (e) {
changeProcessText(S.of(context).wallet_list_failed_to_load(wallet.name, e.toString()));
}
});
},
conditionToDetermineIfToUse2FA:
widget.walletListViewModel.shouldRequireTOTP2FAForAccessingWallet,
);
}
void _navigateToCreateWallet() {
if (isSingleCoin) {
Navigator.of(context)
.pushNamed(Routes.newWallet, arguments: widget.walletListViewModel.currentWalletType);
widget._authService.authenticateAction(
context,
route: Routes.newWallet,
arguments: widget.walletListViewModel.currentWalletType,
conditionToDetermineIfToUse2FA: widget
.walletListViewModel.shouldRequireTOTP2FAForCreatingNewWallets,
);
} else {
Navigator.of(context).pushNamed(Routes.newWalletType);
widget._authService.authenticateAction(
context,
route: Routes.newWalletType,
conditionToDetermineIfToUse2FA: widget
.walletListViewModel.shouldRequireTOTP2FAForCreatingNewWallets,
);
}
}
+230 -264
View File
@@ -1,3 +1,4 @@
import 'package:cake_wallet/core/auth_service.dart';
import 'package:cake_wallet/di.dart';
import 'package:cake_wallet/src/screens/exchange/widgets/desktop_exchange_cards_section.dart';
import 'package:cake_wallet/src/screens/exchange/widgets/mobile_exchange_cards_section.dart';
@@ -37,7 +38,7 @@ import 'package:cake_wallet/src/screens/exchange/widgets/present_provider_picker
import 'package:cake_wallet/src/screens/dashboard/widgets/sync_indicator_icon.dart';
class ExchangePage extends BasePage {
ExchangePage(this.exchangeViewModel) {
ExchangePage(this.exchangeViewModel, this.authService) {
depositWalletName = exchangeViewModel.depositCurrency == CryptoCurrency.xmr
? exchangeViewModel.wallet.name
: null;
@@ -47,6 +48,7 @@ class ExchangePage extends BasePage {
}
final ExchangeViewModel exchangeViewModel;
final AuthService authService;
final depositKey = GlobalKey<ExchangeCardState>();
final receiveKey = GlobalKey<ExchangeCardState>();
final _formKey = GlobalKey<FormState>();
@@ -89,16 +91,17 @@ class ExchangePage extends BasePage {
@override
Widget middle(BuildContext context) => Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Padding(
padding: const EdgeInsets.only(right:6.0),
child: Observer(builder: (_) => SyncIndicatorIcon(isSynced: exchangeViewModel.status is SyncedSyncStatus),)
),
PresentProviderPicker(exchangeViewModel: exchangeViewModel)
],
);
mainAxisAlignment: MainAxisAlignment.center,
children: [
Padding(
padding: const EdgeInsets.only(right: 6.0),
child: Observer(
builder: (_) =>
SyncIndicatorIcon(isSynced: exchangeViewModel.status is SyncedSyncStatus),
)),
PresentProviderPicker(exchangeViewModel: exchangeViewModel)
],
);
@override
Widget trailing(BuildContext context) => TrailButton(
@@ -110,12 +113,13 @@ class ExchangePage extends BasePage {
@override
Widget? leading(BuildContext context) {
final _backButton = Icon(Icons.arrow_back_ios,
final _backButton = Icon(
Icons.arrow_back_ios,
color: titleColor,
size: 16,
);
final _closeButton = currentTheme.type == ThemeType.dark
? closeButtonImageDarkTheme : closeButtonImage;
final _closeButton =
currentTheme.type == ThemeType.dark ? closeButtonImageDarkTheme : closeButtonImage;
bool isMobileView = ResponsiveLayoutUtil.instance.isMobile;
@@ -126,13 +130,10 @@ class ExchangePage extends BasePage {
child: ButtonTheme(
minWidth: double.minPositive,
child: Semantics(
label: !isMobileView
? S.of(context).close
: S.of(context).seed_alert_back,
label: !isMobileView ? S.of(context).close : S.of(context).seed_alert_back,
child: TextButton(
style: ButtonStyle(
overlayColor: MaterialStateColor.resolveWith(
(states) => Colors.transparent),
overlayColor: MaterialStateColor.resolveWith((states) => Colors.transparent),
),
onPressed: () => onClose(context),
child: !isMobileView ? _closeButton : _backButton,
@@ -145,23 +146,19 @@ class ExchangePage extends BasePage {
@override
Widget body(BuildContext context) {
WidgetsBinding.instance
.addPostFrameCallback((_) => _setReactions(context, exchangeViewModel));
WidgetsBinding.instance.addPostFrameCallback((_) => _setReactions(context, exchangeViewModel));
return KeyboardActions(
disableScroll: true,
config: KeyboardActionsConfig(
keyboardActionsPlatform: KeyboardActionsPlatform.IOS,
keyboardBarColor:
Theme.of(context).accentTextTheme!.bodyLarge!.backgroundColor!,
keyboardBarColor: Theme.of(context).accentTextTheme.bodyLarge!.backgroundColor!,
nextFocus: false,
actions: [
KeyboardActionsItem(
focusNode: _depositAmountFocus,
toolbarButtons: [(_) => KeyboardDoneButton()]),
focusNode: _depositAmountFocus, toolbarButtons: [(_) => KeyboardDoneButton()]),
KeyboardActionsItem(
focusNode: _receiveAmountFocus,
toolbarButtons: [(_) => KeyboardDoneButton()])
focusNode: _receiveAmountFocus, toolbarButtons: [(_) => KeyboardDoneButton()])
]),
child: Container(
color: Theme.of(context).colorScheme.background,
@@ -169,30 +166,28 @@ class ExchangePage extends BasePage {
key: _formKey,
child: ScrollableWithBottomSection(
contentPadding: EdgeInsets.only(bottom: 24),
content: Observer(builder: (_) => Column(
children: <Widget>[
_exchangeCardsSection(context),
Padding(
padding: EdgeInsets.only(top: 12, left: 24),
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
StandardCheckbox(
value: exchangeViewModel.isFixedRateMode,
caption: S.of(context).fixed_rate,
onChanged: (value) =>
exchangeViewModel.isFixedRateMode = value,
),
],
)
),
SizedBox(height: 30),
_buildTemplateSection(context)
content: Observer(
builder: (_) => Column(
children: <Widget>[
_exchangeCardsSection(context),
Padding(
padding: EdgeInsets.only(top: 12, left: 24),
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
StandardCheckbox(
value: exchangeViewModel.isFixedRateMode,
caption: S.of(context).fixed_rate,
onChanged: (value) => exchangeViewModel.isFixedRateMode = value,
),
],
)),
SizedBox(height: 30),
_buildTemplateSection(context)
],
),
),
bottomSectionPadding:
EdgeInsets.only(left: 24, right: 24, bottom: 24),
bottomSectionPadding: EdgeInsets.only(left: 24, right: 24, bottom: 24),
bottomSection: Column(children: <Widget>[
Padding(
padding: EdgeInsets.only(bottom: 15),
@@ -210,8 +205,7 @@ class ExchangePage extends BasePage {
textAlign: TextAlign.center,
style: TextStyle(
color: Theme.of(context)
.primaryTextTheme!
.displayLarge!
.primaryTextTheme.displayLarge!
.decorationColor!,
fontWeight: FontWeight.w500,
fontSize: 12),
@@ -223,29 +217,34 @@ class ExchangePage extends BasePage {
builder: (_) => LoadingPrimaryButton(
text: S.of(context).exchange,
onPressed: () {
if (_formKey.currentState != null && _formKey.currentState!.validate()) {
if ((exchangeViewModel.depositCurrency ==
CryptoCurrency.xmr) &&
(!(exchangeViewModel.status
is SyncedSyncStatus))) {
if (_formKey.currentState != null &&
_formKey.currentState!.validate()) {
if ((exchangeViewModel.depositCurrency == CryptoCurrency.xmr) &&
(!(exchangeViewModel.status is SyncedSyncStatus))) {
showPopUp<void>(
context: context,
builder: (BuildContext context) {
return AlertWithOneAction(
alertTitle: S.of(context).exchange,
alertContent: S
.of(context)
.exchange_sync_alert_content,
alertContent: S.of(context).exchange_sync_alert_content,
buttonText: S.of(context).ok,
buttonAction: () =>
Navigator.of(context).pop());
buttonAction: () => Navigator.of(context).pop());
});
} else {
exchangeViewModel.createTrade();
final check = exchangeViewModel.shouldDisplayTOTP();
authService.authenticateAction(
context,
conditionToDetermineIfToUse2FA: check,
onAuthSuccess: (value) {
if (value) {
exchangeViewModel.createTrade();
}
},
);
}
}
},
color: Theme.of(context).accentTextTheme!.bodyLarge!.color!,
color: Theme.of(context).accentTextTheme.bodyLarge!.color!,
textColor: Colors.white,
isDisabled: exchangeViewModel.selectedProviders.isEmpty,
isLoading: exchangeViewModel.tradeState is TradeIsCreating)),
@@ -264,7 +263,7 @@ class ExchangePage extends BasePage {
child: Observer(
builder: (_) {
final templates = exchangeViewModel.templates;
return Row(
children: <Widget>[
AddTemplateButton(
@@ -293,18 +292,15 @@ class ExchangePage extends BasePage {
builder: (dialogContext) {
return AlertWithTwoActions(
alertTitle: S.of(context).template,
alertContent:
S.of(context).confirm_delete_template,
alertContent: S.of(context).confirm_delete_template,
rightButtonText: S.of(context).delete,
leftButtonText: S.of(context).cancel,
actionRightButton: () {
Navigator.of(dialogContext).pop();
exchangeViewModel.removeTemplate(
template: template);
exchangeViewModel.removeTemplate(template: template);
exchangeViewModel.updateTemplate();
},
actionLeftButton: () =>
Navigator.of(dialogContext).pop());
actionLeftButton: () => Navigator.of(dialogContext).pop());
});
},
);
@@ -318,8 +314,8 @@ class ExchangePage extends BasePage {
);
}
void applyTemplate(BuildContext context,
ExchangeViewModel exchangeViewModel, ExchangeTemplate template) async {
void applyTemplate(
BuildContext context, ExchangeViewModel exchangeViewModel, ExchangeTemplate template) async {
exchangeViewModel.changeDepositCurrency(
currency: CryptoCurrency.fromString(template.depositCurrency));
exchangeViewModel.changeReceiveCurrency(
@@ -333,22 +329,19 @@ class ExchangePage extends BasePage {
var domain = template.depositAddress;
var ticker = template.depositCurrency.toLowerCase();
exchangeViewModel.depositAddress =
await fetchParsedAddress(context, domain, ticker);
exchangeViewModel.depositAddress = await fetchParsedAddress(context, domain, ticker);
domain = template.receiveAddress;
ticker = template.receiveCurrency.toLowerCase();
exchangeViewModel.receiveAddress =
await fetchParsedAddress(context, domain, ticker);
exchangeViewModel.receiveAddress = await fetchParsedAddress(context, domain, ticker);
}
void _setReactions(
BuildContext context, ExchangeViewModel exchangeViewModel) {
void _setReactions(BuildContext context, ExchangeViewModel exchangeViewModel) {
if (_isReactionsSet) {
return;
}
if (exchangeViewModel.isLowFee) {
if (exchangeViewModel.isLowFee) {
_showFeeAlert(context);
}
@@ -359,42 +352,30 @@ class ExchangePage extends BasePage {
final limitsState = exchangeViewModel.limitsState;
if (limitsState is LimitsLoadedSuccessfully) {
final min = limitsState.limits.min != null
? limitsState.limits.min.toString()
: null;
final max = limitsState.limits.max != null
? limitsState.limits.max.toString()
: null;
final key = exchangeViewModel.isFixedRateMode
? receiveKey
: depositKey;
final min = limitsState.limits.min != null ? limitsState.limits.min.toString() : null;
final max = limitsState.limits.max != null ? limitsState.limits.max.toString() : null;
final key = exchangeViewModel.isFixedRateMode ? receiveKey : depositKey;
key.currentState!.changeLimits(min: min, max: max);
}
_onCurrencyChange(
exchangeViewModel.receiveCurrency, exchangeViewModel, receiveKey);
_onCurrencyChange(
exchangeViewModel.depositCurrency, exchangeViewModel, depositKey);
_onCurrencyChange(exchangeViewModel.receiveCurrency, exchangeViewModel, receiveKey);
_onCurrencyChange(exchangeViewModel.depositCurrency, exchangeViewModel, depositKey);
reaction(
(_) => exchangeViewModel.wallet.name,
(String _) => _onWalletNameChange(
exchangeViewModel, exchangeViewModel.receiveCurrency, receiveKey));
(String _) =>
_onWalletNameChange(exchangeViewModel, exchangeViewModel.receiveCurrency, receiveKey));
reaction(
(_) => exchangeViewModel.wallet.name,
(String _) => _onWalletNameChange(
exchangeViewModel, exchangeViewModel.depositCurrency, depositKey));
(String _) =>
_onWalletNameChange(exchangeViewModel, exchangeViewModel.depositCurrency, depositKey));
reaction(
(_) => exchangeViewModel.receiveCurrency,
(CryptoCurrency currency) =>
_onCurrencyChange(currency, exchangeViewModel, receiveKey));
reaction((_) => exchangeViewModel.receiveCurrency,
(CryptoCurrency currency) => _onCurrencyChange(currency, exchangeViewModel, receiveKey));
reaction(
(_) => exchangeViewModel.depositCurrency,
(CryptoCurrency currency) =>
_onCurrencyChange(currency, exchangeViewModel, depositKey));
reaction((_) => exchangeViewModel.depositCurrency,
(CryptoCurrency currency) => _onCurrencyChange(currency, exchangeViewModel, depositKey));
reaction((_) => exchangeViewModel.depositAmount, (String amount) {
if (depositKey.currentState!.amountController.text != amount) {
@@ -408,8 +389,7 @@ class ExchangePage extends BasePage {
}
});
reaction((_) => exchangeViewModel.isDepositAddressEnabled,
(bool isEnabled) {
reaction((_) => exchangeViewModel.isDepositAddressEnabled, (bool isEnabled) {
depositKey.currentState!.isAddressEditable(isEditable: isEnabled);
});
@@ -425,13 +405,11 @@ class ExchangePage extends BasePage {
}
});
reaction((_) => exchangeViewModel.isReceiveAddressEnabled,
(bool isEnabled) {
reaction((_) => exchangeViewModel.isReceiveAddressEnabled, (bool isEnabled) {
receiveKey.currentState!.isAddressEditable(isEditable: isEnabled);
});
reaction((_) => exchangeViewModel.isReceiveAmountEditable,
(bool isReceiveAmountEditable) {
reaction((_) => exchangeViewModel.isReceiveAmountEditable, (bool isReceiveAmountEditable) {
receiveKey.currentState!.isAmountEditable(isEditable: isReceiveAmountEditable);
});
@@ -483,20 +461,20 @@ class ExchangePage extends BasePage {
}
});
depositAddressController.addListener(
() => exchangeViewModel.depositAddress = depositAddressController.text);
depositAddressController
.addListener(() => exchangeViewModel.depositAddress = depositAddressController.text);
depositAmountController.addListener(() {
if (depositAmountController.text != exchangeViewModel.depositAmount) {
_depositAmountDebounce.run(() {
_depositAmountDebounce.run(() {
exchangeViewModel.changeDepositAmount(amount: depositAmountController.text);
exchangeViewModel.isReceiveAmountEntered = false;
});
}
});
receiveAddressController.addListener(
() => exchangeViewModel.receiveAddress = receiveAddressController.text);
receiveAddressController
.addListener(() => exchangeViewModel.receiveAddress = receiveAddressController.text);
receiveAmountController.addListener(() {
if (receiveAmountController.text != exchangeViewModel.receiveAmount) {
@@ -507,8 +485,7 @@ class ExchangePage extends BasePage {
}
});
reaction((_) => exchangeViewModel.wallet.walletAddresses.address,
(String address) {
reaction((_) => exchangeViewModel.wallet.walletAddresses.address, (String address) {
if (exchangeViewModel.depositCurrency == CryptoCurrency.xmr) {
depositKey.currentState!.changeAddress(address: address);
}
@@ -519,22 +496,18 @@ class ExchangePage extends BasePage {
});
_depositAddressFocus.addListener(() async {
if (!_depositAddressFocus.hasFocus &&
depositAddressController.text.isNotEmpty) {
if (!_depositAddressFocus.hasFocus && depositAddressController.text.isNotEmpty) {
final domain = depositAddressController.text;
final ticker = exchangeViewModel.depositCurrency.title.toLowerCase();
exchangeViewModel.depositAddress =
await fetchParsedAddress(context, domain, ticker);
exchangeViewModel.depositAddress = await fetchParsedAddress(context, domain, ticker);
}
});
_receiveAddressFocus.addListener(() async {
if (!_receiveAddressFocus.hasFocus &&
receiveAddressController.text.isNotEmpty) {
if (!_receiveAddressFocus.hasFocus && receiveAddressController.text.isNotEmpty) {
final domain = receiveAddressController.text;
final ticker = exchangeViewModel.receiveCurrency.title.toLowerCase();
exchangeViewModel.receiveAddress =
await fetchParsedAddress(context, domain, ticker);
exchangeViewModel.receiveAddress = await fetchParsedAddress(context, domain, ticker);
}
});
@@ -554,29 +527,26 @@ class ExchangePage extends BasePage {
_isReactionsSet = true;
}
void _onCurrencyChange(CryptoCurrency currency,
ExchangeViewModel exchangeViewModel, GlobalKey<ExchangeCardState> key) {
void _onCurrencyChange(CryptoCurrency currency, ExchangeViewModel exchangeViewModel,
GlobalKey<ExchangeCardState> key) {
final isCurrentTypeWallet = currency == exchangeViewModel.wallet.currency;
key.currentState!.changeSelectedCurrency(currency);
key.currentState!.changeWalletName(
isCurrentTypeWallet ? exchangeViewModel.wallet.name : '');
key.currentState!.changeWalletName(isCurrentTypeWallet ? exchangeViewModel.wallet.name : '');
key.currentState!.changeAddress(
address: isCurrentTypeWallet
? exchangeViewModel.wallet.walletAddresses.address : '');
address: isCurrentTypeWallet ? exchangeViewModel.wallet.walletAddresses.address : '');
key.currentState!.changeAmount(amount: '');
}
void _onWalletNameChange(ExchangeViewModel exchangeViewModel,
CryptoCurrency currency, GlobalKey<ExchangeCardState> key) {
void _onWalletNameChange(ExchangeViewModel exchangeViewModel, CryptoCurrency currency,
GlobalKey<ExchangeCardState> key) {
final isCurrentTypeWallet = currency == exchangeViewModel.wallet.currency;
if (isCurrentTypeWallet) {
key.currentState!.changeWalletName(exchangeViewModel.wallet.name);
key.currentState!.addressController.text =
exchangeViewModel.wallet.walletAddresses.address;
key.currentState!.addressController.text = exchangeViewModel.wallet.walletAddresses.address;
} else if (key.currentState!.addressController.text ==
exchangeViewModel.wallet.walletAddresses.address) {
key.currentState!.changeWalletName('');
@@ -584,8 +554,7 @@ class ExchangePage extends BasePage {
}
}
Future<String> fetchParsedAddress(
BuildContext context, String domain, String ticker) async {
Future<String> fetchParsedAddress(BuildContext context, String domain, String ticker) async {
final parsedAddress = await getIt.get<AddressResolver>().resolve(domain, ticker);
final address = await extractAddressFromParsed(context, parsedAddress);
return address;
@@ -594,16 +563,17 @@ class ExchangePage extends BasePage {
void _showFeeAlert(BuildContext context) async {
await Future<void>.delayed(Duration(seconds: 1));
final confirmed = await showPopUp<bool>(
context: context,
builder: (dialogContext) {
return AlertWithTwoActions(
alertTitle: S.of(context).low_fee,
alertContent: S.of(context).low_fee_alert,
leftButtonText: S.of(context).ignor,
rightButtonText: S.of(context).use_suggested,
actionLeftButton: () => Navigator.of(dialogContext).pop(false),
actionRightButton: () => Navigator.of(dialogContext).pop(true));
}) ?? false;
context: context,
builder: (dialogContext) {
return AlertWithTwoActions(
alertTitle: S.of(context).low_fee,
alertContent: S.of(context).low_fee_alert,
leftButtonText: S.of(context).ignor,
rightButtonText: S.of(context).use_suggested,
actionLeftButton: () => Navigator.of(dialogContext).pop(false),
actionRightButton: () => Navigator.of(dialogContext).pop(true));
}) ??
false;
if (confirmed) {
exchangeViewModel.setDefaultTransactionPriority();
}
@@ -612,126 +582,122 @@ class ExchangePage extends BasePage {
void disposeBestRateSync() => exchangeViewModel.bestRateSync.cancel();
Widget _exchangeCardsSection(BuildContext context) {
final firstExchangeCard = Observer(builder: (_) => ExchangeCard(
onDispose: disposeBestRateSync,
hasAllAmount: exchangeViewModel.hasAllAmount,
allAmount: exchangeViewModel.hasAllAmount
? () => exchangeViewModel.calculateDepositAllAmount()
: null,
amountFocusNode: _depositAmountFocus,
addressFocusNode: _depositAddressFocus,
key: depositKey,
title: S.of(context).you_will_send,
initialCurrency: exchangeViewModel.depositCurrency,
initialWalletName: depositWalletName ?? '',
initialAddress:
exchangeViewModel.depositCurrency == exchangeViewModel.wallet.currency
? exchangeViewModel.wallet.walletAddresses.address
: exchangeViewModel.depositAddress,
initialIsAmountEditable: true,
initialIsAddressEditable: exchangeViewModel.isDepositAddressEnabled,
isAmountEstimated: false,
hasRefundAddress: true,
isMoneroWallet: exchangeViewModel.isMoneroWallet,
currencies: exchangeViewModel.depositCurrencies,
onCurrencySelected: (currency) {
// FIXME: need to move it into view model
if (currency == CryptoCurrency.xmr &&
exchangeViewModel.wallet.type != WalletType.monero) {
showPopUp<void>(
context: context,
builder: (dialogContext) {
return AlertWithOneAction(
alertTitle: S.of(context).error,
alertContent:
S.of(context).exchange_incorrect_current_wallet_for_xmr,
buttonText: S.of(context).ok,
buttonAction: () => Navigator.of(dialogContext).pop());
});
return;
}
final firstExchangeCard = Observer(
builder: (_) => ExchangeCard(
onDispose: disposeBestRateSync,
hasAllAmount: exchangeViewModel.hasAllAmount,
allAmount: exchangeViewModel.hasAllAmount
? () => exchangeViewModel.calculateDepositAllAmount()
: null,
amountFocusNode: _depositAmountFocus,
addressFocusNode: _depositAddressFocus,
key: depositKey,
title: S.of(context).you_will_send,
initialCurrency: exchangeViewModel.depositCurrency,
initialWalletName: depositWalletName ?? '',
initialAddress: exchangeViewModel.depositCurrency == exchangeViewModel.wallet.currency
? exchangeViewModel.wallet.walletAddresses.address
: exchangeViewModel.depositAddress,
initialIsAmountEditable: true,
initialIsAddressEditable: exchangeViewModel.isDepositAddressEnabled,
isAmountEstimated: false,
hasRefundAddress: true,
isMoneroWallet: exchangeViewModel.isMoneroWallet,
currencies: exchangeViewModel.depositCurrencies,
onCurrencySelected: (currency) {
// FIXME: need to move it into view model
if (currency == CryptoCurrency.xmr &&
exchangeViewModel.wallet.type != WalletType.monero) {
showPopUp<void>(
context: context,
builder: (dialogContext) {
return AlertWithOneAction(
alertTitle: S.of(context).error,
alertContent: S.of(context).exchange_incorrect_current_wallet_for_xmr,
buttonText: S.of(context).ok,
buttonAction: () => Navigator.of(dialogContext).pop());
});
return;
}
exchangeViewModel.changeDepositCurrency(currency: currency);
},
imageArrow: arrowBottomPurple,
currencyButtonColor: Colors.transparent,
addressButtonsColor: Theme.of(context).focusColor!,
borderColor: Theme.of(context).primaryTextTheme!.bodyLarge!.color!,
currencyValueValidator: (value) {
return !exchangeViewModel.isFixedRateMode
? AmountValidator(
isAutovalidate: true,
currency: exchangeViewModel.depositCurrency,
minValue: exchangeViewModel.limits.min.toString(),
maxValue: exchangeViewModel.limits.max.toString(),
).call(value)
: null;
},
addressTextFieldValidator:
AddressValidator(type: exchangeViewModel.depositCurrency),
onPushPasteButton: (context) async {
final domain = exchangeViewModel.depositAddress;
final ticker = exchangeViewModel.depositCurrency.title.toLowerCase();
exchangeViewModel.depositAddress =
await fetchParsedAddress(context, domain, ticker);
},
onPushAddressBookButton: (context) async {
final domain = exchangeViewModel.depositAddress;
final ticker = exchangeViewModel.depositCurrency.title.toLowerCase();
exchangeViewModel.depositAddress =
await fetchParsedAddress(context, domain, ticker);
},
));
exchangeViewModel.changeDepositCurrency(currency: currency);
},
imageArrow: arrowBottomPurple,
currencyButtonColor: Colors.transparent,
addressButtonsColor: Theme.of(context).focusColor,
borderColor: Theme.of(context).primaryTextTheme.bodyLarge!.color!,
currencyValueValidator: (value) {
return !exchangeViewModel.isFixedRateMode
? AmountValidator(
isAutovalidate: true,
currency: exchangeViewModel.depositCurrency,
minValue: exchangeViewModel.limits.min.toString(),
maxValue: exchangeViewModel.limits.max.toString(),
).call(value)
: null;
},
addressTextFieldValidator: AddressValidator(type: exchangeViewModel.depositCurrency),
onPushPasteButton: (context) async {
final domain = exchangeViewModel.depositAddress;
final ticker = exchangeViewModel.depositCurrency.title.toLowerCase();
exchangeViewModel.depositAddress =
await fetchParsedAddress(context, domain, ticker);
},
onPushAddressBookButton: (context) async {
final domain = exchangeViewModel.depositAddress;
final ticker = exchangeViewModel.depositCurrency.title.toLowerCase();
exchangeViewModel.depositAddress =
await fetchParsedAddress(context, domain, ticker);
},
));
final secondExchangeCard = Observer(builder: (_) => ExchangeCard(
onDispose: disposeBestRateSync,
amountFocusNode: _receiveAmountFocus,
addressFocusNode: _receiveAddressFocus,
key: receiveKey,
title: S.of(context).you_will_get,
initialCurrency: exchangeViewModel.receiveCurrency,
initialWalletName: receiveWalletName ?? '',
initialAddress:
exchangeViewModel.receiveCurrency == exchangeViewModel.wallet.currency
? exchangeViewModel.wallet.walletAddresses.address
: exchangeViewModel.receiveAddress,
initialIsAmountEditable: exchangeViewModel.isReceiveAmountEditable,
initialIsAddressEditable: exchangeViewModel.isReceiveAddressEnabled,
isAmountEstimated: true,
isMoneroWallet: exchangeViewModel.isMoneroWallet,
currencies: exchangeViewModel.receiveCurrencies,
onCurrencySelected: (currency) =>
exchangeViewModel.changeReceiveCurrency(currency: currency),
imageArrow: arrowBottomCakeGreen,
currencyButtonColor: Colors.transparent,
addressButtonsColor: Theme.of(context).focusColor!,
borderColor:
Theme.of(context).primaryTextTheme!.bodyLarge!.decorationColor!,
currencyValueValidator: (value) {
return exchangeViewModel.isFixedRateMode
? AmountValidator(
isAutovalidate: true,
currency: exchangeViewModel.receiveCurrency,
minValue: exchangeViewModel.limits.min.toString(),
maxValue: exchangeViewModel.limits.max.toString(),
).call(value)
: null;
},
addressTextFieldValidator:
AddressValidator(type: exchangeViewModel.receiveCurrency),
onPushPasteButton: (context) async {
final domain = exchangeViewModel.receiveAddress;
final ticker = exchangeViewModel.receiveCurrency.title.toLowerCase();
exchangeViewModel.receiveAddress =
await fetchParsedAddress(context, domain, ticker);
},
onPushAddressBookButton: (context) async {
final domain = exchangeViewModel.receiveAddress;
final ticker = exchangeViewModel.receiveCurrency.title.toLowerCase();
exchangeViewModel.receiveAddress =
await fetchParsedAddress(context, domain, ticker);
},
));
final secondExchangeCard = Observer(
builder: (_) => ExchangeCard(
onDispose: disposeBestRateSync,
amountFocusNode: _receiveAmountFocus,
addressFocusNode: _receiveAddressFocus,
key: receiveKey,
title: S.of(context).you_will_get,
initialCurrency: exchangeViewModel.receiveCurrency,
initialWalletName: receiveWalletName ?? '',
initialAddress: exchangeViewModel.receiveCurrency == exchangeViewModel.wallet.currency
? exchangeViewModel.wallet.walletAddresses.address
: exchangeViewModel.receiveAddress,
initialIsAmountEditable: exchangeViewModel.isReceiveAmountEditable,
initialIsAddressEditable: exchangeViewModel.isReceiveAddressEnabled,
isAmountEstimated: true,
isMoneroWallet: exchangeViewModel.isMoneroWallet,
currencies: exchangeViewModel.receiveCurrencies,
onCurrencySelected: (currency) =>
exchangeViewModel.changeReceiveCurrency(currency: currency),
imageArrow: arrowBottomCakeGreen,
currencyButtonColor: Colors.transparent,
addressButtonsColor: Theme.of(context).focusColor,
borderColor: Theme.of(context).primaryTextTheme.bodyLarge!.decorationColor!,
currencyValueValidator: (value) {
return exchangeViewModel.isFixedRateMode
? AmountValidator(
isAutovalidate: true,
currency: exchangeViewModel.receiveCurrency,
minValue: exchangeViewModel.limits.min.toString(),
maxValue: exchangeViewModel.limits.max.toString(),
).call(value)
: null;
},
addressTextFieldValidator: AddressValidator(type: exchangeViewModel.receiveCurrency),
onPushPasteButton: (context) async {
final domain = exchangeViewModel.receiveAddress;
final ticker = exchangeViewModel.receiveCurrency.title.toLowerCase();
exchangeViewModel.receiveAddress =
await fetchParsedAddress(context, domain, ticker);
},
onPushAddressBookButton: (context) async {
final domain = exchangeViewModel.receiveAddress;
final ticker = exchangeViewModel.receiveCurrency.title.toLowerCase();
exchangeViewModel.receiveAddress =
await fetchParsedAddress(context, domain, ticker);
},
));
if (ResponsiveLayoutUtil.instance.isMobile) {
return MobileExchangeCardsSection(
+10 -10
View File
@@ -97,7 +97,8 @@ class RootState extends State<Root> with WidgetsBindingObserver {
return;
}
if (!_isInactive && widget.authenticationStore.state == AuthenticationState.allowed) {
if (!_isInactive &&
widget.authenticationStore.state == AuthenticationState.allowed) {
setState(() => _setInactive(true));
}
@@ -124,13 +125,16 @@ class RootState extends State<Root> with WidgetsBindingObserver {
return;
} else {
final useTotp = widget.appStore.settingsStore.useTOTP2FA;
if (useTotp) {
final shouldUseTotp2FAToAccessWallets = widget.appStore
.settingsStore.shouldRequireTOTP2FAForAccessingWallet;
if (useTotp && shouldUseTotp2FAToAccessWallets) {
_reset();
auth.close(
route: Routes.totpAuthCodePage,
arguments: TotpAuthArgumentsModel(
onTotpAuthenticationFinished:
(bool isAuthenticatedSuccessfully, TotpAuthCodePageState totpAuth) {
(bool isAuthenticatedSuccessfully,
TotpAuthCodePageState totpAuth) {
if (!isAuthenticatedSuccessfully) {
return;
}
@@ -151,15 +155,11 @@ class RootState extends State<Root> with WidgetsBindingObserver {
route: launchUri != null ? Routes.send : null,
arguments: PaymentRequest.fromUri(launchUri),
);
launchUri = null;
launchUri = null;
}
}
},
);
},
);
});
} else if (launchUri != null) {
widget.navigatorKey.currentState?.pushNamed(
+34 -18
View File
@@ -1,3 +1,4 @@
import 'package:cake_wallet/core/auth_service.dart';
import 'package:cake_wallet/entities/fiat_currency.dart';
import 'package:cake_wallet/entities/template.dart';
import 'package:cake_wallet/src/screens/dashboard/widgets/sync_indicator_icon.dart';
@@ -32,10 +33,12 @@ import 'package:cw_core/crypto_currency.dart';
class SendPage extends BasePage {
SendPage({
required this.sendViewModel,
required this.authService,
this.initialPaymentRequest,
}) : _formKey = GlobalKey<FormState>();
final SendViewModel sendViewModel;
final AuthService authService;
final GlobalKey<FormState> _formKey;
final controller = PageController(initialPage: 0);
final PaymentRequest? initialPaymentRequest;
@@ -56,12 +59,14 @@ class SendPage extends BasePage {
@override
Widget? leading(BuildContext context) {
final _backButton = Icon(Icons.arrow_back_ios,
final _backButton = Icon(
Icons.arrow_back_ios,
color: titleColor,
size: 16,
);
final _closeButton = currentTheme.type == ThemeType.dark
? closeButtonImageDarkTheme : closeButtonImage;
? closeButtonImageDarkTheme
: closeButtonImage;
bool isMobileView = ResponsiveLayoutUtil.instance.isMobile;
@@ -78,7 +83,7 @@ class SendPage extends BasePage {
child: TextButton(
style: ButtonStyle(
overlayColor: MaterialStateColor.resolveWith(
(states) => Colors.transparent),
(states) => Colors.transparent),
),
onPressed: () => onClose(context),
child: !isMobileView ? _closeButton : _backButton,
@@ -114,11 +119,13 @@ class SendPage extends BasePage {
mainAxisAlignment: MainAxisAlignment.center,
children: [
Padding(
padding: const EdgeInsets.only(right:8.0),
child: Observer(builder: (_) => SyncIndicatorIcon(isSynced: sendViewModel.isReadyForSend),),
padding: const EdgeInsets.only(right: 8.0),
child: Observer(
builder: (_) =>
SyncIndicatorIcon(isSynced: sendViewModel.isReadyForSend),
),
),
if (supMiddle != null)
supMiddle
if (supMiddle != null) supMiddle
],
);
}
@@ -200,12 +207,12 @@ class SendPage extends BasePage {
dotWidth: 6.0,
dotHeight: 6.0,
dotColor: Theme.of(context)
.primaryTextTheme
!.displaySmall!
.primaryTextTheme!
.displaySmall!
.backgroundColor!,
activeDotColor: Theme.of(context)
.primaryTextTheme
!.displayMedium!
.primaryTextTheme!
.displayMedium!
.backgroundColor!),
)
: Offstage();
@@ -339,8 +346,8 @@ class SendPage extends BasePage {
'Change your asset (${sendViewModel.selectedCryptoCurrency})',
color: Colors.transparent,
textColor: Theme.of(context)
.accentTextTheme
!.displaySmall!
.accentTextTheme!
.displaySmall!
.decorationColor!,
))),
if (sendViewModel.hasMultiRecipient)
@@ -357,13 +364,13 @@ class SendPage extends BasePage {
text: S.of(context).add_receiver,
color: Colors.transparent,
textColor: Theme.of(context)
.accentTextTheme
!.displaySmall!
.accentTextTheme!
.displaySmall!
.decorationColor!,
isDottedBorder: true,
borderColor: Theme.of(context)
.primaryTextTheme
!.displaySmall!
.primaryTextTheme!
.displaySmall!
.decorationColor!,
)),
Observer(
@@ -390,7 +397,16 @@ class SendPage extends BasePage {
return;
}
await sendViewModel.createTransaction();
final check = sendViewModel.shouldDisplayTotp();
authService.authenticateAction(
context,
conditionToDetermineIfToUse2FA: check,
onAuthSuccess: (value) async {
if (value) {
await sendViewModel.createTransaction();
}
},
);
},
text: S.of(context).send,
color:
@@ -30,12 +30,22 @@ class SecurityBackupPage extends BasePage {
child: Column(mainAxisSize: MainAxisSize.min, children: [
SettingsCellWithArrow(
title: S.current.show_keys,
handler: (_) => _authService.authenticateAction(context, route: Routes.showKeys),
handler: (_) => _authService.authenticateAction(
context,
route: Routes.showKeys,
conditionToDetermineIfToUse2FA: _securitySettingsViewModel
.shouldRequireTOTP2FAForAllSecurityAndBackupSettings,
),
),
StandardListSeparator(padding: EdgeInsets.symmetric(horizontal: 24)),
SettingsCellWithArrow(
title: S.current.create_backup,
handler: (_) => _authService.authenticateAction(context, route: Routes.backup),
handler: (_) => _authService.authenticateAction(
context,
route: Routes.backup,
conditionToDetermineIfToUse2FA: _securitySettingsViewModel
.shouldRequireTOTP2FAForAllSecurityAndBackupSettings,
),
),
StandardListSeparator(padding: EdgeInsets.symmetric(horizontal: 24)),
SettingsCellWithArrow(
@@ -46,6 +56,8 @@ class SecurityBackupPage extends BasePage {
arguments: (PinCodeState<PinCodeWidget> setupPinContext, String _) {
setupPinContext.close();
},
conditionToDetermineIfToUse2FA: _securitySettingsViewModel
.shouldRequireTOTP2FAForAllSecurityAndBackupSettings,
),
),
StandardListSeparator(padding: EdgeInsets.symmetric(horizontal: 24)),
@@ -67,7 +79,10 @@ class SecurityBackupPage extends BasePage {
_securitySettingsViewModel
.setAllowBiometricalAuthentication(isAuthenticatedSuccessfully);
}
});
},
conditionToDetermineIfToUse2FA: _securitySettingsViewModel
.shouldRequireTOTP2FAForAllSecurityAndBackupSettings,
);
} else {
_securitySettingsViewModel.setAllowBiometricalAuthentication(value);
}
@@ -94,6 +109,8 @@ class SecurityBackupPage extends BasePage {
route: _securitySettingsViewModel.useTotp2FA
? Routes.modify2FAPage
: Routes.setup_2faPage,
conditionToDetermineIfToUse2FA: _securitySettingsViewModel
.shouldRequireTOTP2FAForAllSecurityAndBackupSettings,
),
);
},
@@ -22,7 +22,7 @@ class SettingsChoicesCell extends StatelessWidget {
style: TextStyle(
fontSize: 14,
fontWeight: FontWeight.normal,
color: Theme.of(context).primaryTextTheme!.titleLarge!.color!,
color: Theme.of(context).primaryTextTheme.titleLarge!.color!,
),
),
],
@@ -34,10 +34,7 @@ class SettingsChoicesCell extends StatelessWidget {
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(30),
color: Theme.of(context)
.accentTextTheme!
.displaySmall!
.color!,
color: Theme.of(context).accentTextTheme.displaySmall!.color!,
),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
@@ -52,10 +49,7 @@ class SettingsChoicesCell extends StatelessWidget {
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(30),
color: isSelected
? Theme.of(context)
.accentTextTheme!
.bodyLarge!
.color!
? Theme.of(context).accentTextTheme.bodyLarge!.color!
: null,
),
child: Text(
@@ -63,10 +57,7 @@ class SettingsChoicesCell extends StatelessWidget {
style: TextStyle(
color: isSelected
? Colors.white
: Theme.of(context)
.primaryTextTheme!
.bodySmall!
.color!,
: Theme.of(context).primaryTextTheme.bodySmall!.color!,
fontWeight: isSelected ? FontWeight.w700 : FontWeight.normal,
),
),
+147 -30
View File
@@ -1,12 +1,16 @@
import 'package:cake_wallet/entities/cake_2fa_preset_options.dart';
import 'package:cake_wallet/generated/i18n.dart';
import 'package:cake_wallet/src/screens/settings/widgets/settings_choices_cell.dart';
import 'package:cake_wallet/src/screens/settings/widgets/settings_switcher_cell.dart';
import 'package:cake_wallet/src/widgets/alert_with_two_actions.dart';
import 'package:cake_wallet/utils/show_pop_up.dart';
import 'package:flutter/cupertino.dart';
import 'package:cake_wallet/view_model/settings/choices_list_item.dart';
import 'package:flutter/material.dart';
import 'package:cake_wallet/src/screens/base_page.dart';
import 'package:cake_wallet/src/screens/settings/widgets/settings_cell_with_arrow.dart';
import 'package:cake_wallet/view_model/set_up_2fa_viewmodel.dart';
import 'package:cake_wallet/src/widgets/standard_list.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
import '../../../routes.dart';
@@ -21,35 +25,148 @@ class Modify2FAPage extends BasePage {
@override
Widget body(BuildContext context) {
return SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SettingsCellWithArrow(
title: S.current.disable_cake_2fa,
handler: (_) async {
await showPopUp<void>(
context: context,
builder: (BuildContext context) {
return AlertWithTwoActions(
alertTitle: S.current.disable_cake_2fa,
alertContent: S.current.question_to_disable_2fa,
leftButtonText: S.current.cancel,
rightButtonText: S.current.disable,
actionLeftButton: () {
Navigator.of(context).pop();
},
actionRightButton: () {
setup2FAViewModel.setUseTOTP2FA(false);
Navigator.pushNamedAndRemoveUntil(
context, Routes.dashboard, (route) => false);
},
);
},
);
}),
StandardListSeparator(padding: EdgeInsets.symmetric(horizontal: 24)),
],
),
child: _2FAControlsWidget(setup2FAViewModel: setup2FAViewModel),
);
}
}
class _2FAControlsWidget extends StatelessWidget {
const _2FAControlsWidget({required this.setup2FAViewModel});
final Setup2FAViewModel setup2FAViewModel;
@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SettingsCellWithArrow(
title: S.current.disable_cake_2fa,
handler: (_) async {
await showPopUp<void>(
context: context,
builder: (BuildContext context) {
return AlertWithTwoActions(
alertTitle: S.current.disable_cake_2fa,
alertContent: S.current.question_to_disable_2fa,
leftButtonText: S.current.cancel,
rightButtonText: S.current.disable,
actionLeftButton: () => Navigator.of(context).pop(),
actionRightButton: () {
setup2FAViewModel.setUseTOTP2FA(false);
Navigator.pushNamedAndRemoveUntil(context, Routes.dashboard, (route) => false);
},
);
},
);
},
),
StandardListSeparator(padding: EdgeInsets.symmetric(horizontal: 24)),
Observer(
builder: (context) {
return SettingsChoicesCell(
ChoicesListItem<Cake2FAPresetsOptions>(
title: S.current.cake_2fa_preset,
onItemSelected: setup2FAViewModel.selectCakePreset,
selectedItem: setup2FAViewModel.selectedCake2FAPreset,
items: [
Cake2FAPresetsOptions.narrow,
Cake2FAPresetsOptions.normal,
Cake2FAPresetsOptions.aggressive,
],
),
);
},
),
Observer(
builder: (context) {
return SettingsSwitcherCell(
title: S.current.require_for_assessing_wallet,
value: setup2FAViewModel.shouldRequireTOTP2FAForAccessingWallet,
onValueChange: (context, value) async =>
setup2FAViewModel.switchShouldRequireTOTP2FAForAccessingWallet(value),
);
},
),
StandardListSeparator(padding: EdgeInsets.symmetric(horizontal: 24)),
Observer(
builder: (context) {
return SettingsSwitcherCell(
title: S.current.require_for_sends_to_non_contacts,
value: setup2FAViewModel.shouldRequireTOTP2FAForSendsToNonContact,
onValueChange: (context, value) async =>
setup2FAViewModel.switchShouldRequireTOTP2FAForSendsToNonContact(value),
);
},
),
StandardListSeparator(padding: EdgeInsets.symmetric(horizontal: 24)),
Observer(
builder: (context) {
return SettingsSwitcherCell(
title: S.current.require_for_sends_to_contacts,
value: setup2FAViewModel.shouldRequireTOTP2FAForSendsToContact,
onValueChange: (context, value) async =>
setup2FAViewModel.switchShouldRequireTOTP2FAForSendsToContact(value),
);
},
),
StandardListSeparator(padding: EdgeInsets.symmetric(horizontal: 24)),
Observer(
builder: (context) {
return SettingsSwitcherCell(
title: S.current.require_for_sends_to_internal_wallets,
value: setup2FAViewModel.shouldRequireTOTP2FAForSendsToInternalWallets,
onValueChange: (context, value) async =>
setup2FAViewModel.switchShouldRequireTOTP2FAForSendsToInternalWallets(value),
);
},
),
StandardListSeparator(padding: EdgeInsets.symmetric(horizontal: 24)),
Observer(
builder: (context) {
return SettingsSwitcherCell(
title: S.current.require_for_exchanges_to_internal_wallets,
value: setup2FAViewModel.shouldRequireTOTP2FAForExchangesToInternalWallets,
onValueChange: (context, value) async =>
setup2FAViewModel.switchShouldRequireTOTP2FAForExchangesToInternalWallets(value),
);
},
),
StandardListSeparator(padding: EdgeInsets.symmetric(horizontal: 24)),
Observer(
builder: (context) {
return SettingsSwitcherCell(
title: S.current.require_for_adding_contacts,
value: setup2FAViewModel.shouldRequireTOTP2FAForAddingContacts,
onValueChange: (context, value) async =>
setup2FAViewModel.switchShouldRequireTOTP2FAForAddingContacts(value),
);
},
),
StandardListSeparator(padding: EdgeInsets.symmetric(horizontal: 24)),
Observer(
builder: (context) {
return SettingsSwitcherCell(
title: S.current.require_for_creating_new_wallets,
value: setup2FAViewModel.shouldRequireTOTP2FAForCreatingNewWallets,
onValueChange: (context, value) async =>
setup2FAViewModel.switchShouldRequireTOTP2FAForCreatingNewWallet(value),
);
},
),
StandardListSeparator(padding: EdgeInsets.symmetric(horizontal: 24)),
Observer(
builder: (context) {
return SettingsSwitcherCell(
title: S.current.require_for_all_security_and_backup_settings,
value: setup2FAViewModel.shouldRequireTOTP2FAForAllSecurityAndBackupSettings,
onValueChange: (context, value) async => setup2FAViewModel
.switchShouldRequireTOTP2FAForAllSecurityAndBackupSettings(value),
);
},
),
StandardListSeparator(padding: EdgeInsets.symmetric(horizontal: 24)),
],
);
}
}
+2 -1
View File
@@ -52,7 +52,8 @@ class Setup2FAPage extends BasePage {
SizedBox(height: 86),
SettingsCellWithArrow(
title: S.current.setup_totp_recommended,
handler: (_) => Navigator.of(context).pushNamed(Routes.setup_2faQRPage),
handler: (_) => Navigator.of(context)
.pushReplacementNamed(Routes.setup_2faQRPage),
),
StandardListSeparator(padding: EdgeInsets.symmetric(horizontal: 24)),
],
@@ -18,7 +18,8 @@ import 'package:mobx/mobx.dart';
import '../../../palette.dart';
import '../../../routes.dart';
typedef OnTotpAuthenticationFinished = void Function(bool, TotpAuthCodePageState);
typedef OnTotpAuthenticationFinished = void Function(
bool, TotpAuthCodePageState);
class TotpAuthCodePage extends StatefulWidget {
TotpAuthCodePage(
@@ -43,8 +44,9 @@ class TotpAuthCodePageState extends State<TotpAuthCodePage> {
@override
void initState() {
if(widget.totpArguments.onTotpAuthenticationFinished != null) {
_reaction ??= reaction((_) => widget.setup2FAViewModel.state, (ExecutionState state) {
if (widget.totpArguments.onTotpAuthenticationFinished != null) {
_reaction ??= reaction((_) => widget.setup2FAViewModel.state,
(ExecutionState state) {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (state is ExecutedSuccessfullyState) {
widget.totpArguments.onTotpAuthenticationFinished!(true, this);
@@ -57,9 +59,9 @@ class TotpAuthCodePageState extends State<TotpAuthCodePage> {
if (state is AuthenticationBanned) {
widget.totpArguments.onTotpAuthenticationFinished!(false, this);
}
});
});
}
});
});
}
super.initState();
@@ -73,7 +75,8 @@ class TotpAuthCodePageState extends State<TotpAuthCodePage> {
void changeProcessText(String text) {
dismissFlushBar(_authBar);
_progressBar = createBar<void>(text, duration: null)..show(_key.currentContext!);
_progressBar = createBar<void>(text, duration: null)
..show(_key.currentContext!);
}
Future<void> close({String? route, dynamic arguments}) async {
@@ -82,7 +85,8 @@ class TotpAuthCodePageState extends State<TotpAuthCodePage> {
}
await Future<void>.delayed(Duration(milliseconds: 50));
if (route != null) {
Navigator.of(_key.currentContext!).pushReplacementNamed(route, arguments: arguments);
Navigator.of(_key.currentContext!)
.pushReplacementNamed(route, arguments: arguments);
} else {
Navigator.of(_key.currentContext!).pop();
}
@@ -120,7 +124,8 @@ class TOTPEnterCode extends BasePage {
}
@override
String get title => isForSetup ? S.current.setup_2fa : S.current.verify_with_2fa;
String get title =>
isForSetup ? S.current.setup_2fa : S.current.verify_with_2fa;
Widget? leading(BuildContext context) {
return isClosable ? super.leading(context) : null;
@@ -166,21 +171,24 @@ class TOTPEnterCode extends BasePage {
return PrimaryButton(
isDisabled: setup2FAViewModel.enteredOTPCode.length != 8,
onPressed: () async {
final result =
await setup2FAViewModel.totp2FAAuth(totpController.text, isForSetup);
final bannedState = setup2FAViewModel.state is AuthenticationBanned;
final result = await setup2FAViewModel.totp2FAAuth(
totpController.text, isForSetup);
final bannedState =
setup2FAViewModel.state is AuthenticationBanned;
await showPopUp<void>(
context: context,
builder: (BuildContext context) {
return PopUpCancellableAlertDialog(
contentText: _textDisplayedInPopupOnResult(result, bannedState, context),
contentText: _textDisplayedInPopupOnResult(
result, bannedState, context),
actionButtonText: S.of(context).ok,
buttonAction: () {
result ? setup2FAViewModel.success() : null;
if (isForSetup && result) {
Navigator.pushNamedAndRemoveUntil(
context, Routes.dashboard, (route) => false);
Navigator.pop(context);
// Navigator.of(context)
// .popAndPushNamed(Routes.modify2FAPage);
} else {
Navigator.of(context).pop(result);
}
@@ -188,6 +196,11 @@ class TOTPEnterCode extends BasePage {
);
},
);
if (isForSetup && result) {
Navigator.pushReplacementNamed(
context, Routes.modify2FAPage);
}
},
text: S.of(context).continue_text,
color: Theme.of(context).accentTextTheme.bodyLarge!.color!,
@@ -201,10 +214,13 @@ class TOTPEnterCode extends BasePage {
);
}
String _textDisplayedInPopupOnResult(bool result, bool bannedState, BuildContext context) {
String _textDisplayedInPopupOnResult(
bool result, bool bannedState, BuildContext context) {
switch (result) {
case true:
return isForSetup ? S.current.totp_2fa_success : S.current.totp_verification_success;
return isForSetup
? S.current.totp_2fa_success
: S.current.totp_verification_success;
case false:
if (bannedState) {
final state = setup2FAViewModel.state as AuthenticationBanned;
+3 -1
View File
@@ -125,7 +125,9 @@ class WalletEditPage extends BasePage {
}
_onSuccessfulAuth(context);
});
},
conditionToDetermineIfToUse2FA: false,
);
}
void _onSuccessfulAuth(BuildContext context) async {
@@ -55,7 +55,7 @@ class WalletListBodyState extends State<WalletListBody> {
final newWalletImage =
Image.asset('assets/images/new_wallet.png', height: 12, width: 12, color: Colors.white);
final restoreWalletImage = Image.asset('assets/images/restore_wallet.png',
height: 12, width: 12, color: Theme.of(context).primaryTextTheme!.titleLarge!.color!);
height: 12, width: 12, color: Theme.of(context).primaryTextTheme.titleLarge!.color!);
return Container(
padding: EdgeInsets.only(top: 16),
@@ -72,7 +72,7 @@ class WalletListBodyState extends State<WalletListBody> {
itemBuilder: (__, index) {
final wallet = widget.walletListViewModel.wallets[index];
final currentColor = wallet.isCurrent
? Theme.of(context).accentTextTheme!.titleSmall!.decorationColor!
? Theme.of(context).accentTextTheme.titleSmall!.decorationColor!
: Theme.of(context).colorScheme.background;
final row = GestureDetector(
onTap: () => wallet.isCurrent ? null : _loadWallet(wallet),
@@ -131,8 +131,7 @@ class WalletListBodyState extends State<WalletListBody> {
: Row(children: [
Expanded(child: row),
GestureDetector(
onTap: () => Navigator.of(context).pushNamed(
Routes.walletEdit,
onTap: () => Navigator.of(context).pushNamed(Routes.walletEdit,
arguments: [widget.walletListViewModel, wallet]),
child: Container(
padding: EdgeInsets.only(right: 20),
@@ -150,10 +149,7 @@ class WalletListBodyState extends State<WalletListBody> {
child: Icon(
Icons.edit,
size: 14,
color: Theme.of(context)
.textTheme
.headlineMedium!
.color!,
color: Theme.of(context).textTheme.headlineMedium!.color!,
),
),
),
@@ -167,27 +163,59 @@ class WalletListBodyState extends State<WalletListBody> {
bottomSection: Column(children: <Widget>[
PrimaryImageButton(
onPressed: () {
//TODO(David): Find a way to optimize this
if (isSingleCoin) {
Navigator.of(context).pushNamed(Routes.newWallet,
arguments: widget.walletListViewModel.currentWalletType);
if (widget.walletListViewModel.shouldRequireTOTP2FAForCreatingNewWallets) {
widget.authService.authenticateAction(
context,
route: Routes.newWallet,
arguments: widget.walletListViewModel.currentWalletType,
conditionToDetermineIfToUse2FA:
widget.walletListViewModel.shouldRequireTOTP2FAForCreatingNewWallets,
);
} else {
Navigator.of(context).pushNamed(
Routes.newWallet,
arguments: widget.walletListViewModel.currentWalletType,
);
}
} else {
Navigator.of(context).pushNamed(Routes.newWalletType);
if (widget.walletListViewModel.shouldRequireTOTP2FAForCreatingNewWallets) {
widget.authService.authenticateAction(
context,
route: Routes.newWalletType,
conditionToDetermineIfToUse2FA:
widget.walletListViewModel.shouldRequireTOTP2FAForCreatingNewWallets,
);
} else {
Navigator.of(context).pushNamed(Routes.newWalletType);
}
}
},
image: newWalletImage,
text: S.of(context).wallet_list_create_new_wallet,
color: Theme.of(context).accentTextTheme!.bodyLarge!.color!,
color: Theme.of(context).accentTextTheme.bodyLarge!.color!,
textColor: Colors.white,
),
SizedBox(height: 10.0),
PrimaryImageButton(
onPressed: () {
Navigator.of(context).pushNamed(Routes.restoreOptions, arguments: false);
if (widget.walletListViewModel.shouldRequireTOTP2FAForCreatingNewWallets) {
widget.authService.authenticateAction(
context,
route: Routes.restoreOptions,
arguments: false,
conditionToDetermineIfToUse2FA:
widget.walletListViewModel.shouldRequireTOTP2FAForCreatingNewWallets,
);
} else {
Navigator.of(context).pushNamed(Routes.restoreOptions, arguments: false);
}
},
image: restoreWalletImage,
text: S.of(context).wallet_list_restore_wallet,
color: Theme.of(context).accentTextTheme!.bodySmall!.color!,
textColor: Theme.of(context).primaryTextTheme!.titleLarge!.color!)
color: Theme.of(context).accentTextTheme.bodySmall!.color!,
textColor: Theme.of(context).primaryTextTheme.titleLarge!.color!)
])),
);
}
@@ -208,27 +236,31 @@ class WalletListBodyState extends State<WalletListBody> {
}
Future<void> _loadWallet(WalletListItem wallet) async {
await widget.authService.authenticateAction(context,
onAuthSuccess: (isAuthenticatedSuccessfully) async {
if (!isAuthenticatedSuccessfully) {
return;
}
try {
changeProcessText(S.of(context).wallet_list_loading_wallet(wallet.name));
await widget.walletListViewModel.loadWallet(wallet);
await hideProgressText();
// only pop the wallets route in mobile as it will go back to dashboard page
// in desktop platforms the navigation tree is different
if (ResponsiveLayoutUtil.instance.shouldRenderMobileUI()) {
WidgetsBinding.instance.addPostFrameCallback((_) {
Navigator.of(context).pop();
});
await widget.authService.authenticateAction(
context,
onAuthSuccess: (isAuthenticatedSuccessfully) async {
if (!isAuthenticatedSuccessfully) {
return;
}
} catch (e) {
changeProcessText(S.of(context).wallet_list_failed_to_load(wallet.name, e.toString()));
}
});
try {
changeProcessText(S.of(context).wallet_list_loading_wallet(wallet.name));
await widget.walletListViewModel.loadWallet(wallet);
await hideProgressText();
// only pop the wallets route in mobile as it will go back to dashboard page
// in desktop platforms the navigation tree is different
if (ResponsiveLayoutUtil.instance.shouldRenderMobileUI()) {
WidgetsBinding.instance.addPostFrameCallback((_) {
Navigator.of(context).pop();
});
}
} catch (e) {
changeProcessText(S.of(context).wallet_list_failed_to_load(wallet.name, e.toString()));
}
},
conditionToDetermineIfToUse2FA:
widget.walletListViewModel.shouldRequireTOTP2FAForAccessingWallet,
);
}
void changeProcessText(String text) {