143e2005fad1fd32e060fd40ea6c5b1de689df5f
[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 <string>
8
9 #include "base/bind.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"
37
38 namespace {
39
40 class InlineSigninHelper : public SigninOAuthHelper,
41                            public SigninOAuthHelper::Consumer {
42  public:
43   InlineSigninHelper(
44       base::WeakPtr<InlineLoginHandlerImpl> handler,
45       net::URLRequestContextGetter* getter,
46       Profile* profile,
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);
52
53  private:
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;
61
62   base::WeakPtr<InlineLoginHandlerImpl> handler_;
63   Profile* profile_;
64   GURL current_url_;
65   std::string email_;
66   std::string password_;
67   std::string session_index_;
68   bool choose_what_to_sync_;
69
70   DISALLOW_COPY_AND_ASSIGN(InlineSigninHelper);
71 };
72
73 InlineSigninHelper::InlineSigninHelper(
74     base::WeakPtr<InlineLoginHandlerImpl> handler,
75     net::URLRequestContextGetter* getter,
76     Profile* profile,
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),
83       handler_(handler),
84       profile_(profile),
85       current_url_(current_url),
86       email_(email),
87       password_(password),
88       session_index_(session_index),
89       choose_what_to_sync_(choose_what_to_sync) {
90   DCHECK(profile_);
91   DCHECK(!email_.empty());
92   DCHECK(!session_index_.empty());
93 }
94
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;
101   if (handler_) {
102     contents = handler_->web_ui()->GetWebContents();
103     browser = handler_->GetDesktopBrowser();
104   }
105
106   AboutSigninInternals* about_signin_internals =
107     AboutSigninInternalsFactory::GetForProfile(profile_);
108   about_signin_internals->OnRefreshTokenReceived("Successful");
109
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);
115
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(
120           FROM_HERE,
121           base::Bind(&InlineLoginHandlerImpl::CloseTab,
122           handler_,
123           signin::ShouldShowAccountManagement(current_url_)));
124     }
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
145     bool start_signin =
146         !OneClickSigninHelper::HandleCrossAccountError(
147             contents, "",
148             email, password_, refresh_token,
149             OneClickSigninHelper::AUTO_ACCEPT_EXPLICIT,
150             source, start_mode,
151             base::Bind(&InlineLoginHandlerImpl::SyncStarterCallback,
152                        handler_));
153     if (start_signin) {
154       // Call OneClickSigninSyncStarter to exchange oauth code for tokens.
155       // OneClickSigninSyncStarter will delete itself once the job is done.
156       new OneClickSigninSyncStarter(
157           profile_, browser,
158           email, password_, refresh_token,
159           start_mode,
160           contents,
161           confirmation_required,
162           signin::GetNextPageURLForPromoURL(current_url_),
163           base::Bind(&InlineLoginHandlerImpl::SyncStarterCallback, handler_));
164     }
165   }
166
167   base::MessageLoop::current()->DeleteSoon(FROM_HERE, this);
168 }
169
170 void InlineSigninHelper::OnSigninOAuthInformationFailure(
171   const GoogleServiceAuthError& error) {
172   if (handler_)
173     handler_->HandleLoginError(error.ToString());
174
175   AboutSigninInternals* about_signin_internals =
176     AboutSigninInternalsFactory::GetForProfile(profile_);
177   about_signin_internals->OnRefreshTokenReceived("Failure");
178
179   base::MessageLoop::current()->DeleteSoon(FROM_HERE, this);
180 }
181
182 }  // namespace
183
184 InlineLoginHandlerImpl::InlineLoginHandlerImpl()
185       : weak_factory_(this),
186         choose_what_to_sync_(false) {
187 }
188
189 InlineLoginHandlerImpl::~InlineLoginHandlerImpl() {}
190
191 bool InlineLoginHandlerImpl::HandleContextMenu(
192     const content::ContextMenuParams& params) {
193 #ifndef NDEBUG
194   return false;
195 #else
196   return true;
197 #endif
198 }
199
200 void InlineLoginHandlerImpl::SetExtraInitParams(base::DictionaryValue& params) {
201   params.SetString("service", "chromiumsync");
202
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);
209
210   signin::Source source = signin::GetSourceForPromoURL(current_url);
211   OneClickSigninHelper::LogHistogramValue(
212       source, one_click_signin::HISTOGRAM_SHOWN);
213 }
214
215 void InlineLoginHandlerImpl::CompleteLogin(const base::ListValue* args) {
216   content::WebContents* contents = web_ui()->GetWebContents();
217   const GURL& current_url = contents->GetURL();
218
219   const base::DictionaryValue* dict = NULL;
220   args->GetDictionary(0, &dict);
221
222   bool skip_for_now = false;
223   dict->GetBoolean("skipForNow", &skip_for_now);
224   if (skip_for_now) {
225     signin::SetUserSkippedPromo(Profile::FromWebUI(web_ui()));
226     SyncStarterCallback(OneClickSigninSyncStarter::SYNC_SETUP_FAILURE);
227     return;
228   }
229
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);
237
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
241   // page.
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",
246                                  &validate_email) &&
247       validate_email == "1") {
248     if (!gaia::AreEmailsSame(email_, default_email)) {
249       SyncStarterCallback(OneClickSigninSyncStarter::SYNC_SETUP_FAILURE);
250       return;
251     }
252   }
253
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_);
259
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(
266       source,
267       switch_to_advanced ? one_click_signin::HISTOGRAM_WITH_ADVANCED :
268                            one_click_signin::HISTOGRAM_WITH_DEFAULTS);
269
270   OneClickSigninHelper::CanOfferFor can_offer_for =
271       OneClickSigninHelper::CAN_OFFER_FOR_ALL;
272   switch (source) {
273     case signin::SOURCE_AVATAR_BUBBLE_ADD_ACCOUNT:
274       can_offer_for = OneClickSigninHelper::CAN_OFFER_FOR_SECONDARY_ACCOUNT;
275       break;
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;
282       break;
283     }
284     default:
285       // No need to change |can_offer_for|.
286       break;
287   }
288
289   std::string error_msg;
290   bool can_offer = OneClickSigninHelper::CanOffer(
291       contents, can_offer_for, email_, &error_msg);
292   if (!can_offer) {
293     HandleLoginError(error_msg);
294     return;
295   }
296
297   AboutSigninInternals* about_signin_internals =
298       AboutSigninInternalsFactory::GetForProfile(Profile::FromWebUI(web_ui()));
299   about_signin_internals->OnAuthenticationResultReceived(
300       "GAIA Auth Successful");
301
302   content::StoragePartition* partition =
303       content::BrowserContext::GetStoragePartitionForSite(
304           contents->GetBrowserContext(),
305           GURL(chrome::kChromeUIChromeSigninURL));
306
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_);
312
313   email_.clear();
314   password_.clear();
315   session_index_.clear();
316   web_ui()->CallJavascriptFunction("inline.login.closeDialog");
317 }
318
319 void InlineLoginHandlerImpl::HandleLoginError(const std::string& error_msg) {
320   SyncStarterCallback(OneClickSigninSyncStarter::SYNC_SETUP_FAILURE);
321
322   Browser* browser = GetDesktopBrowser();
323   if (browser && !error_msg.empty()) {
324     VLOG(1) << "InlineLoginHandlerImpl::HandleLoginError shows error message: "
325             << error_msg;
326     OneClickSigninHelper::ShowSigninErrorBubble(browser, error_msg);
327   }
328
329   email_.clear();
330   password_.clear();
331   session_index_.clear();
332 }
333
334 Browser* InlineLoginHandlerImpl::GetDesktopBrowser() {
335   Browser* browser = chrome::FindBrowserWithWebContents(
336       web_ui()->GetWebContents());
337   if (!browser) {
338     browser = chrome::FindLastActiveWithProfile(
339         Profile::FromWebUI(web_ui()), chrome::GetActiveDesktop());
340   }
341   return browser;
342 }
343
344 void InlineLoginHandlerImpl::SyncStarterCallback(
345     OneClickSigninSyncStarter::SyncSetupResult result) {
346   content::WebContents* contents = web_ui()->GetWebContents();
347
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.
352     return;
353   }
354
355   const GURL& current_url = contents->GetLastCommittedURL();
356   signin::Source source = signin::GetSourceForPromoURL(current_url);
357   bool auto_close = signin::IsAutoCloseEnabledInURL(current_url);
358
359   if (result == OneClickSigninSyncStarter::SYNC_SETUP_FAILURE) {
360     OneClickSigninHelper::RedirectToNtpOrAppsPage(contents, source);
361   } else if (auto_close) {
362     base::MessageLoop::current()->PostTask(
363         FROM_HERE,
364         base::Bind(&InlineLoginHandlerImpl::CloseTab,
365                    weak_factory_.GetWeakPtr(),
366                    signin::ShouldShowAccountManagement(current_url)));
367   } else {
368      OneClickSigninHelper::RedirectToNtpOrAppsPageIfNecessary(contents, source);
369   }
370 }
371
372 void InlineLoginHandlerImpl::CloseTab(bool show_account_management) {
373   content::WebContents* tab = web_ui()->GetWebContents();
374   Browser* browser = chrome::FindBrowserWithWebContents(tab);
375   if (browser) {
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);
382       }
383     }
384
385     if (show_account_management) {
386       browser->window()->ShowAvatarBubbleFromAvatarButton(
387             BrowserWindow::AVATAR_BUBBLE_MODE_ACCOUNT_MANAGEMENT,
388             signin::ManageAccountsParams());
389     }
390   }
391 }