Upstream version 5.34.104.0
[platform/framework/web/crosswalk.git] / src / chrome / browser / ui / webui / signin / inline_login_handler_impl.cc
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.
4
5 #include "chrome/browser/ui/webui/signin/inline_login_handler_impl.h"
6
7 #include "base/bind.h"
8 #include "base/prefs/pref_service.h"
9 #include "base/strings/string_number_conversions.h"
10 #include "base/strings/string_util.h"
11 #include "base/values.h"
12 #include "chrome/browser/profiles/profile.h"
13 #include "chrome/browser/signin/signin_global_error.h"
14 #include "chrome/browser/signin/signin_oauth_helper.h"
15 #include "chrome/browser/signin/signin_promo.h"
16 #include "chrome/browser/sync/profile_sync_service.h"
17 #include "chrome/browser/sync/profile_sync_service_factory.h"
18 #include "chrome/browser/ui/browser_finder.h"
19 #include "chrome/browser/ui/sync/one_click_signin_helper.h"
20 #include "chrome/browser/ui/sync/one_click_signin_histogram.h"
21 #include "chrome/browser/ui/tabs/tab_strip_model.h"
22 #include "chrome/common/pref_names.h"
23 #include "chrome/common/url_constants.h"
24 #include "content/public/browser/storage_partition.h"
25 #include "content/public/browser/web_contents.h"
26 #include "content/public/browser/web_ui.h"
27 #include "google_apis/gaia/gaia_auth_fetcher.h"
28 #include "google_apis/gaia/gaia_constants.h"
29 #include "google_apis/gaia/gaia_urls.h"
30 #include "net/base/url_util.h"
31
32 namespace {
33
34 } // empty namespace
35
36 InlineLoginHandlerImpl::InlineLoginHandlerImpl()
37       : weak_factory_(this),
38         choose_what_to_sync_(false),
39         complete_login_triggered_(false) {
40 }
41
42 InlineLoginHandlerImpl::~InlineLoginHandlerImpl() {}
43
44 void InlineLoginHandlerImpl::RegisterMessages() {
45   InlineLoginHandler::RegisterMessages();
46
47   web_ui()->RegisterMessageCallback("switchToFullTab",
48       base::Bind(&InlineLoginHandlerImpl::HandleSwitchToFullTabMessage,
49                   base::Unretained(this)));
50 }
51
52 void InlineLoginHandlerImpl::SetExtraInitParams(base::DictionaryValue& params) {
53   params.SetInteger("authMode", InlineLoginHandler::kDesktopAuthMode);
54
55   const GURL& current_url = web_ui()->GetWebContents()->GetURL();
56   signin::Source source = signin::GetSourceForPromoURL(current_url);
57   DCHECK(source != signin::SOURCE_UNKNOWN);
58   if (source == signin::SOURCE_AVATAR_BUBBLE_ADD_ACCOUNT ||
59       source == signin::SOURCE_AVATAR_BUBBLE_SIGN_IN) {
60     // Drop the leading slash in the path.
61     params.SetString("gaiaPath",
62         GaiaUrls::GetInstance()->embedded_signin_url().path().substr(1));
63   }
64
65   params.SetString("service", "chromiumsync");
66   params.SetString("continueUrl",
67       signin::GetLandingURL("source", static_cast<int>(source)).spec());
68
69   std::string default_email;
70   if (source != signin::SOURCE_AVATAR_BUBBLE_ADD_ACCOUNT) {
71     default_email = Profile::FromWebUI(web_ui())->GetPrefs()->
72         GetString(prefs::kGoogleServicesLastUsername);
73   } else {
74     if (!net::GetValueForKeyInQuery(current_url, "email", &default_email))
75       default_email.clear();
76   }
77   if (!default_email.empty())
78     params.SetString("email", default_email);
79
80   std::string frame_url;
81   net::GetValueForKeyInQuery(current_url, "frameUrl", &frame_url);
82   if (!frame_url.empty())
83     params.SetString("frameUrl", frame_url);
84
85   std::string is_constrained;
86   net::GetValueForKeyInQuery(current_url, "constrained", &is_constrained);
87   if (!is_constrained.empty())
88     params.SetString("constrained", is_constrained);
89
90   // TODO(rogerta): this needs to be passed on to gaia somehow.
91   std::string read_only_email;
92   net::GetValueForKeyInQuery(current_url, "readOnlyEmail", &read_only_email);
93   if (!read_only_email.empty())
94     params.SetString("readOnlyEmail", read_only_email);
95
96   OneClickSigninHelper::LogHistogramValue(
97       source, one_click_signin::HISTOGRAM_SHOWN);
98 }
99
100 void InlineLoginHandlerImpl::HandleSwitchToFullTabMessage(
101     const base::ListValue* args) {
102   base::string16 url_str;
103   CHECK(args->GetString(0, &url_str));
104
105   content::WebContents* web_contents = web_ui()->GetWebContents();
106   GURL main_frame_url(web_contents->GetURL());
107   main_frame_url = net::AppendOrReplaceQueryParameter(
108       main_frame_url, "frameUrl", UTF16ToASCII(url_str));
109   chrome::NavigateParams params(
110       Profile::FromWebUI(web_ui()),
111       net::AppendOrReplaceQueryParameter(main_frame_url, "constrained", "0"),
112       content::PAGE_TRANSITION_AUTO_TOPLEVEL);
113   chrome::Navigate(&params);
114
115   web_ui()->CallJavascriptFunction("inline.login.closeDialog");
116 }
117
118 void InlineLoginHandlerImpl::CompleteLogin(const base::ListValue* args) {
119   if (complete_login_triggered_) {
120     // Gaia is supposed to trigger CompleteLogin by sending a completelogin
121     // message to Chrome, since Gaia does not always do this, Chrome injects
122     // some code into the Gaia page to handle that. This may result in duplicate
123     // completelogin messages when Gaia does send the message.
124     // TODO(guohui): coordinate with Gaia team to only send the completeLogin
125     // message on Chrome versions that do not inject similar code into Gaia.
126     VLOG(1) << "InlineLoginHandlerImpl::CompleteLogin called more than once";
127     return;
128   }
129   complete_login_triggered_ = true;
130
131   content::WebContents* contents = web_ui()->GetWebContents();
132   const GURL& current_url = contents->GetURL();
133
134   const base::DictionaryValue* dict = NULL;
135   args->GetDictionary(0, &dict);
136
137   bool skip_for_now = false;
138   dict->GetBoolean("skipForNow", &skip_for_now);
139   if (skip_for_now) {
140     signin::SetUserSkippedPromo(Profile::FromWebUI(web_ui()));
141     SyncStarterCallback(OneClickSigninSyncStarter::SYNC_SETUP_FAILURE);
142     return;
143   }
144
145   base::string16 email;
146   dict->GetString("email", &email);
147   DCHECK(!email.empty());
148   email_ = UTF16ToASCII(email);
149   base::string16 password;
150   dict->GetString("password", &password);
151   password_ = UTF16ToASCII(password);
152
153   // When doing a SAML sign in, this email check may result in a false
154   // positive.  This happens when the user types one email address in the
155   // gaia sign in page, but signs in to a different account in the SAML sign in
156   // page.
157   std::string default_email;
158   std::string validate_email;
159   if (net::GetValueForKeyInQuery(current_url, "email", &default_email) &&
160       net::GetValueForKeyInQuery(current_url, "validateEmail",
161                                  &validate_email) &&
162       validate_email == "1") {
163     if (email_ != default_email) {
164       SyncStarterCallback(OneClickSigninSyncStarter::SYNC_SETUP_FAILURE);
165       return;
166     }
167   }
168
169   base::string16 session_index;
170   dict->GetString("sessionIndex", &session_index);
171   session_index_ = UTF16ToASCII(session_index);
172   DCHECK(!session_index_.empty());
173   dict->GetBoolean("chooseWhatToSync", &choose_what_to_sync_);
174
175   signin::Source source = signin::GetSourceForPromoURL(current_url);
176   OneClickSigninHelper::LogHistogramValue(
177       source, one_click_signin::HISTOGRAM_ACCEPTED);
178   bool switch_to_advanced =
179       choose_what_to_sync_ && (source != signin::SOURCE_SETTINGS);
180   OneClickSigninHelper::LogHistogramValue(
181       source,
182       switch_to_advanced ? one_click_signin::HISTOGRAM_WITH_ADVANCED :
183                            one_click_signin::HISTOGRAM_WITH_DEFAULTS);
184
185   OneClickSigninHelper::CanOfferFor can_offer_for =
186       source == signin::SOURCE_AVATAR_BUBBLE_ADD_ACCOUNT ?
187       OneClickSigninHelper::CAN_OFFER_FOR_SECONDARY_ACCOUNT :
188       OneClickSigninHelper::CAN_OFFER_FOR_ALL;
189   std::string error_msg;
190   bool can_offer = OneClickSigninHelper::CanOffer(
191       contents, can_offer_for, email_, &error_msg);
192   if (!can_offer) {
193     HandleLoginError(error_msg);
194     return;
195   }
196
197   content::StoragePartition* partition =
198       content::BrowserContext::GetStoragePartitionForSite(
199           contents->GetBrowserContext(),
200           GURL(chrome::kChromeUIChromeSigninURL));
201
202   auth_fetcher_.reset(new GaiaAuthFetcher(this,
203                                           GaiaConstants::kChromeSource,
204                                           partition->GetURLRequestContext()));
205   auth_fetcher_->StartCookieForOAuthCodeExchange(session_index_);
206 }
207
208 void InlineLoginHandlerImpl::OnClientOAuthCodeSuccess(
209     const std::string& oauth_code) {
210   DCHECK(!oauth_code.empty());
211
212   content::WebContents* contents = web_ui()->GetWebContents();
213   Profile* profile = Profile::FromWebUI(web_ui());
214   ProfileSyncService* sync_service =
215       ProfileSyncServiceFactory::GetForProfile(profile);
216   const GURL& current_url = contents->GetURL();
217   signin::Source source = signin::GetSourceForPromoURL(current_url);
218
219   if (source == signin::SOURCE_AVATAR_BUBBLE_ADD_ACCOUNT) {
220     // SigninOAuthHelper will delete itself.
221     SigninOAuthHelper* helper = new SigninOAuthHelper(profile);
222     helper->StartAddingAccount(oauth_code);
223
224     if (signin::IsAutoCloseEnabledInURL(current_url)) {
225       // Close the gaia sign in tab via a task to make sure we aren't in the
226       // middle of any webui handler code.
227       base::MessageLoop::current()->PostTask(
228           FROM_HERE,
229           base::Bind(&InlineLoginHandlerImpl::CloseTab,
230                      weak_factory_.GetWeakPtr()));
231     }
232   } else {
233     OneClickSigninSyncStarter::StartSyncMode start_mode =
234         source == signin::SOURCE_SETTINGS || choose_what_to_sync_ ?
235             (SigninGlobalError::GetForProfile(profile)->HasMenuItem() &&
236               sync_service && sync_service->HasSyncSetupCompleted()) ?
237                 OneClickSigninSyncStarter::SHOW_SETTINGS_WITHOUT_CONFIGURE :
238                 OneClickSigninSyncStarter::CONFIGURE_SYNC_FIRST :
239             OneClickSigninSyncStarter::SYNC_WITH_DEFAULT_SETTINGS;
240     OneClickSigninSyncStarter::ConfirmationRequired confirmation_required =
241         source == signin::SOURCE_SETTINGS ||
242         source == signin::SOURCE_WEBSTORE_INSTALL ||
243         choose_what_to_sync_?
244             OneClickSigninSyncStarter::NO_CONFIRMATION :
245             OneClickSigninSyncStarter::CONFIRM_AFTER_SIGNIN;
246       OneClickSigninSyncStarter::Callback sync_callback = base::Bind(
247           &InlineLoginHandlerImpl::SyncStarterCallback,
248           weak_factory_.GetWeakPtr());
249
250       bool cross_account_error_handled =
251           OneClickSigninHelper::HandleCrossAccountError(
252               contents, "" /* session_index, not used */,
253               email_, password_, oauth_code,
254               OneClickSigninHelper::AUTO_ACCEPT_EXPLICIT,
255               source, start_mode, sync_callback);
256
257       if (!cross_account_error_handled) {
258         // Call OneClickSigninSyncStarter to exchange oauth code for tokens.
259         // OneClickSigninSyncStarter will delete itself once the job is done.
260         new OneClickSigninSyncStarter(
261             profile, GetDesktopBrowser(), "" /* session_index, not used */,
262             email_, password_, oauth_code,
263             start_mode,
264             contents,
265             confirmation_required,
266             sync_callback);
267       }
268   }
269
270   email_.clear();
271   password_.clear();
272   session_index_.clear();
273   web_ui()->CallJavascriptFunction("inline.login.closeDialog");
274 }
275
276 void InlineLoginHandlerImpl::OnClientOAuthCodeFailure(
277     const GoogleServiceAuthError& error) {
278   LOG(ERROR) << "InlineLoginUI::OnClientOAuthCodeFailure";
279   HandleLoginError(error.ToString());
280 }
281
282 void InlineLoginHandlerImpl::HandleLoginError(const std::string& error_msg) {
283   SyncStarterCallback(OneClickSigninSyncStarter::SYNC_SETUP_FAILURE);
284
285   Browser* browser = GetDesktopBrowser();
286   if (browser && !error_msg.empty()) {
287     VLOG(1) << "InlineLoginHandlerImpl::HandleLoginError shows error message: "
288             << error_msg;
289     OneClickSigninHelper::ShowSigninErrorBubble(browser, error_msg);
290   }
291
292   email_.clear();
293   password_.clear();
294   session_index_.clear();
295 }
296
297 Browser* InlineLoginHandlerImpl::GetDesktopBrowser() {
298   Browser* browser = chrome::FindBrowserWithWebContents(
299       web_ui()->GetWebContents());
300   if (!browser) {
301     browser = chrome::FindLastActiveWithProfile(
302         Profile::FromWebUI(web_ui()), chrome::GetActiveDesktop());
303   }
304   return browser;
305 }
306
307 void InlineLoginHandlerImpl::SyncStarterCallback(
308     OneClickSigninSyncStarter::SyncSetupResult result) {
309   content::WebContents* contents = web_ui()->GetWebContents();
310
311   if (contents->GetController().GetPendingEntry()) {
312     // Do nothing if a navigation is pending, since this call can be triggered
313     // from DidStartLoading. This avoids deleting the pending entry while we are
314     // still navigating to it. See crbug/346632.
315     return;
316   }
317
318   const GURL& current_url = contents->GetLastCommittedURL();
319   signin::Source source = signin::GetSourceForPromoURL(current_url);
320   DCHECK(source != signin::SOURCE_UNKNOWN);
321   bool auto_close = signin::IsAutoCloseEnabledInURL(current_url);
322
323   if (result == OneClickSigninSyncStarter::SYNC_SETUP_FAILURE) {
324     OneClickSigninHelper::RedirectToNtpOrAppsPage(contents, source);
325   } else if (auto_close) {
326     base::MessageLoop::current()->PostTask(
327         FROM_HERE,
328         base::Bind(&InlineLoginHandlerImpl::CloseTab,
329                    weak_factory_.GetWeakPtr()));
330   } else {
331      OneClickSigninHelper::RedirectToNtpOrAppsPageIfNecessary(contents, source);
332   }
333 }
334
335 void InlineLoginHandlerImpl::CloseTab() {
336   content::WebContents* tab = web_ui()->GetWebContents();
337   Browser* browser = chrome::FindBrowserWithWebContents(tab);
338   if (browser) {
339     TabStripModel* tab_strip_model = browser->tab_strip_model();
340     if (tab_strip_model) {
341       int index = tab_strip_model->GetIndexOfWebContents(tab);
342       if (index != TabStripModel::kNoTab) {
343         tab_strip_model->ExecuteContextMenuCommand(
344             index, TabStripModel::CommandCloseTab);
345       }
346     }
347   }
348 }