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/signin/inline_login_handler_impl.h"
10 #include "base/strings/string_number_conversions.h"
11 #include "base/strings/string_util.h"
12 #include "base/strings/utf_string_conversions.h"
13 #include "base/values.h"
14 #include "chrome/browser/profiles/profile.h"
15 #include "chrome/browser/signin/about_signin_internals_factory.h"
16 #include "chrome/browser/signin/profile_oauth2_token_service_factory.h"
17 #include "chrome/browser/signin/signin_manager_factory.h"
18 #include "chrome/browser/sync/profile_sync_service.h"
19 #include "chrome/browser/sync/profile_sync_service_factory.h"
20 #include "chrome/browser/ui/browser_finder.h"
21 #include "chrome/browser/ui/browser_window.h"
22 #include "chrome/browser/ui/sync/one_click_signin_helper.h"
23 #include "chrome/browser/ui/sync/one_click_signin_histogram.h"
24 #include "chrome/browser/ui/tabs/tab_strip_model.h"
25 #include "chrome/common/url_constants.h"
26 #include "components/signin/core/browser/about_signin_internals.h"
27 #include "components/signin/core/browser/profile_oauth2_token_service.h"
28 #include "components/signin/core/browser/signin_error_controller.h"
29 #include "components/signin/core/browser/signin_oauth_helper.h"
30 #include "content/public/browser/storage_partition.h"
31 #include "content/public/browser/web_ui.h"
32 #include "google_apis/gaia/gaia_auth_fetcher.h"
33 #include "google_apis/gaia/gaia_auth_util.h"
34 #include "google_apis/gaia/gaia_constants.h"
35 #include "google_apis/gaia/gaia_urls.h"
36 #include "net/base/url_util.h"
40 class InlineSigninHelper : public SigninOAuthHelper,
41 public SigninOAuthHelper::Consumer {
44 base::WeakPtr<InlineLoginHandlerImpl> handler,
45 net::URLRequestContextGetter* getter,
47 const GURL& current_url,
48 const std::string& email,
49 const std::string& password,
50 const std::string& session_index,
51 bool choose_what_to_sync);
54 // Overriden from SigninOAuthHelper::Consumer.
55 virtual void OnSigninOAuthInformationAvailable(
56 const std::string& email,
57 const std::string& display_email,
58 const std::string& refresh_token) OVERRIDE;
59 virtual void OnSigninOAuthInformationFailure(
60 const GoogleServiceAuthError& error) OVERRIDE;
62 base::WeakPtr<InlineLoginHandlerImpl> handler_;
66 std::string password_;
67 std::string session_index_;
68 bool choose_what_to_sync_;
70 DISALLOW_COPY_AND_ASSIGN(InlineSigninHelper);
73 InlineSigninHelper::InlineSigninHelper(
74 base::WeakPtr<InlineLoginHandlerImpl> handler,
75 net::URLRequestContextGetter* getter,
77 const GURL& current_url,
78 const std::string& email,
79 const std::string& password,
80 const std::string& session_index,
81 bool choose_what_to_sync)
82 : SigninOAuthHelper(getter, session_index, this),
85 current_url_(current_url),
88 session_index_(session_index),
89 choose_what_to_sync_(choose_what_to_sync) {
91 DCHECK(!email_.empty());
92 DCHECK(!session_index_.empty());
95 void InlineSigninHelper::OnSigninOAuthInformationAvailable(
96 const std::string& email,
97 const std::string& display_email,
98 const std::string& refresh_token) {
99 content::WebContents* contents = NULL;
100 Browser* browser = NULL;
102 contents = handler_->web_ui()->GetWebContents();
103 browser = handler_->GetDesktopBrowser();
106 AboutSigninInternals* about_signin_internals =
107 AboutSigninInternalsFactory::GetForProfile(profile_);
108 about_signin_internals->OnRefreshTokenReceived("Successful");
110 signin::Source source = signin::GetSourceForPromoURL(current_url_);
111 if (source == signin::SOURCE_AVATAR_BUBBLE_ADD_ACCOUNT ||
112 source == signin::SOURCE_REAUTH) {
113 ProfileOAuth2TokenServiceFactory::GetForProfile(profile_)->
114 UpdateCredentials(email, refresh_token);
116 if (signin::IsAutoCloseEnabledInURL(current_url_)) {
117 // Close the gaia sign in tab via a task to make sure we aren't in the
118 // middle of any webui handler code.
119 base::MessageLoop::current()->PostTask(
121 base::Bind(&InlineLoginHandlerImpl::CloseTab,
123 signin::ShouldShowAccountManagement(current_url_)));
126 ProfileSyncService* sync_service =
127 ProfileSyncServiceFactory::GetForProfile(profile_);
128 SigninErrorController* error_controller =
129 ProfileOAuth2TokenServiceFactory::GetForProfile(profile_)->
130 signin_error_controller();
131 OneClickSigninSyncStarter::StartSyncMode start_mode =
132 source == signin::SOURCE_SETTINGS || choose_what_to_sync_ ?
133 (error_controller->HasError() &&
134 sync_service && sync_service->HasSyncSetupCompleted()) ?
135 OneClickSigninSyncStarter::SHOW_SETTINGS_WITHOUT_CONFIGURE :
136 OneClickSigninSyncStarter::CONFIGURE_SYNC_FIRST :
137 OneClickSigninSyncStarter::SYNC_WITH_DEFAULT_SETTINGS;
138 OneClickSigninSyncStarter::ConfirmationRequired confirmation_required =
139 source == signin::SOURCE_SETTINGS ||
140 source == signin::SOURCE_WEBSTORE_INSTALL ||
141 choose_what_to_sync_ ?
142 OneClickSigninSyncStarter::NO_CONFIRMATION :
143 OneClickSigninSyncStarter::CONFIRM_AFTER_SIGNIN;
146 !OneClickSigninHelper::HandleCrossAccountError(
148 email, password_, refresh_token,
149 OneClickSigninHelper::AUTO_ACCEPT_EXPLICIT,
151 base::Bind(&InlineLoginHandlerImpl::SyncStarterCallback,
154 // Call OneClickSigninSyncStarter to exchange oauth code for tokens.
155 // OneClickSigninSyncStarter will delete itself once the job is done.
156 new OneClickSigninSyncStarter(
158 email, password_, refresh_token,
161 confirmation_required,
162 signin::GetNextPageURLForPromoURL(current_url_),
163 base::Bind(&InlineLoginHandlerImpl::SyncStarterCallback, handler_));
167 base::MessageLoop::current()->DeleteSoon(FROM_HERE, this);
170 void InlineSigninHelper::OnSigninOAuthInformationFailure(
171 const GoogleServiceAuthError& error) {
173 handler_->HandleLoginError(error.ToString());
175 AboutSigninInternals* about_signin_internals =
176 AboutSigninInternalsFactory::GetForProfile(profile_);
177 about_signin_internals->OnRefreshTokenReceived("Failure");
179 base::MessageLoop::current()->DeleteSoon(FROM_HERE, this);
184 InlineLoginHandlerImpl::InlineLoginHandlerImpl()
185 : weak_factory_(this),
186 choose_what_to_sync_(false) {
189 InlineLoginHandlerImpl::~InlineLoginHandlerImpl() {}
191 bool InlineLoginHandlerImpl::HandleContextMenu(
192 const content::ContextMenuParams& params) {
200 void InlineLoginHandlerImpl::SetExtraInitParams(base::DictionaryValue& params) {
201 params.SetString("service", "chromiumsync");
203 content::WebContents* contents = web_ui()->GetWebContents();
204 const GURL& current_url = contents->GetURL();
205 std::string is_constrained;
206 net::GetValueForKeyInQuery(current_url, "constrained", &is_constrained);
207 if (is_constrained == "1")
208 contents->SetDelegate(this);
210 signin::Source source = signin::GetSourceForPromoURL(current_url);
211 OneClickSigninHelper::LogHistogramValue(
212 source, one_click_signin::HISTOGRAM_SHOWN);
215 void InlineLoginHandlerImpl::CompleteLogin(const base::ListValue* args) {
216 content::WebContents* contents = web_ui()->GetWebContents();
217 const GURL& current_url = contents->GetURL();
219 const base::DictionaryValue* dict = NULL;
220 args->GetDictionary(0, &dict);
222 bool skip_for_now = false;
223 dict->GetBoolean("skipForNow", &skip_for_now);
225 signin::SetUserSkippedPromo(Profile::FromWebUI(web_ui()));
226 SyncStarterCallback(OneClickSigninSyncStarter::SYNC_SETUP_FAILURE);
230 base::string16 email;
231 dict->GetString("email", &email);
232 DCHECK(!email.empty());
233 email_ = base::UTF16ToASCII(email);
234 base::string16 password;
235 dict->GetString("password", &password);
236 password_ = base::UTF16ToASCII(password);
238 // When doing a SAML sign in, this email check may result in a false
239 // positive. This happens when the user types one email address in the
240 // gaia sign in page, but signs in to a different account in the SAML sign in
242 std::string default_email;
243 std::string validate_email;
244 if (net::GetValueForKeyInQuery(current_url, "email", &default_email) &&
245 net::GetValueForKeyInQuery(current_url, "validateEmail",
247 validate_email == "1") {
248 if (!gaia::AreEmailsSame(email_, default_email)) {
249 SyncStarterCallback(OneClickSigninSyncStarter::SYNC_SETUP_FAILURE);
254 base::string16 session_index;
255 dict->GetString("sessionIndex", &session_index);
256 session_index_ = base::UTF16ToASCII(session_index);
257 DCHECK(!session_index_.empty());
258 dict->GetBoolean("chooseWhatToSync", &choose_what_to_sync_);
260 signin::Source source = signin::GetSourceForPromoURL(current_url);
261 OneClickSigninHelper::LogHistogramValue(
262 source, one_click_signin::HISTOGRAM_ACCEPTED);
263 bool switch_to_advanced =
264 choose_what_to_sync_ && (source != signin::SOURCE_SETTINGS);
265 OneClickSigninHelper::LogHistogramValue(
267 switch_to_advanced ? one_click_signin::HISTOGRAM_WITH_ADVANCED :
268 one_click_signin::HISTOGRAM_WITH_DEFAULTS);
270 OneClickSigninHelper::CanOfferFor can_offer_for =
271 OneClickSigninHelper::CAN_OFFER_FOR_ALL;
273 case signin::SOURCE_AVATAR_BUBBLE_ADD_ACCOUNT:
274 can_offer_for = OneClickSigninHelper::CAN_OFFER_FOR_SECONDARY_ACCOUNT;
276 case signin::SOURCE_REAUTH: {
277 std::string primary_username =
278 SigninManagerFactory::GetForProfile(
279 Profile::FromWebUI(web_ui()))->GetAuthenticatedUsername();
280 if (!gaia::AreEmailsSame(default_email, primary_username))
281 can_offer_for = OneClickSigninHelper::CAN_OFFER_FOR_SECONDARY_ACCOUNT;
285 // No need to change |can_offer_for|.
289 std::string error_msg;
290 bool can_offer = OneClickSigninHelper::CanOffer(
291 contents, can_offer_for, email_, &error_msg);
293 HandleLoginError(error_msg);
297 AboutSigninInternals* about_signin_internals =
298 AboutSigninInternalsFactory::GetForProfile(Profile::FromWebUI(web_ui()));
299 about_signin_internals->OnAuthenticationResultReceived(
300 "GAIA Auth Successful");
302 content::StoragePartition* partition =
303 content::BrowserContext::GetStoragePartitionForSite(
304 contents->GetBrowserContext(),
305 GURL(chrome::kChromeUIChromeSigninURL));
307 // InlineSigninHelper will delete itself.
308 new InlineSigninHelper(GetWeakPtr(), partition->GetURLRequestContext(),
309 Profile::FromWebUI(web_ui()), current_url,
310 email_, password_, session_index_,
311 choose_what_to_sync_);
315 session_index_.clear();
316 web_ui()->CallJavascriptFunction("inline.login.closeDialog");
319 void InlineLoginHandlerImpl::HandleLoginError(const std::string& error_msg) {
320 SyncStarterCallback(OneClickSigninSyncStarter::SYNC_SETUP_FAILURE);
322 Browser* browser = GetDesktopBrowser();
323 if (browser && !error_msg.empty()) {
324 VLOG(1) << "InlineLoginHandlerImpl::HandleLoginError shows error message: "
326 OneClickSigninHelper::ShowSigninErrorBubble(browser, error_msg);
331 session_index_.clear();
334 Browser* InlineLoginHandlerImpl::GetDesktopBrowser() {
335 Browser* browser = chrome::FindBrowserWithWebContents(
336 web_ui()->GetWebContents());
338 browser = chrome::FindLastActiveWithProfile(
339 Profile::FromWebUI(web_ui()), chrome::GetActiveDesktop());
344 void InlineLoginHandlerImpl::SyncStarterCallback(
345 OneClickSigninSyncStarter::SyncSetupResult result) {
346 content::WebContents* contents = web_ui()->GetWebContents();
348 if (contents->GetController().GetPendingEntry()) {
349 // Do nothing if a navigation is pending, since this call can be triggered
350 // from DidStartLoading. This avoids deleting the pending entry while we are
351 // still navigating to it. See crbug/346632.
355 const GURL& current_url = contents->GetLastCommittedURL();
356 signin::Source source = signin::GetSourceForPromoURL(current_url);
357 bool auto_close = signin::IsAutoCloseEnabledInURL(current_url);
359 if (result == OneClickSigninSyncStarter::SYNC_SETUP_FAILURE) {
360 OneClickSigninHelper::RedirectToNtpOrAppsPage(contents, source);
361 } else if (auto_close) {
362 base::MessageLoop::current()->PostTask(
364 base::Bind(&InlineLoginHandlerImpl::CloseTab,
365 weak_factory_.GetWeakPtr(),
366 signin::ShouldShowAccountManagement(current_url)));
368 OneClickSigninHelper::RedirectToNtpOrAppsPageIfNecessary(contents, source);
372 void InlineLoginHandlerImpl::CloseTab(bool show_account_management) {
373 content::WebContents* tab = web_ui()->GetWebContents();
374 Browser* browser = chrome::FindBrowserWithWebContents(tab);
376 TabStripModel* tab_strip_model = browser->tab_strip_model();
377 if (tab_strip_model) {
378 int index = tab_strip_model->GetIndexOfWebContents(tab);
379 if (index != TabStripModel::kNoTab) {
380 tab_strip_model->ExecuteContextMenuCommand(
381 index, TabStripModel::CommandCloseTab);
385 if (show_account_management) {
386 browser->window()->ShowAvatarBubbleFromAvatarButton(
387 BrowserWindow::AVATAR_BUBBLE_MODE_ACCOUNT_MANAGEMENT,
388 signin::ManageAccountsParams());