authentication_dialog.cc 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. // Copyright 2021 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include "ash/in_session_auth/authentication_dialog.h"
  5. #include <memory>
  6. #include "ash/components/login/auth/auth_performer.h"
  7. #include "ash/components/login/auth/public/cryptohome_error.h"
  8. #include "ash/components/login/auth/public/cryptohome_key_constants.h"
  9. #include "ash/components/login/auth/public/user_context.h"
  10. #include "ash/public/cpp/in_session_auth_dialog_controller.h"
  11. #include "ash/public/cpp/in_session_auth_token_provider.h"
  12. #include "ash/public/cpp/shelf_config.h"
  13. #include "ash/strings/grit/ash_strings.h"
  14. #include "base/bind.h"
  15. #include "base/strings/utf_string_conversions.h"
  16. #include "base/time/time.h"
  17. #include "base/unguessable_token.h"
  18. #include "ui/base/l10n/l10n_util.h"
  19. #include "ui/base/ui_base_types.h"
  20. #include "ui/display/screen.h"
  21. #include "ui/gfx/color_palette.h"
  22. #include "ui/gfx/geometry/insets.h"
  23. #include "ui/views/controls/button/label_button.h"
  24. #include "ui/views/controls/label.h"
  25. #include "ui/views/controls/textfield/textfield.h"
  26. #include "ui/views/layout/flex_layout.h"
  27. #include "ui/views/layout/layout_provider.h"
  28. #include "ui/views/layout/layout_types.h"
  29. #include "ui/views/view_class_properties.h"
  30. #include "ui/views/widget/widget.h"
  31. namespace ash {
  32. namespace {
  33. void AddMargins(views::View* view) {
  34. const auto* layout_provider = views::LayoutProvider::Get();
  35. const int horizontal_spacing = layout_provider->GetDistanceMetric(
  36. views::DISTANCE_RELATED_CONTROL_HORIZONTAL);
  37. const int vertical_spacing = layout_provider->GetDistanceMetric(
  38. views::DISTANCE_RELATED_CONTROL_VERTICAL);
  39. view->SetProperty(views::kMarginsKey,
  40. gfx::Insets::VH(vertical_spacing, horizontal_spacing));
  41. }
  42. void ConfigurePasswordField(views::Textfield* password_field) {
  43. const auto password_field_name =
  44. l10n_util::GetStringUTF16(IDS_ASH_LOGIN_POD_PASSWORD_PLACEHOLDER);
  45. password_field->SetAccessibleName(password_field_name);
  46. password_field->SetReadOnly(false);
  47. password_field->SetTextInputType(ui::TextInputType::TEXT_INPUT_TYPE_PASSWORD);
  48. password_field->SetPlaceholderText(password_field_name);
  49. AddMargins(password_field);
  50. }
  51. void ConfigureInvalidPasswordLabel(views::Label* invalid_password_label) {
  52. invalid_password_label->SetProperty(views::kCrossAxisAlignmentKey,
  53. views::LayoutAlignment::kStart);
  54. invalid_password_label->SetEnabledColor(SK_ColorRED);
  55. AddMargins(invalid_password_label);
  56. }
  57. void CenterWidgetOnPrimaryDisplay(views::Widget* widget) {
  58. auto bounds = display::Screen::GetScreen()->GetPrimaryDisplay().work_area();
  59. bounds.ClampToCenteredSize(widget->GetContentsView()->GetPreferredSize());
  60. widget->SetBounds(bounds);
  61. }
  62. } // namespace
  63. AuthenticationDialog::AuthenticationDialog(
  64. InSessionAuthDialogController::OnAuthComplete on_auth_complete,
  65. InSessionAuthTokenProvider* auth_token_provider,
  66. std::unique_ptr<AuthPerformer> auth_performer,
  67. const AccountId& account_id)
  68. : password_field_(AddChildView(std::make_unique<views::Textfield>())),
  69. invalid_password_label_(AddChildView(std::make_unique<views::Label>())),
  70. on_auth_complete_(std::move(on_auth_complete)),
  71. auth_performer_(std::move(auth_performer)),
  72. auth_token_provider_(auth_token_provider) {
  73. // Dialog setup
  74. set_fixed_width(views::LayoutProvider::Get()->GetDistanceMetric(
  75. views::DistanceMetric::DISTANCE_BUBBLE_PREFERRED_WIDTH));
  76. SetTitle(l10n_util::GetStringUTF16(IDS_ASH_IN_SESSION_AUTH_TITLE));
  77. SetModalType(ui::MODAL_TYPE_SYSTEM);
  78. // Callback setup
  79. SetCancelCallback(base::BindOnce(&AuthenticationDialog::CancelAuthAttempt,
  80. base::Unretained(this)));
  81. SetCloseCallback(base::BindOnce(&AuthenticationDialog::CancelAuthAttempt,
  82. base::Unretained(this)));
  83. SetLayoutManager(std::make_unique<views::FlexLayout>())
  84. ->SetOrientation(views::LayoutOrientation::kVertical)
  85. .SetCollapseMargins(true);
  86. ConfigureChildViews();
  87. // We don't want the user to submit an auth factor to cryptohome before the
  88. // auth session has started. We re-enable the UI in `OnAuthSessionStarted`
  89. SetUIDisabled(true);
  90. auto user_context = std::make_unique<UserContext>();
  91. user_context->SetAccountId(account_id);
  92. auth_performer_->StartAuthSession(
  93. std::move(user_context), /*ephemeral=*/false,
  94. base::BindOnce(&AuthenticationDialog::OnAuthSessionStarted,
  95. weak_factory_.GetWeakPtr()));
  96. }
  97. AuthenticationDialog::~AuthenticationDialog() = default;
  98. void AuthenticationDialog::Show() {
  99. auto* widget = DialogDelegateView::CreateDialogWidget(this,
  100. /*context=*/nullptr,
  101. /*parent=*/nullptr);
  102. CenterWidgetOnPrimaryDisplay(widget);
  103. Init();
  104. widget->Show();
  105. }
  106. void AuthenticationDialog::Init() {
  107. ConfigureOkButton();
  108. password_field_->RequestFocus();
  109. }
  110. void AuthenticationDialog::NotifyResult(bool success,
  111. const base::UnguessableToken& token,
  112. base::TimeDelta timeout) {
  113. if (on_auth_complete_) {
  114. std::move(on_auth_complete_).Run(success, token, timeout);
  115. }
  116. }
  117. void AuthenticationDialog::ConfigureOkButton() {
  118. views::LabelButton* ok_button = GetOkButton();
  119. ok_button->SetText(
  120. l10n_util::GetStringUTF16(IDS_ASH_LOGIN_SUBMIT_BUTTON_ACCESSIBLE_NAME));
  121. ok_button->SetCallback(base::BindRepeating(
  122. &AuthenticationDialog::ValidateAuthFactor, weak_factory_.GetWeakPtr()));
  123. }
  124. void AuthenticationDialog::SetUIDisabled(bool is_disabled) {
  125. SetButtonEnabled(ui::DialogButton::DIALOG_BUTTON_OK, !is_disabled);
  126. SetButtonEnabled(ui::DialogButton::DIALOG_BUTTON_CANCEL, !is_disabled);
  127. password_field_->SetReadOnly(is_disabled);
  128. }
  129. void AuthenticationDialog::ValidateAuthFactor() {
  130. // Clear warning message.
  131. invalid_password_label_->SetText({});
  132. SetUIDisabled(true);
  133. // Create a copy of `user_context_` so that we don't lose it to std::move
  134. // for future auth attempts
  135. auth_performer_->AuthenticateWithPassword(
  136. user_context_->GetAuthFactorsData()
  137. .FindOnlinePasswordKey()
  138. ->label.value(),
  139. base::UTF16ToUTF8(password_field_->GetText()),
  140. std::make_unique<UserContext>(*user_context_),
  141. base::BindOnce(&AuthenticationDialog::OnAuthFactorValidityChecked,
  142. weak_factory_.GetWeakPtr()));
  143. }
  144. void AuthenticationDialog::OnAuthFactorValidityChecked(
  145. std::unique_ptr<UserContext> user_context,
  146. absl::optional<CryptohomeError> cryptohome_error) {
  147. if (cryptohome_error.has_value()) {
  148. if (cryptohome_error.value().error_code ==
  149. user_data_auth::CRYPTOHOME_INVALID_AUTH_SESSION_TOKEN) {
  150. // Auth session expired for some reason, start it again and reattempt
  151. // authentication.
  152. auth_performer_->StartAuthSession(
  153. std::move(user_context), /*ephemeral=*/false,
  154. base::BindOnce(&AuthenticationDialog::OnAuthSessionInvalid,
  155. weak_factory_.GetWeakPtr()));
  156. return;
  157. }
  158. LOG(ERROR) << "An error happened during the attempt to validate"
  159. "the password: "
  160. << cryptohome_error.value().error_code;
  161. password_field_->SetInvalid(true);
  162. password_field_->SelectAll(false);
  163. invalid_password_label_->SetText(
  164. l10n_util::GetStringUTF16(IDS_ASH_LOGIN_ERROR_AUTHENTICATING));
  165. SetUIDisabled(false);
  166. return;
  167. }
  168. is_closing_ = true;
  169. auth_token_provider_->ExchangeForToken(
  170. std::move(user_context),
  171. base::BindOnce(&AuthenticationDialog::NotifyResult,
  172. weak_factory_.GetWeakPtr(), /*success=*/true));
  173. SetUIDisabled(false);
  174. CancelDialog();
  175. return;
  176. }
  177. void AuthenticationDialog::CancelAuthAttempt() {
  178. // If dialog is closing after the submission of a valid auth factor,
  179. // we should not notify any parties, as they would have already been
  180. // notified after `AuthenticationDialog::OnAuthFactorValidityChecked`
  181. if (!is_closing_) {
  182. NotifyResult(/*success=*/false, /*token=*/{}, /*timeout=*/{});
  183. }
  184. }
  185. void AuthenticationDialog::ConfigureChildViews() {
  186. ConfigurePasswordField(password_field_);
  187. ConfigureInvalidPasswordLabel(invalid_password_label_);
  188. }
  189. void AuthenticationDialog::OnAuthSessionInvalid(
  190. bool user_exists,
  191. std::unique_ptr<UserContext> user_context,
  192. absl::optional<CryptohomeError> cryptohome_error) {
  193. OnAuthSessionStarted(user_exists, std::move(user_context), cryptohome_error);
  194. ValidateAuthFactor();
  195. }
  196. void AuthenticationDialog::OnAuthSessionStarted(
  197. bool user_exists,
  198. std::unique_ptr<UserContext> user_context,
  199. absl::optional<CryptohomeError> cryptohome_error) {
  200. if (cryptohome_error.has_value()) {
  201. LOG(ERROR) << "Error starting authsession for in session authentication: "
  202. << cryptohome_error.value().error_code;
  203. CancelAuthAttempt();
  204. } else if (!user_exists) {
  205. LOG(ERROR) << "Attempting to authenticate a user which does not exist. "
  206. "Aborting authentication attempt";
  207. CancelAuthAttempt();
  208. } else {
  209. user_context_ = std::move(user_context);
  210. SetUIDisabled(false);
  211. }
  212. }
  213. } // namespace ash