Cast: Stop logging kVideoFrameSentToEncoder and rename a couple events.
[chromium-blink-merge.git] / chrome / browser / ui / webui / signin / inline_login_handler_impl.cc
blobb79b1c9576312ff8ef9610c60e4cb5d435bcda3c
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"
7 #include <string>
9 #include "base/bind.h"
10 #include "base/prefs/pref_service.h"
11 #include "base/strings/string_number_conversions.h"
12 #include "base/strings/string_util.h"
13 #include "base/strings/utf_string_conversions.h"
14 #include "base/values.h"
15 #include "chrome/browser/profiles/profile.h"
16 #include "chrome/browser/signin/about_signin_internals_factory.h"
17 #include "chrome/browser/signin/profile_oauth2_token_service_factory.h"
18 #include "chrome/browser/signin/signin_promo.h"
19 #include "chrome/browser/sync/profile_sync_service.h"
20 #include "chrome/browser/sync/profile_sync_service_factory.h"
21 #include "chrome/browser/ui/browser_finder.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/pref_names.h"
26 #include "chrome/common/url_constants.h"
27 #include "components/signin/core/browser/about_signin_internals.h"
28 #include "components/signin/core/browser/profile_oauth2_token_service.h"
29 #include "components/signin/core/browser/signin_error_controller.h"
30 #include "components/signin/core/browser/signin_oauth_helper.h"
31 #include "content/public/browser/storage_partition.h"
32 #include "content/public/browser/web_contents.h"
33 #include "content/public/browser/web_ui.h"
34 #include "google_apis/gaia/gaia_auth_fetcher.h"
35 #include "google_apis/gaia/gaia_auth_util.h"
36 #include "google_apis/gaia/gaia_constants.h"
37 #include "google_apis/gaia/gaia_urls.h"
38 #include "net/base/url_util.h"
40 namespace {
42 class InlineSigninHelper : public SigninOAuthHelper,
43 public SigninOAuthHelper::Consumer {
44 public:
45 InlineSigninHelper(
46 base::WeakPtr<InlineLoginHandlerImpl> handler,
47 net::URLRequestContextGetter* getter,
48 Profile* profile,
49 const GURL& current_url,
50 const std::string& email,
51 const std::string& password,
52 const std::string& session_index,
53 bool choose_what_to_sync);
55 private:
56 // Overriden from SigninOAuthHelper::Consumer.
57 virtual void OnSigninOAuthInformationAvailable(
58 const std::string& email,
59 const std::string& display_email,
60 const std::string& refresh_token) OVERRIDE;
61 virtual void OnSigninOAuthInformationFailure(
62 const GoogleServiceAuthError& error) OVERRIDE;
64 base::WeakPtr<InlineLoginHandlerImpl> handler_;
65 Profile* profile_;
66 GURL current_url_;
67 std::string email_;
68 std::string password_;
69 std::string session_index_;
70 bool choose_what_to_sync_;
72 DISALLOW_COPY_AND_ASSIGN(InlineSigninHelper);
75 InlineSigninHelper::InlineSigninHelper(
76 base::WeakPtr<InlineLoginHandlerImpl> handler,
77 net::URLRequestContextGetter* getter,
78 Profile* profile,
79 const GURL& current_url,
80 const std::string& email,
81 const std::string& password,
82 const std::string& session_index,
83 bool choose_what_to_sync)
84 : SigninOAuthHelper(getter, session_index, this),
85 handler_(handler),
86 profile_(profile),
87 current_url_(current_url),
88 email_(email),
89 password_(password),
90 session_index_(session_index),
91 choose_what_to_sync_(choose_what_to_sync) {
92 DCHECK(profile_);
93 DCHECK(!email_.empty());
94 DCHECK(!session_index_.empty());
97 void InlineSigninHelper::OnSigninOAuthInformationAvailable(
98 const std::string& email,
99 const std::string& display_email,
100 const std::string& refresh_token) {
101 content::WebContents* contents = NULL;
102 Browser* browser = NULL;
103 if (handler_) {
104 contents = handler_->web_ui()->GetWebContents();
105 browser = handler_->GetDesktopBrowser();
108 AboutSigninInternals* about_signin_internals =
109 AboutSigninInternalsFactory::GetForProfile(profile_);
110 about_signin_internals->OnRefreshTokenReceived("Successful");
112 signin::Source source = signin::GetSourceForPromoURL(current_url_);
113 if (source == signin::SOURCE_AVATAR_BUBBLE_ADD_ACCOUNT) {
114 ProfileOAuth2TokenServiceFactory::GetForProfile(profile_)->
115 UpdateCredentials(email, refresh_token);
117 if (signin::IsAutoCloseEnabledInURL(current_url_)) {
118 // Close the gaia sign in tab via a task to make sure we aren't in the
119 // middle of any webui handler code.
120 base::MessageLoop::current()->PostTask(
121 FROM_HERE,
122 base::Bind(&InlineLoginHandlerImpl::CloseTab,
123 handler_));
125 } else {
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;
144 bool start_signin = true;
146 if (source != signin::SOURCE_AVATAR_BUBBLE_ADD_ACCOUNT) {
147 start_signin = !OneClickSigninHelper::HandleCrossAccountError(
148 contents, "",
149 email, password_, refresh_token,
150 OneClickSigninHelper::AUTO_ACCEPT_EXPLICIT,
151 source, start_mode,
152 base::Bind(&InlineLoginHandlerImpl::SyncStarterCallback,
153 handler_));
156 if (start_signin) {
157 // Call OneClickSigninSyncStarter to exchange oauth code for tokens.
158 // OneClickSigninSyncStarter will delete itself once the job is done.
159 new OneClickSigninSyncStarter(
160 profile_, browser,
161 email, password_, refresh_token,
162 start_mode,
163 contents,
164 confirmation_required,
165 base::Bind(&InlineLoginHandlerImpl::SyncStarterCallback, handler_));
169 base::MessageLoop::current()->DeleteSoon(FROM_HERE, this);
172 void InlineSigninHelper::OnSigninOAuthInformationFailure(
173 const GoogleServiceAuthError& error) {
174 if (handler_)
175 handler_->HandleLoginError(error.ToString());
177 AboutSigninInternals* about_signin_internals =
178 AboutSigninInternalsFactory::GetForProfile(profile_);
179 about_signin_internals->OnRefreshTokenReceived("Failure");
181 base::MessageLoop::current()->DeleteSoon(FROM_HERE, this);
184 } // namespace
186 InlineLoginHandlerImpl::InlineLoginHandlerImpl()
187 : weak_factory_(this),
188 choose_what_to_sync_(false) {
191 InlineLoginHandlerImpl::~InlineLoginHandlerImpl() {}
193 void InlineLoginHandlerImpl::RegisterMessages() {
194 InlineLoginHandler::RegisterMessages();
196 web_ui()->RegisterMessageCallback("switchToFullTab",
197 base::Bind(&InlineLoginHandlerImpl::HandleSwitchToFullTabMessage,
198 base::Unretained(this)));
201 void InlineLoginHandlerImpl::SetExtraInitParams(base::DictionaryValue& params) {
202 params.SetInteger("authMode", InlineLoginHandler::kDesktopAuthMode);
204 const GURL& current_url = web_ui()->GetWebContents()->GetURL();
205 signin::Source source = signin::GetSourceForPromoURL(current_url);
206 if (source == signin::SOURCE_AVATAR_BUBBLE_ADD_ACCOUNT ||
207 source == signin::SOURCE_AVATAR_BUBBLE_SIGN_IN) {
208 // Drop the leading slash in the path.
209 params.SetString("gaiaPath",
210 GaiaUrls::GetInstance()->embedded_signin_url().path().substr(1));
213 params.SetString("service", "chromiumsync");
214 params.SetString("continueUrl",
215 signin::GetLandingURL("source", static_cast<int>(source)).spec());
217 std::string default_email;
218 if (source != signin::SOURCE_AVATAR_BUBBLE_ADD_ACCOUNT) {
219 default_email = Profile::FromWebUI(web_ui())->GetPrefs()->
220 GetString(prefs::kGoogleServicesLastUsername);
221 } else {
222 if (!net::GetValueForKeyInQuery(current_url, "email", &default_email))
223 default_email.clear();
225 if (!default_email.empty())
226 params.SetString("email", default_email);
228 std::string frame_url;
229 net::GetValueForKeyInQuery(current_url, "frameUrl", &frame_url);
230 if (!frame_url.empty())
231 params.SetString("frameUrl", frame_url);
233 std::string is_constrained;
234 net::GetValueForKeyInQuery(current_url, "constrained", &is_constrained);
235 if (!is_constrained.empty())
236 params.SetString("constrained", is_constrained);
238 // TODO(rogerta): this needs to be passed on to gaia somehow.
239 std::string read_only_email;
240 net::GetValueForKeyInQuery(current_url, "readOnlyEmail", &read_only_email);
241 if (!read_only_email.empty())
242 params.SetString("readOnlyEmail", read_only_email);
244 OneClickSigninHelper::LogHistogramValue(
245 source, one_click_signin::HISTOGRAM_SHOWN);
248 void InlineLoginHandlerImpl::HandleSwitchToFullTabMessage(
249 const base::ListValue* args) {
250 base::string16 url_str;
251 CHECK(args->GetString(0, &url_str));
253 content::WebContents* web_contents = web_ui()->GetWebContents();
254 GURL main_frame_url(web_contents->GetURL());
255 main_frame_url = net::AppendOrReplaceQueryParameter(
256 main_frame_url, "frameUrl", base::UTF16ToASCII(url_str));
257 chrome::NavigateParams params(
258 Profile::FromWebUI(web_ui()),
259 net::AppendOrReplaceQueryParameter(main_frame_url, "constrained", "0"),
260 content::PAGE_TRANSITION_AUTO_TOPLEVEL);
261 chrome::Navigate(&params);
263 web_ui()->CallJavascriptFunction("inline.login.closeDialog");
266 void InlineLoginHandlerImpl::CompleteLogin(const base::ListValue* args) {
267 content::WebContents* contents = web_ui()->GetWebContents();
268 const GURL& current_url = contents->GetURL();
270 const base::DictionaryValue* dict = NULL;
271 args->GetDictionary(0, &dict);
273 bool skip_for_now = false;
274 dict->GetBoolean("skipForNow", &skip_for_now);
275 if (skip_for_now) {
276 signin::SetUserSkippedPromo(Profile::FromWebUI(web_ui()));
277 SyncStarterCallback(OneClickSigninSyncStarter::SYNC_SETUP_FAILURE);
278 return;
281 base::string16 email;
282 dict->GetString("email", &email);
283 DCHECK(!email.empty());
284 email_ = base::UTF16ToASCII(email);
285 base::string16 password;
286 dict->GetString("password", &password);
287 password_ = base::UTF16ToASCII(password);
289 // When doing a SAML sign in, this email check may result in a false
290 // positive. This happens when the user types one email address in the
291 // gaia sign in page, but signs in to a different account in the SAML sign in
292 // page.
293 std::string default_email;
294 std::string validate_email;
295 if (net::GetValueForKeyInQuery(current_url, "email", &default_email) &&
296 net::GetValueForKeyInQuery(current_url, "validateEmail",
297 &validate_email) &&
298 validate_email == "1") {
299 if (!gaia::AreEmailsSame(email_, default_email)) {
300 SyncStarterCallback(OneClickSigninSyncStarter::SYNC_SETUP_FAILURE);
301 return;
305 base::string16 session_index;
306 dict->GetString("sessionIndex", &session_index);
307 session_index_ = base::UTF16ToASCII(session_index);
308 DCHECK(!session_index_.empty());
309 dict->GetBoolean("chooseWhatToSync", &choose_what_to_sync_);
311 signin::Source source = signin::GetSourceForPromoURL(current_url);
312 OneClickSigninHelper::LogHistogramValue(
313 source, one_click_signin::HISTOGRAM_ACCEPTED);
314 bool switch_to_advanced =
315 choose_what_to_sync_ && (source != signin::SOURCE_SETTINGS);
316 OneClickSigninHelper::LogHistogramValue(
317 source,
318 switch_to_advanced ? one_click_signin::HISTOGRAM_WITH_ADVANCED :
319 one_click_signin::HISTOGRAM_WITH_DEFAULTS);
321 OneClickSigninHelper::CanOfferFor can_offer_for =
322 source == signin::SOURCE_AVATAR_BUBBLE_ADD_ACCOUNT ?
323 OneClickSigninHelper::CAN_OFFER_FOR_SECONDARY_ACCOUNT :
324 OneClickSigninHelper::CAN_OFFER_FOR_ALL;
325 std::string error_msg;
326 bool can_offer = OneClickSigninHelper::CanOffer(
327 contents, can_offer_for, email_, &error_msg);
328 if (!can_offer) {
329 HandleLoginError(error_msg);
330 return;
333 content::StoragePartition* partition =
334 content::BrowserContext::GetStoragePartitionForSite(
335 contents->GetBrowserContext(),
336 GURL(chrome::kChromeUIChromeSigninURL));
338 // InlineSigninHelper will delete itself.
339 new InlineSigninHelper(GetWeakPtr(), partition->GetURLRequestContext(),
340 Profile::FromWebUI(web_ui()), current_url,
341 email_, password_, session_index_,
342 choose_what_to_sync_);
344 email_.clear();
345 password_.clear();
346 session_index_.clear();
347 web_ui()->CallJavascriptFunction("inline.login.closeDialog");
350 void InlineLoginHandlerImpl::HandleLoginError(const std::string& error_msg) {
351 SyncStarterCallback(OneClickSigninSyncStarter::SYNC_SETUP_FAILURE);
353 Browser* browser = GetDesktopBrowser();
354 if (browser && !error_msg.empty()) {
355 VLOG(1) << "InlineLoginHandlerImpl::HandleLoginError shows error message: "
356 << error_msg;
357 OneClickSigninHelper::ShowSigninErrorBubble(browser, error_msg);
360 email_.clear();
361 password_.clear();
362 session_index_.clear();
365 Browser* InlineLoginHandlerImpl::GetDesktopBrowser() {
366 Browser* browser = chrome::FindBrowserWithWebContents(
367 web_ui()->GetWebContents());
368 if (!browser) {
369 browser = chrome::FindLastActiveWithProfile(
370 Profile::FromWebUI(web_ui()), chrome::GetActiveDesktop());
372 return browser;
375 void InlineLoginHandlerImpl::SyncStarterCallback(
376 OneClickSigninSyncStarter::SyncSetupResult result) {
377 content::WebContents* contents = web_ui()->GetWebContents();
379 if (contents->GetController().GetPendingEntry()) {
380 // Do nothing if a navigation is pending, since this call can be triggered
381 // from DidStartLoading. This avoids deleting the pending entry while we are
382 // still navigating to it. See crbug/346632.
383 return;
386 const GURL& current_url = contents->GetLastCommittedURL();
387 signin::Source source = signin::GetSourceForPromoURL(current_url);
388 bool auto_close = signin::IsAutoCloseEnabledInURL(current_url);
390 if (result == OneClickSigninSyncStarter::SYNC_SETUP_FAILURE) {
391 OneClickSigninHelper::RedirectToNtpOrAppsPage(contents, source);
392 } else if (auto_close) {
393 base::MessageLoop::current()->PostTask(
394 FROM_HERE,
395 base::Bind(&InlineLoginHandlerImpl::CloseTab,
396 weak_factory_.GetWeakPtr()));
397 } else {
398 OneClickSigninHelper::RedirectToNtpOrAppsPageIfNecessary(contents, source);
402 void InlineLoginHandlerImpl::CloseTab() {
403 content::WebContents* tab = web_ui()->GetWebContents();
404 Browser* browser = chrome::FindBrowserWithWebContents(tab);
405 if (browser) {
406 TabStripModel* tab_strip_model = browser->tab_strip_model();
407 if (tab_strip_model) {
408 int index = tab_strip_model->GetIndexOfWebContents(tab);
409 if (index != TabStripModel::kNoTab) {
410 tab_strip_model->ExecuteContextMenuCommand(
411 index, TabStripModel::CommandCloseTab);