LocalizedValuesBuilder moved to components/login.
[chromium-blink-merge.git] / chrome / browser / ui / webui / chromeos / login / gaia_screen_handler.cc
blob2f289191ebfaba2f84b08414f9a046a3a0337e11
1 // Copyright 2013 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.
5 #include "chrome/browser/ui/webui/chromeos/login/gaia_screen_handler.h"
7 #include "base/bind.h"
8 #include "base/logging.h"
9 #include "base/metrics/histogram.h"
10 #include "base/prefs/pref_service.h"
11 #include "base/strings/utf_string_conversions.h"
12 #include "base/values.h"
13 #include "chrome/browser/browser_process.h"
14 #include "chrome/browser/browser_shutdown.h"
15 #include "chrome/browser/chromeos/input_method/input_method_util.h"
16 #include "chrome/browser/chromeos/language_preferences.h"
17 #include "chrome/browser/chromeos/login/startup_utils.h"
18 #include "chrome/browser/chromeos/login/ui/user_adding_screen.h"
19 #include "chrome/browser/chromeos/login/users/chrome_user_manager.h"
20 #include "chrome/browser/chromeos/policy/consumer_management_service.h"
21 #include "chrome/browser/chromeos/policy/consumer_management_stage.h"
22 #include "chrome/browser/chromeos/profiles/profile_helper.h"
23 #include "chrome/browser/chromeos/settings/cros_settings.h"
24 #include "chrome/browser/io_thread.h"
25 #include "chrome/browser/lifetime/application_lifetime.h"
26 #include "chrome/browser/ui/webui/chromeos/login/signin_screen_handler.h"
27 #include "chrome/browser/ui/webui/signin/inline_login_ui.h"
28 #include "chrome/common/chrome_version_info.h"
29 #include "chrome/common/pref_names.h"
30 #include "chrome/grit/generated_resources.h"
31 #include "chromeos/chromeos_switches.h"
32 #include "chromeos/settings/cros_settings_names.h"
33 #include "components/login/localized_values_builder.h"
34 #include "components/user_manager/user_manager.h"
35 #include "content/public/browser/browser_thread.h"
36 #include "content/public/browser/render_frame_host.h"
37 #include "google_apis/gaia/gaia_auth_util.h"
38 #include "google_apis/gaia/gaia_switches.h"
39 #include "google_apis/gaia/gaia_urls.h"
40 #include "ui/base/ime/chromeos/input_method_manager.h"
41 #include "ui/base/l10n/l10n_util.h"
43 using content::BrowserThread;
45 namespace chromeos {
47 namespace {
49 const char kJsScreenPath[] = "login.GaiaSigninScreen";
50 const char kAuthIframeParentName[] = "signin-frame";
51 const char kAuthIframeParentOrigin[] =
52 "chrome-extension://mfffpogegjflfpflabcdkioaeobkgjik/";
54 void UpdateAuthParams(base::DictionaryValue* params,
55 bool has_users,
56 bool is_enrolling_consumer_management) {
57 CrosSettings* cros_settings = CrosSettings::Get();
58 bool allow_new_user = true;
59 cros_settings->GetBoolean(kAccountsPrefAllowNewUser, &allow_new_user);
60 bool allow_guest = true;
61 cros_settings->GetBoolean(kAccountsPrefAllowGuest, &allow_guest);
62 // Account creation depends on Guest sign-in (http://crosbug.com/24570).
63 params->SetBoolean("createAccount", allow_new_user && allow_guest);
64 params->SetBoolean("guestSignin", allow_guest);
66 // Allow supervised user creation only if:
67 // 1. Enterprise managed device > is allowed by policy.
68 // 2. Consumer device > owner exists.
69 // 3. New users are allowed by owner.
70 // 4. Supervised users are allowed by owner.
71 bool supervised_users_allowed =
72 user_manager::UserManager::Get()->AreSupervisedUsersAllowed();
73 bool supervised_users_can_create = true;
74 int message_id = -1;
75 if (!has_users) {
76 supervised_users_can_create = false;
77 message_id = IDS_CREATE_SUPERVISED_USER_NO_MANAGER_TEXT;
79 if (!allow_new_user || !supervised_users_allowed) {
80 supervised_users_can_create = false;
81 message_id = IDS_CREATE_SUPERVISED_USER_CREATION_RESTRICTED_TEXT;
83 if (supervised_users_can_create &&
84 ChromeUserManager::Get()
85 ->GetUsersAllowedForSupervisedUsersCreation()
86 .empty()) {
87 supervised_users_can_create = false;
88 message_id = IDS_CREATE_SUPERVISED_USER_NO_MANAGER_EXCEPT_KIDS_TEXT;
91 params->SetBoolean("supervisedUsersEnabled", supervised_users_allowed);
92 params->SetBoolean("supervisedUsersCanCreate", supervised_users_can_create);
93 if (!supervised_users_can_create) {
94 params->SetString("supervisedUsersRestrictionReason",
95 l10n_util::GetStringUTF16(message_id));
98 // Now check whether we're in multi-profiles user adding scenario and
99 // disable GAIA right panel features if that's the case.
100 // For consumer management enrollment, we also hide all right panel components
101 // and show only an enrollment message.
102 if (UserAddingScreen::Get()->IsRunning() ||
103 is_enrolling_consumer_management) {
104 params->SetBoolean("createAccount", false);
105 params->SetBoolean("guestSignin", false);
106 params->SetBoolean("supervisedUsersEnabled", false);
110 void RecordSAMLScrapingVerificationResultInHistogram(bool success) {
111 UMA_HISTOGRAM_BOOLEAN("ChromeOS.SAML.Scraping.VerificationResult", success);
114 // The Task posted to PostTaskAndReply in StartClearingDnsCache on the IO
115 // thread.
116 void ClearDnsCache(IOThread* io_thread) {
117 DCHECK_CURRENTLY_ON(BrowserThread::IO);
118 if (browser_shutdown::IsTryingToQuit())
119 return;
121 io_thread->ClearHostCache();
124 void PushFrontIMIfNotExists(const std::string& input_method,
125 std::vector<std::string>* input_methods) {
126 if (input_method.empty())
127 return;
129 if (std::find(input_methods->begin(), input_methods->end(), input_method) ==
130 input_methods->end())
131 input_methods->insert(input_methods->begin(), input_method);
134 } // namespace
136 GaiaContext::GaiaContext()
137 : force_reload(false),
138 is_local(false),
139 password_changed(false),
140 show_users(false),
141 use_offline(false),
142 has_users(false) {}
144 GaiaScreenHandler::GaiaScreenHandler(
145 CoreOobeActor* core_oobe_actor,
146 const scoped_refptr<NetworkStateInformer>& network_state_informer,
147 policy::ConsumerManagementService* consumer_management)
148 : BaseScreenHandler(kJsScreenPath),
149 frame_state_(FRAME_STATE_UNKNOWN),
150 frame_error_(net::OK),
151 network_state_informer_(network_state_informer),
152 consumer_management_(consumer_management),
153 core_oobe_actor_(core_oobe_actor),
154 dns_cleared_(false),
155 dns_clear_task_running_(false),
156 cookies_cleared_(false),
157 show_when_dns_and_cookies_cleared_(false),
158 focus_stolen_(false),
159 gaia_silent_load_(false),
160 using_saml_api_(false),
161 is_enrolling_consumer_management_(false),
162 test_expects_complete_login_(false),
163 embedded_signin_enabled_by_shortcut_(false),
164 signin_screen_handler_(NULL),
165 weak_factory_(this) {
166 DCHECK(network_state_informer_.get());
169 GaiaScreenHandler::~GaiaScreenHandler() {
172 void GaiaScreenHandler::LoadGaia(const GaiaContext& context) {
173 if (!auth_extension_) {
174 Profile* signin_profile = ProfileHelper::GetSigninProfile();
175 auth_extension_.reset(new ScopedGaiaAuthExtension(signin_profile));
178 base::DictionaryValue params;
179 const bool is_enrolling_consumer_management =
180 context.is_enrolling_consumer_management;
182 params.SetBoolean("forceReload", context.force_reload);
183 params.SetBoolean("isLocal", context.is_local);
184 params.SetBoolean("passwordChanged", context.password_changed);
185 params.SetBoolean("isShowUsers", context.show_users);
186 params.SetBoolean("useOffline", context.use_offline);
187 params.SetString("email", context.email);
188 params.SetBoolean("isEnrollingConsumerManagement",
189 is_enrolling_consumer_management);
191 UpdateAuthParams(&params,
192 context.has_users,
193 is_enrolling_consumer_management);
195 if (!context.use_offline) {
196 const std::string app_locale = g_browser_process->GetApplicationLocale();
197 if (!app_locale.empty())
198 params.SetString("hl", app_locale);
199 } else {
200 base::DictionaryValue* localized_strings = new base::DictionaryValue();
201 localized_strings->SetString(
202 "stringEmail", l10n_util::GetStringUTF16(IDS_LOGIN_OFFLINE_EMAIL));
203 localized_strings->SetString(
204 "stringPassword",
205 l10n_util::GetStringUTF16(IDS_LOGIN_OFFLINE_PASSWORD));
206 localized_strings->SetString(
207 "stringSignIn", l10n_util::GetStringUTF16(IDS_LOGIN_OFFLINE_SIGNIN));
208 localized_strings->SetString(
209 "stringEmptyEmail",
210 l10n_util::GetStringUTF16(IDS_LOGIN_OFFLINE_EMPTY_EMAIL));
211 localized_strings->SetString(
212 "stringEmptyPassword",
213 l10n_util::GetStringUTF16(IDS_LOGIN_OFFLINE_EMPTY_PASSWORD));
214 localized_strings->SetString(
215 "stringError", l10n_util::GetStringUTF16(IDS_LOGIN_OFFLINE_ERROR));
216 params.Set("localizedStrings", localized_strings);
219 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
221 const GURL gaia_url =
222 command_line->HasSwitch(::switches::kGaiaUrl)
223 ? GURL(command_line->GetSwitchValueASCII(::switches::kGaiaUrl))
224 : GaiaUrls::GetInstance()->gaia_url();
225 params.SetString("gaiaUrl", gaia_url.spec());
227 if (command_line->HasSwitch(switches::kGaiaEndpointChromeOS)) {
228 params.SetString("gaiaEndpoint", command_line->GetSwitchValueASCII(
229 switches::kGaiaEndpointChromeOS));
231 if (context.embedded_signin_enabled) {
232 params.SetBoolean("useEmbedded", true);
233 // We set 'constrained' here to switch troubleshooting page on embedded
234 // signin to full tab.
235 params.SetInteger("constrained", 1);
238 frame_state_ = FRAME_STATE_LOADING;
239 CallJS("loadAuthExtension", params);
242 void GaiaScreenHandler::UpdateGaia(const GaiaContext& context) {
243 base::DictionaryValue params;
244 UpdateAuthParams(&params, context.has_users,
245 context.is_enrolling_consumer_management);
246 CallJS("updateAuthExtension", params);
249 void GaiaScreenHandler::ReloadGaia(bool force_reload) {
250 if (frame_state_ == FRAME_STATE_LOADING && !force_reload) {
251 VLOG(1) << "Skipping reloading of Gaia since gaia is loading.";
252 return;
254 NetworkStateInformer::State state = network_state_informer_->state();
255 if (state != NetworkStateInformer::ONLINE) {
256 VLOG(1) << "Skipping reloading of Gaia since network state="
257 << NetworkStateInformer::StatusString(state);
258 return;
260 VLOG(1) << "Reloading Gaia.";
261 frame_state_ = FRAME_STATE_LOADING;
262 CallJS("doReload");
265 void GaiaScreenHandler::SwitchToEmbeddedSignin() {
266 // This feature should not be working on Stable,Beta images.
267 chrome::VersionInfo::Channel channel = chrome::VersionInfo::GetChannel();
268 if (channel == chrome::VersionInfo::CHANNEL_STABLE ||
269 channel == chrome::VersionInfo::CHANNEL_BETA) {
270 return;
272 embedded_signin_enabled_by_shortcut_ = true;
273 LoadAuthExtension(
274 true /* force */, true /* silent_load */, false /* offline */);
277 void GaiaScreenHandler::CancelEmbeddedSignin() {
278 embedded_signin_enabled_by_shortcut_ = false;
281 void GaiaScreenHandler::DeclareLocalizedValues(
282 ::login::LocalizedValuesBuilder* builder) {
283 builder->Add("signinScreenTitle", IDS_SIGNIN_SCREEN_TITLE);
284 builder->Add("signinScreenPasswordChanged",
285 IDS_SIGNIN_SCREEN_PASSWORD_CHANGED);
286 builder->Add("createAccount", IDS_CREATE_ACCOUNT_HTML);
287 builder->Add("guestSignin", IDS_BROWSE_WITHOUT_SIGNING_IN_HTML);
288 builder->Add("createSupervisedUser",
289 IDS_CREATE_SUPERVISED_USER_HTML);
290 builder->Add("createSupervisedUserFeatureName",
291 IDS_CREATE_SUPERVISED_USER_FEATURE_NAME);
292 builder->Add("consumerManagementEnrollmentSigninMessage",
293 IDS_LOGIN_CONSUMER_MANAGEMENT_ENROLLMENT);
295 // Strings used by the SAML fatal error dialog.
296 builder->Add("fatalErrorMessageNoAccountDetails",
297 IDS_LOGIN_FATAL_ERROR_NO_ACCOUNT_DETAILS);
298 builder->Add("fatalErrorMessageNoPassword",
299 IDS_LOGIN_FATAL_ERROR_NO_PASSWORD);
300 builder->Add("fatalErrorMessageVerificationFailed",
301 IDS_LOGIN_FATAL_ERROR_PASSWORD_VERIFICATION);
302 builder->Add("fatalErrorMessageInsecureURL",
303 IDS_LOGIN_FATAL_ERROR_TEXT_INSECURE_URL);
304 builder->Add("fatalErrorInstructions", IDS_LOGIN_FATAL_ERROR_INSTRUCTIONS);
305 builder->Add("fatalErrorDismissButton", IDS_OK);
308 void GaiaScreenHandler::GetAdditionalParameters(base::DictionaryValue* dict) {
309 dict->SetBoolean("isWebviewSignin", StartupUtils::IsWebviewSigninEnabled());
312 void GaiaScreenHandler::Initialize() {
315 void GaiaScreenHandler::RegisterMessages() {
316 AddCallback("frameLoadingCompleted",
317 &GaiaScreenHandler::HandleFrameLoadingCompleted);
318 AddCallback("completeLogin", &GaiaScreenHandler::HandleCompleteLogin);
319 AddCallback("completeAuthentication",
320 &GaiaScreenHandler::HandleCompleteAuthentication);
321 AddCallback("usingSAMLAPI", &GaiaScreenHandler::HandleUsingSAMLAPI);
322 AddCallback("scrapedPasswordCount",
323 &GaiaScreenHandler::HandleScrapedPasswordCount);
324 AddCallback("scrapedPasswordVerificationFailed",
325 &GaiaScreenHandler::HandleScrapedPasswordVerificationFailed);
326 AddCallback("loginWebuiReady", &GaiaScreenHandler::HandleGaiaUIReady);
327 AddCallback("switchToFullTab", &GaiaScreenHandler::HandleSwitchToFullTab);
328 AddCallback("toggleWebviewSignin",
329 &GaiaScreenHandler::HandleToggleWebviewSignin);
332 void GaiaScreenHandler::HandleFrameLoadingCompleted(int status) {
333 const net::Error frame_error = static_cast<net::Error>(-status);
334 if (frame_error == net::ERR_ABORTED) {
335 LOG(WARNING) << "Ignoring Gaia frame error: " << frame_error;
336 return;
338 frame_error_ = frame_error;
339 if (frame_error == net::OK) {
340 VLOG(1) << "Gaia is loaded";
341 frame_state_ = FRAME_STATE_LOADED;
342 } else {
343 LOG(WARNING) << "Gaia frame error: " << frame_error_;
344 frame_state_ = FRAME_STATE_ERROR;
347 if (network_state_informer_->state() != NetworkStateInformer::ONLINE)
348 return;
349 if (frame_state_ == FRAME_STATE_LOADED)
350 UpdateState(ErrorScreenActor::ERROR_REASON_UPDATE);
351 else if (frame_state_ == FRAME_STATE_ERROR)
352 UpdateState(ErrorScreenActor::ERROR_REASON_FRAME_ERROR);
355 void GaiaScreenHandler::HandleCompleteAuthentication(
356 const std::string& gaia_id,
357 const std::string& email,
358 const std::string& password,
359 const std::string& auth_code) {
360 if (!Delegate())
361 return;
363 DCHECK(!email.empty());
364 DCHECK(!gaia_id.empty());
365 Delegate()->SetDisplayEmail(gaia::SanitizeEmail(email));
366 UserContext user_context(email);
367 user_context.SetGaiaID(gaia_id);
368 user_context.SetKey(Key(password));
369 user_context.SetAuthCode(auth_code);
370 Delegate()->CompleteLogin(user_context);
373 void GaiaScreenHandler::HandleCompleteLogin(const std::string& gaia_id,
374 const std::string& typed_email,
375 const std::string& password,
376 bool using_saml) {
377 if (!is_enrolling_consumer_management_) {
378 DoCompleteLogin(gaia_id, typed_email, password, using_saml);
379 return;
382 // Consumer management enrollment is in progress.
383 const std::string owner_email =
384 user_manager::UserManager::Get()->GetOwnerEmail();
385 if (typed_email != owner_email) {
386 // Show Gaia sign-in screen again, since we only allow the owner to sign
387 // in.
388 populated_email_ = owner_email;
389 ShowGaiaAsync(is_enrolling_consumer_management_);
390 return;
393 CHECK(consumer_management_);
394 consumer_management_->SetOwner(owner_email,
395 base::Bind(&GaiaScreenHandler::OnSetOwnerDone,
396 weak_factory_.GetWeakPtr(),
397 gaia_id,
398 typed_email,
399 password,
400 using_saml));
403 void GaiaScreenHandler::HandleUsingSAMLAPI() {
404 SetSAMLPrincipalsAPIUsed(true);
407 void GaiaScreenHandler::HandleScrapedPasswordCount(int password_count) {
408 SetSAMLPrincipalsAPIUsed(false);
409 // Use a histogram that has 11 buckets, one for each of the values in [0, 9]
410 // and an overflow bucket at the end.
411 UMA_HISTOGRAM_ENUMERATION(
412 "ChromeOS.SAML.Scraping.PasswordCount", std::min(password_count, 10), 11);
413 if (password_count == 0)
414 HandleScrapedPasswordVerificationFailed();
417 void GaiaScreenHandler::HandleScrapedPasswordVerificationFailed() {
418 RecordSAMLScrapingVerificationResultInHistogram(false);
421 void GaiaScreenHandler::HandleSwitchToFullTab() {
422 CallJS("switchToFullTab");
425 void GaiaScreenHandler::HandleToggleWebviewSignin() {
426 if (StartupUtils::EnableWebviewSignin(
427 !StartupUtils::IsWebviewSigninEnabled())) {
428 chrome::AttemptRestart();
432 void GaiaScreenHandler::HandleGaiaUIReady() {
433 if (focus_stolen_) {
434 // Set focus to the Gaia page.
435 // TODO(altimofeev): temporary solution, until focus parameters are
436 // implemented on the Gaia side.
437 // Do this only once. Any subsequent call would relod GAIA frame.
438 focus_stolen_ = false;
439 const char code[] =
440 "if (typeof gWindowOnLoad != 'undefined') gWindowOnLoad();";
441 content::RenderFrameHost* frame = InlineLoginUI::GetAuthIframe(
442 web_ui()->GetWebContents(),
443 GURL(kAuthIframeParentOrigin),
444 kAuthIframeParentName);
445 frame->ExecuteJavaScript(base::ASCIIToUTF16(code));
447 if (gaia_silent_load_) {
448 focus_stolen_ = true;
449 // Prevent focus stealing by the Gaia page.
450 // TODO(altimofeev): temporary solution, until focus parameters are
451 // implemented on the Gaia side.
452 const char code[] =
453 "var gWindowOnLoad = window.onload; "
454 "window.onload=function() {};";
455 content::RenderFrameHost* frame = InlineLoginUI::GetAuthIframe(
456 web_ui()->GetWebContents(),
457 GURL(kAuthIframeParentOrigin),
458 kAuthIframeParentName);
459 frame->ExecuteJavaScript(base::ASCIIToUTF16(code));
461 // As we could miss and window.onload could already be called, restore
462 // focus to current pod (see crbug/175243).
463 DCHECK(signin_screen_handler_);
464 signin_screen_handler_->RefocusCurrentPod();
466 HandleFrameLoadingCompleted(0);
468 if (test_expects_complete_login_)
469 SubmitLoginFormForTest();
472 void GaiaScreenHandler::OnSetOwnerDone(const std::string& gaia_id,
473 const std::string& typed_email,
474 const std::string& password,
475 bool using_saml,
476 bool success) {
477 CHECK(consumer_management_);
478 if (success) {
479 consumer_management_->SetStage(
480 policy::ConsumerManagementStage::EnrollmentOwnerStored());
481 } else {
482 LOG(ERROR) << "Failed to write owner e-mail to boot lockbox.";
483 consumer_management_->SetStage(
484 policy::ConsumerManagementStage::EnrollmentBootLockboxFailed());
485 // We should continue logging in the user, as there's not much we can do
486 // here.
488 DoCompleteLogin(gaia_id, typed_email, password, using_saml);
491 void GaiaScreenHandler::DoCompleteLogin(const std::string& gaia_id,
492 const std::string& typed_email,
493 const std::string& password,
494 bool using_saml) {
495 if (!Delegate())
496 return;
498 if (using_saml && !using_saml_api_)
499 RecordSAMLScrapingVerificationResultInHistogram(true);
501 DCHECK(!typed_email.empty());
502 DCHECK(!gaia_id.empty());
503 const std::string sanitized_email = gaia::SanitizeEmail(typed_email);
504 Delegate()->SetDisplayEmail(sanitized_email);
505 UserContext user_context(sanitized_email);
506 user_context.SetGaiaID(gaia_id);
507 user_context.SetKey(Key(password));
508 user_context.SetAuthFlow(using_saml
509 ? UserContext::AUTH_FLOW_GAIA_WITH_SAML
510 : UserContext::AUTH_FLOW_GAIA_WITHOUT_SAML);
511 Delegate()->CompleteLogin(user_context);
513 if (test_expects_complete_login_) {
514 VLOG(2) << "Complete test login for " << typed_email
515 << ", requested=" << test_user_;
517 test_expects_complete_login_ = false;
518 test_user_.clear();
519 test_pass_.clear();
523 void GaiaScreenHandler::PopulateEmail(const std::string& user_id) {
524 populated_email_ = user_id;
527 void GaiaScreenHandler::PasswordChangedFor(const std::string& user_id) {
528 password_changed_for_.insert(user_id);
531 void GaiaScreenHandler::StartClearingDnsCache() {
532 if (dns_clear_task_running_ || !g_browser_process->io_thread())
533 return;
535 dns_cleared_ = false;
536 BrowserThread::PostTaskAndReply(
537 BrowserThread::IO,
538 FROM_HERE,
539 base::Bind(&ClearDnsCache, g_browser_process->io_thread()),
540 base::Bind(&GaiaScreenHandler::OnDnsCleared, weak_factory_.GetWeakPtr()));
541 dns_clear_task_running_ = true;
544 void GaiaScreenHandler::OnDnsCleared() {
545 DCHECK_CURRENTLY_ON(BrowserThread::UI);
546 dns_clear_task_running_ = false;
547 dns_cleared_ = true;
548 ShowGaiaScreenIfReady();
551 void GaiaScreenHandler::StartClearingCookies(
552 const base::Closure& on_clear_callback) {
553 cookies_cleared_ = false;
554 ProfileHelper* profile_helper = ProfileHelper::Get();
555 LOG_ASSERT(Profile::FromWebUI(web_ui()) ==
556 profile_helper->GetSigninProfile());
557 profile_helper->ClearSigninProfile(
558 base::Bind(&GaiaScreenHandler::OnCookiesCleared,
559 weak_factory_.GetWeakPtr(),
560 on_clear_callback));
563 void GaiaScreenHandler::OnCookiesCleared(
564 const base::Closure& on_clear_callback) {
565 DCHECK_CURRENTLY_ON(BrowserThread::UI);
566 cookies_cleared_ = true;
567 on_clear_callback.Run();
570 void GaiaScreenHandler::ShowSigninScreenForCreds(const std::string& username,
571 const std::string& password) {
572 VLOG(2) << "ShowSigninScreenForCreds for user " << username
573 << ", frame_state=" << frame_state();
575 test_user_ = username;
576 test_pass_ = password;
577 test_expects_complete_login_ = true;
579 // Submit login form for test if gaia is ready. If gaia is loading, login
580 // will be attempted in HandleLoginWebuiReady after gaia is ready. Otherwise,
581 // reload gaia then follow the loading case.
582 if (frame_state() == GaiaScreenHandler::FRAME_STATE_LOADED) {
583 SubmitLoginFormForTest();
584 } else if (frame_state() != GaiaScreenHandler::FRAME_STATE_LOADING) {
585 DCHECK(signin_screen_handler_);
586 signin_screen_handler_->OnShowAddUser();
590 void GaiaScreenHandler::SubmitLoginFormForTest() {
591 VLOG(2) << "Submit login form for test, user=" << test_user_;
593 std::string code;
594 code += "document.getElementById('Email').value = '" + test_user_ + "';";
595 code += "document.getElementById('Passwd').value = '" + test_pass_ + "';";
596 code += "document.getElementById('signIn').click();";
598 content::RenderFrameHost* frame = InlineLoginUI::GetAuthIframe(
599 web_ui()->GetWebContents(),
600 GURL(kAuthIframeParentOrigin),
601 kAuthIframeParentName);
602 frame->ExecuteJavaScript(base::ASCIIToUTF16(code));
604 // Test properties are cleared in HandleCompleteLogin because the form
605 // submission might fail and login will not be attempted after reloading
606 // if they are cleared here.
609 void GaiaScreenHandler::SetSAMLPrincipalsAPIUsed(bool api_used) {
610 using_saml_api_ = api_used;
611 UMA_HISTOGRAM_BOOLEAN("ChromeOS.SAML.APIUsed", api_used);
614 void GaiaScreenHandler::ShowGaiaAsync(bool is_enrolling_consumer_management) {
615 is_enrolling_consumer_management_ = is_enrolling_consumer_management;
616 show_when_dns_and_cookies_cleared_ = true;
617 if (gaia_silent_load_ && populated_email_.empty()) {
618 dns_cleared_ = true;
619 cookies_cleared_ = true;
620 ShowGaiaScreenIfReady();
621 } else {
622 StartClearingDnsCache();
623 StartClearingCookies(base::Bind(&GaiaScreenHandler::ShowGaiaScreenIfReady,
624 weak_factory_.GetWeakPtr()));
628 void GaiaScreenHandler::CancelShowGaiaAsync() {
629 show_when_dns_and_cookies_cleared_ = false;
632 void GaiaScreenHandler::ShowGaiaScreenIfReady() {
633 if (!dns_cleared_ ||
634 !cookies_cleared_ ||
635 !show_when_dns_and_cookies_cleared_ ||
636 !Delegate()) {
637 return;
640 std::string active_network_path = network_state_informer_->network_path();
641 if (gaia_silent_load_ &&
642 (network_state_informer_->state() != NetworkStateInformer::ONLINE ||
643 gaia_silent_load_network_ != active_network_path)) {
644 // Network has changed. Force Gaia reload.
645 gaia_silent_load_ = false;
646 // Gaia page will be realoded, so focus isn't stolen anymore.
647 focus_stolen_ = false;
650 // Note that LoadAuthExtension clears |populated_email_|.
651 if (populated_email_.empty())
652 Delegate()->LoadSigninWallpaper();
653 else
654 Delegate()->LoadWallpaper(populated_email_);
656 input_method::InputMethodManager* imm =
657 input_method::InputMethodManager::Get();
659 scoped_refptr<input_method::InputMethodManager::State> gaia_ime_state =
660 imm->GetActiveIMEState()->Clone();
661 imm->SetState(gaia_ime_state);
663 // Set Least Recently Used input method for the user.
664 if (!populated_email_.empty()) {
665 SigninScreenHandler::SetUserInputMethod(populated_email_,
666 gaia_ime_state.get());
667 } else {
668 std::vector<std::string> input_methods =
669 imm->GetInputMethodUtil()->GetHardwareLoginInputMethodIds();
670 const std::string owner_im = SigninScreenHandler::GetUserLRUInputMethod(
671 user_manager::UserManager::Get()->GetOwnerEmail());
672 const std::string system_im = g_browser_process->local_state()->GetString(
673 language_prefs::kPreferredKeyboardLayout);
675 PushFrontIMIfNotExists(owner_im, &input_methods);
676 PushFrontIMIfNotExists(system_im, &input_methods);
678 gaia_ime_state->EnableLoginLayouts(
679 g_browser_process->GetApplicationLocale(), input_methods);
681 if (!system_im.empty()) {
682 gaia_ime_state->ChangeInputMethod(system_im, false /* show_message */);
683 } else if (!owner_im.empty()) {
684 gaia_ime_state->ChangeInputMethod(owner_im, false /* show_message */);
688 LoadAuthExtension(!gaia_silent_load_, false, false);
689 signin_screen_handler_->UpdateUIState(
690 SigninScreenHandler::UI_STATE_GAIA_SIGNIN, NULL);
692 if (gaia_silent_load_) {
693 // The variable is assigned to false because silently loaded Gaia page was
694 // used.
695 gaia_silent_load_ = false;
696 if (focus_stolen_)
697 HandleGaiaUIReady();
699 signin_screen_handler_->UpdateState(ErrorScreenActor::ERROR_REASON_UPDATE);
701 if (core_oobe_actor_) {
702 PrefService* prefs = g_browser_process->local_state();
703 if (prefs->GetBoolean(prefs::kFactoryResetRequested)) {
704 core_oobe_actor_->ShowDeviceResetScreen();
705 } else if (prefs->GetBoolean(prefs::kDebuggingFeaturesRequested)) {
706 core_oobe_actor_->ShowEnableDebuggingScreen();
711 void GaiaScreenHandler::MaybePreloadAuthExtension() {
712 VLOG(1) << "MaybePreloadAuthExtension() call.";
714 // If cookies clearing was initiated or |dns_clear_task_running_| then auth
715 // extension showing has already been initiated and preloading is senseless.
716 if (signin_screen_handler_->ShouldLoadGaia() &&
717 !gaia_silent_load_ &&
718 !cookies_cleared_ &&
719 !dns_clear_task_running_ &&
720 network_state_informer_->state() == NetworkStateInformer::ONLINE) {
721 gaia_silent_load_ = true;
722 gaia_silent_load_network_ = network_state_informer_->network_path();
723 LoadAuthExtension(true, true, false);
727 void GaiaScreenHandler::LoadAuthExtension(bool force,
728 bool silent_load,
729 bool offline) {
730 GaiaContext context;
731 context.force_reload = force;
732 context.is_local = offline;
733 context.password_changed = !populated_email_.empty() &&
734 password_changed_for_.count(populated_email_);
735 context.use_offline = offline;
736 context.email = populated_email_;
737 context.is_enrolling_consumer_management = is_enrolling_consumer_management_;
738 if (Delegate()) {
739 context.show_users = Delegate()->IsShowUsers();
740 context.has_users = !Delegate()->GetUsers().empty();
743 context.embedded_signin_enabled =
744 base::CommandLine::ForCurrentProcess()->HasSwitch(
745 chromeos::switches::kEnableEmbeddedSignin) ||
746 embedded_signin_enabled_by_shortcut_;
748 populated_email_.clear();
750 LoadGaia(context);
753 void GaiaScreenHandler::UpdateState(ErrorScreenActor::ErrorReason reason) {
754 if (signin_screen_handler_)
755 signin_screen_handler_->UpdateState(reason);
758 SigninScreenHandlerDelegate* GaiaScreenHandler::Delegate() {
759 DCHECK(signin_screen_handler_);
760 return signin_screen_handler_->delegate_;
763 void GaiaScreenHandler::SetSigninScreenHandler(SigninScreenHandler* handler) {
764 signin_screen_handler_ = handler;
766 } // namespace chromeos