summaryrefslogtreecommitdiffstats
path: root/chrome/browser/browser_signin.cc
blob: 5e63c876d8d3de9bfa26e8efea77b0e5a0ac142d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/browser_signin.h"

#include <string>
#include <vector>

#include "app/resource_bundle.h"
#include "base/json/json_reader.h"
#include "base/json/json_writer.h"
#include "base/message_loop.h"
#include "base/singleton.h"
#include "base/string_util.h"
#include "base/values.h"
#include "chrome/browser/browser_thread.h"
#include "chrome/browser/dom_ui/chrome_url_data_manager.h"
#include "chrome/browser/dom_ui/constrained_html_ui.h"
#include "chrome/browser/dom_ui/dom_ui_util.h"
#include "chrome/browser/dom_ui/html_dialog_ui.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/sync/profile_sync_service.h"
#include "chrome/browser/sync/sync_setup_flow.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/jstemplate_builder.h"
#include "chrome/common/notification_details.h"
#include "chrome/common/notification_source.h"
#include "chrome/common/notification_type.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/url_constants.h"
#include "grit/browser_resources.h"

class BrowserSigninResourcesSource : public ChromeURLDataManager::DataSource {
 public:
  BrowserSigninResourcesSource()
      : DataSource(chrome::kChromeUIDialogHost, MessageLoop::current()) {
  }

  virtual void StartDataRequest(const std::string& path,
                                bool is_off_the_record,
                                int request_id);

  virtual std::string GetMimeType(const std::string& path) const {
    return "text/html";
  }

 private:
  virtual ~BrowserSigninResourcesSource() {}

  DISALLOW_COPY_AND_ASSIGN(BrowserSigninResourcesSource);
};

void BrowserSigninResourcesSource::StartDataRequest(const std::string& path,
                                                    bool is_off_the_record,
                                                    int request_id) {
  const char kSigninPath[] = "signin";

  std::string response;
  if (path == kSigninPath) {
    const base::StringPiece html(
        ResourceBundle::GetSharedInstance().GetRawDataResource(
            IDR_SIGNIN_HTML));
    DictionaryValue dict;
    SetFontAndTextDirection(&dict);
    response = jstemplate_builder::GetI18nTemplateHtml(html, &dict);
  }

  scoped_refptr<RefCountedBytes> html_bytes(new RefCountedBytes);
  html_bytes->data.resize(response.size());
  std::copy(response.begin(), response.end(), html_bytes->data.begin());
  SendResponse(request_id, html_bytes);
}

class BrowserSigninHtml : public HtmlDialogUIDelegate,
                          public DOMMessageHandler {
 public:
  BrowserSigninHtml(BrowserSignin* signin,
                    string16 suggested_email,
                    string16 login_message);
  virtual ~BrowserSigninHtml() {}

  // HtmlDialogUIDelegate implementation
  virtual bool IsDialogModal() const {
    return false;
  };
  virtual std::wstring GetDialogTitle() const {
    return L"";
  }
  virtual GURL GetDialogContentURL() const {
    return GURL("chrome://dialog/signin");
  }
  virtual void GetDOMMessageHandlers(
      std::vector<DOMMessageHandler*>* handlers) const {
    const DOMMessageHandler* handler = this;
    handlers->push_back(const_cast<DOMMessageHandler*>(handler));
  }
  virtual void GetDialogSize(gfx::Size* size) const {
    size->set_width(600);
    size->set_height(300);
  }
  virtual std::string GetDialogArgs() const {
    return UTF16ToASCII(login_message_);
  }
  virtual void OnDialogClosed(const std::string& json_retval) {
    closed_ = true;
    signin_->Cancel();
  }
  virtual void OnCloseContents(TabContents* source, bool* out_close_dialog) {
  }
  virtual bool ShouldShowDialogTitle() const { return true; }

  // DOMMessageHandler implementation.
  virtual void RegisterMessages();

  // Refreshes the UI, such as after an authentication error.
  void ReloadUI();

  // Method which calls into javascript to force the dialog to close.
  void ForceDialogClose();

 private:
  // JS callback handlers.
  void HandleSigninInit(const ListValue* args);
  void HandleSubmitAuth(const ListValue* args);

  // Nonowned pointer; |signin_| owns this object.
  BrowserSignin* signin_;

  string16 suggested_email_;
  string16 login_message_;

  bool closed_;
};

BrowserSigninHtml::BrowserSigninHtml(BrowserSignin* signin,
                                     string16 suggested_email,
                                     string16 login_message)
    : signin_(signin),
      suggested_email_(suggested_email),
      login_message_(login_message),
      closed_(false) {
}

void BrowserSigninHtml::RegisterMessages() {
  dom_ui_->RegisterMessageCallback(
      "SubmitAuth", NewCallback(this, &BrowserSigninHtml::HandleSubmitAuth));
  dom_ui_->RegisterMessageCallback(
      "SigninInit", NewCallback(this, &BrowserSigninHtml::HandleSigninInit));
}

void BrowserSigninHtml::ReloadUI() {
  HandleSigninInit(NULL);
}

void BrowserSigninHtml::ForceDialogClose() {
  if (!closed_ && dom_ui_) {
    StringValue value("DialogClose");
    ListValue close_args;
    close_args.Append(new StringValue(""));
    dom_ui_->CallJavascriptFunction(L"chrome.send", value, close_args);
  }
}

void BrowserSigninHtml::HandleSigninInit(const ListValue* args) {
  if (!dom_ui_)
    return;

  RenderViewHost* rvh = dom_ui_->tab_contents()->render_view_host();
  rvh->ExecuteJavascriptInWebFrame(L"//iframe[@id='login']", L"hideBlurb();");

  DictionaryValue json_args;
  std::string json;
  std::wstring javascript(L"");
  SyncSetupFlow::GetArgsForGaiaLogin(signin_->GetProfileSyncService(),
                                     &json_args);

  // Replace the suggested email, unless sync has already required a
  // particular value.
  bool is_editable;
  std::string user;
  json_args.GetBoolean("editable_user", &is_editable);
  json_args.GetString("user", &user);
  if (is_editable && user.empty() && !suggested_email_.empty())
    json_args.SetString("user", suggested_email_);

  base::JSONWriter::Write(&json_args, false, &json);
  javascript += L"showGaiaLogin(" + UTF8ToWide(json) + L");";
  rvh->ExecuteJavascriptInWebFrame(L"//iframe[@id='login']", javascript);
}

void BrowserSigninHtml::HandleSubmitAuth(const ListValue* args) {
  std::string json(dom_ui_util::GetJsonResponseFromFirstArgumentInList(args));
  scoped_ptr<DictionaryValue> result(static_cast<DictionaryValue*>(
      base::JSONReader::Read(json, false)));
  std::string username;
  std::string password;
  std::string captcha;
  std::string access_code;
  if (!result.get() ||
      !result->GetString("user", &username) ||
      !result->GetString("pass", &password) ||
      !result->GetString("captcha", &captcha) ||
      !result->GetString("access_code", &access_code)) {
    LOG(ERROR) << "Unintelligble format for authentication data from page.";
    signin_->Cancel();
  }
  signin_->GetProfileSyncService()->OnUserSubmittedAuth(
      username, password, captcha, access_code);
}

BrowserSignin::BrowserSignin(Profile* profile)
    : profile_(profile),
      delegate_(NULL),
      html_dialog_ui_delegate_(NULL) {
  BrowserSigninResourcesSource* source = new BrowserSigninResourcesSource();
  BrowserThread::PostTask(
      BrowserThread::IO, FROM_HERE,
      NewRunnableMethod(Singleton<ChromeURLDataManager>::get(),
                        &ChromeURLDataManager::AddDataSource,
                        make_scoped_refptr(source)));
}

BrowserSignin::~BrowserSignin() {
  delegate_ = NULL;
}

void BrowserSignin::RequestSignin(TabContents* tab_contents,
                                  const string16& suggested_email,
                                  const string16& login_message,
                                  SigninDelegate* delegate) {
  CHECK(tab_contents);
  CHECK(delegate);
  // Cancel existing request.
  if (delegate_)
    Cancel();
  delegate_ = delegate;
  suggested_email_ = suggested_email;
  login_message_ = login_message;
  RegisterAuthNotifications();
  ShowSigninTabModal(tab_contents);
}

std::string BrowserSignin::GetSignedInUsername() const {
  std::string username =
      profile_->GetPrefs()->GetString(prefs::kGoogleServicesUsername);
  VLOG(1) << "GetSignedInUsername: " << username;
  return username;
}

void BrowserSignin::Observe(NotificationType type,
                            const NotificationSource& source,
                            const NotificationDetails& details) {
  switch (type.value) {
    case NotificationType::GOOGLE_SIGNIN_SUCCESSFUL: {
      VLOG(1) << "GOOGLE_SIGNIN_SUCCESSFUL";
      if (delegate_)
        delegate_->OnLoginSuccess();
      // Close the dialog.
      OnLoginFinished();
      break;
    }
    case NotificationType::GOOGLE_SIGNIN_FAILED: {
      VLOG(1) << "GOOGLE_SIGNIN_FAILED";
      // The signin failed, refresh the UI with error information.
      html_dialog_ui_delegate_->ReloadUI();
      break;
    }
    default:
      NOTREACHED();
  }
}

void BrowserSignin::Cancel() {
  if (delegate_) {
    delegate_->OnLoginFailure(GoogleServiceAuthError(
        GoogleServiceAuthError::REQUEST_CANCELED));
    GetProfileSyncService()->OnUserCancelledDialog();
  }
  OnLoginFinished();
}

void BrowserSignin::OnLoginFinished() {
  if (html_dialog_ui_delegate_)
    html_dialog_ui_delegate_->ForceDialogClose();
  // The dialog will be deleted by DOMUI due to the dialog close,
  // don't hold a reference.
  html_dialog_ui_delegate_ = NULL;

  if (delegate_) {
    UnregisterAuthNotifications();
    delegate_ = NULL;
  }
}

ProfileSyncService* BrowserSignin::GetProfileSyncService() const {
  return profile_->GetProfileSyncService();
}

BrowserSigninHtml* BrowserSignin::CreateHtmlDialogUI() {
  return new BrowserSigninHtml(this, suggested_email_, login_message_);
}

void BrowserSignin::RegisterAuthNotifications() {
  registrar_.Add(this,
                 NotificationType::GOOGLE_SIGNIN_SUCCESSFUL,
                 Source<Profile>(profile_));
  registrar_.Add(this,
                 NotificationType::GOOGLE_SIGNIN_FAILED,
                 Source<Profile>(profile_));
}

void BrowserSignin::UnregisterAuthNotifications() {
  registrar_.Remove(this,
                    NotificationType::GOOGLE_SIGNIN_SUCCESSFUL,
                    Source<Profile>(profile_));
  registrar_.Remove(this,
                    NotificationType::GOOGLE_SIGNIN_FAILED,
                    Source<Profile>(profile_));
}

void BrowserSignin::ShowSigninTabModal(TabContents* tab_contents) {
//  TODO(johnnyg): Need a linux views implementation for ConstrainedHtmlDialog.
#if defined(OS_WIN) || defined(OS_CHROMEOS) || !defined(TOOLKIT_VIEWS)
  html_dialog_ui_delegate_ = CreateHtmlDialogUI();
  ConstrainedHtmlUI::CreateConstrainedHtmlDialog(profile_,
                                                 html_dialog_ui_delegate_,
                                                 tab_contents);
#endif
}