GN + Android: extract android_standalone_library rule.
[chromium-blink-merge.git] / components / signin / core / browser / about_signin_internals.cc
blob9ff37168b0a5c3bf8f4a1f6ec6ff0cea7be84e07
1 // Copyright (c) 2012 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 "components/signin/core/browser/about_signin_internals.h"
7 #include "base/command_line.h"
8 #include "base/debug/trace_event.h"
9 #include "base/hash.h"
10 #include "base/i18n/time_formatting.h"
11 #include "base/logging.h"
12 #include "base/prefs/pref_service.h"
13 #include "base/profiler/scoped_tracker.h"
14 #include "base/strings/stringprintf.h"
15 #include "base/strings/utf_string_conversions.h"
16 #include "components/signin/core/browser/profile_oauth2_token_service.h"
17 #include "components/signin/core/browser/signin_client.h"
18 #include "components/signin/core/browser/signin_internals_util.h"
19 #include "components/signin/core/browser/signin_manager.h"
20 #include "components/signin/core/common/profile_management_switches.h"
21 #include "components/signin/core/common/signin_switches.h"
22 #include "google_apis/gaia/gaia_auth_fetcher.h"
23 #include "google_apis/gaia/gaia_auth_util.h"
24 #include "google_apis/gaia/gaia_constants.h"
25 #include "google_apis/gaia/gaia_urls.h"
26 #include "net/cookies/canonical_cookie.h"
28 using base::Time;
29 using namespace signin_internals_util;
31 namespace {
33 std::string GetTimeStr(base::Time time) {
34 return base::UTF16ToUTF8(base::TimeFormatShortDateAndTime(time));
37 base::ListValue* AddSection(base::ListValue* parent_list,
38 const std::string& title) {
39 scoped_ptr<base::DictionaryValue> section(new base::DictionaryValue());
40 base::ListValue* section_contents = new base::ListValue();
42 section->SetString("title", title);
43 section->Set("data", section_contents);
44 parent_list->Append(section.release());
45 return section_contents;
48 void AddSectionEntry(base::ListValue* section_list,
49 const std::string& field_name,
50 const std::string& field_status,
51 const std::string& field_time = "") {
52 scoped_ptr<base::DictionaryValue> entry(new base::DictionaryValue());
53 entry->SetString("label", field_name);
54 entry->SetString("status", field_status);
55 entry->SetString("time", field_time);
56 section_list->Append(entry.release());
59 void AddCookieEntry(base::ListValue* accounts_list,
60 const std::string& field_email,
61 const std::string& field_valid) {
62 scoped_ptr<base::DictionaryValue> entry(new base::DictionaryValue());
63 entry->SetString("email", field_email);
64 entry->SetString("valid", field_valid);
65 accounts_list->Append(entry.release());
68 std::string SigninStatusFieldToLabel(UntimedSigninStatusField field) {
69 switch (field) {
70 case USERNAME:
71 return "User Id";
72 case UNTIMED_FIELDS_END:
73 NOTREACHED();
74 return std::string();
76 NOTREACHED();
77 return std::string();
80 #if !defined (OS_CHROMEOS)
81 std::string SigninStatusFieldToLabel(TimedSigninStatusField field) {
82 switch (field) {
83 case SIGNIN_TYPE:
84 return "Type";
85 case AUTHENTICATION_RESULT_RECEIVED:
86 return "Last Authentication Result Received";
87 case REFRESH_TOKEN_RECEIVED:
88 return "Last RefreshToken Received";
89 case GET_USER_INFO_STATUS:
90 return "Last OnGetUserInfo Received";
91 case UBER_TOKEN_STATUS:
92 return "Last OnUberToken Received";
93 case MERGE_SESSION_STATUS:
94 return "Last OnMergeSession Received";
95 case TIMED_FIELDS_END:
96 NOTREACHED();
97 return "Error";
99 NOTREACHED();
100 return "Error";
102 #endif // !defined (OS_CHROMEOS)
104 } // anonymous namespace
106 AboutSigninInternals::AboutSigninInternals(
107 ProfileOAuth2TokenService* token_service,
108 SigninManagerBase* signin_manager)
109 : token_service_(token_service),
110 signin_manager_(signin_manager),
111 client_(NULL) {}
113 AboutSigninInternals::~AboutSigninInternals() {}
115 void AboutSigninInternals::AddSigninObserver(
116 AboutSigninInternals::Observer* observer) {
117 signin_observers_.AddObserver(observer);
120 void AboutSigninInternals::RemoveSigninObserver(
121 AboutSigninInternals::Observer* observer) {
122 signin_observers_.RemoveObserver(observer);
125 void AboutSigninInternals::NotifySigninValueChanged(
126 const UntimedSigninStatusField& field,
127 const std::string& value) {
128 unsigned int field_index = field - UNTIMED_FIELDS_BEGIN;
129 DCHECK(field_index >= 0 &&
130 field_index < signin_status_.untimed_signin_fields.size());
132 signin_status_.untimed_signin_fields[field_index] = value;
134 // Also persist these values in the prefs.
135 const std::string pref_path = SigninStatusFieldToString(field);
136 client_->GetPrefs()->SetString(pref_path.c_str(), value);
138 NotifyObservers();
141 void AboutSigninInternals::NotifySigninValueChanged(
142 const TimedSigninStatusField& field,
143 const std::string& value) {
144 unsigned int field_index = field - TIMED_FIELDS_BEGIN;
145 DCHECK(field_index >= 0 &&
146 field_index < signin_status_.timed_signin_fields.size());
148 Time now = Time::NowFromSystemTime();
149 std::string time_as_str =
150 base::UTF16ToUTF8(base::TimeFormatShortDateAndTime(now));
151 TimedSigninStatusValue timed_value(value, time_as_str);
153 signin_status_.timed_signin_fields[field_index] = timed_value;
155 // Also persist these values in the prefs.
156 const std::string value_pref = SigninStatusFieldToString(field) + ".value";
157 const std::string time_pref = SigninStatusFieldToString(field) + ".time";
158 client_->GetPrefs()->SetString(value_pref.c_str(), value);
159 client_->GetPrefs()->SetString(time_pref.c_str(), time_as_str);
161 NotifyObservers();
164 void AboutSigninInternals::RefreshSigninPrefs() {
165 // Since the AboutSigninInternals has a dependency on the SigninManager
166 // (as seen in the AboutSigninInternalsFactory) the SigninManager can have
167 // the AuthenticatedUsername set before AboutSigninInternals can observe it.
168 // For that scenario, read the AuthenticatedUsername if it exists.
169 if (signin_manager_->IsAuthenticated()) {
170 signin_status_.untimed_signin_fields[USERNAME] =
171 signin_manager_->GetAuthenticatedUsername();
174 // Return if no client exists. Can occur in unit tests.
175 if (!client_)
176 return;
178 PrefService* pref_service = client_->GetPrefs();
179 for (int i = UNTIMED_FIELDS_BEGIN; i < UNTIMED_FIELDS_END; ++i) {
180 const std::string pref_path =
181 SigninStatusFieldToString(static_cast<UntimedSigninStatusField>(i));
183 signin_status_.untimed_signin_fields[i - UNTIMED_FIELDS_BEGIN] =
184 pref_service->GetString(pref_path.c_str());
186 for (int i = TIMED_FIELDS_BEGIN; i < TIMED_FIELDS_END; ++i) {
187 const std::string value_pref =
188 SigninStatusFieldToString(static_cast<TimedSigninStatusField>(i)) +
189 ".value";
190 const std::string time_pref =
191 SigninStatusFieldToString(static_cast<TimedSigninStatusField>(i)) +
192 ".time";
194 TimedSigninStatusValue value(pref_service->GetString(value_pref.c_str()),
195 pref_service->GetString(time_pref.c_str()));
196 signin_status_.timed_signin_fields[i - TIMED_FIELDS_BEGIN] = value;
199 // TODO(rogerta): Get status and timestamps for oauth2 tokens.
201 NotifyObservers();
204 void AboutSigninInternals::Initialize(SigninClient* client) {
205 DCHECK(!client_);
206 client_ = client;
208 RefreshSigninPrefs();
210 signin_manager_->AddSigninDiagnosticsObserver(this);
211 token_service_->AddDiagnosticsObserver(this);
212 cookie_changed_subscription_ = client_->AddCookieChangedCallback(
213 GaiaUrls::GetInstance()->gaia_url(),
214 "LSID",
215 base::Bind(&AboutSigninInternals::OnCookieChanged,
216 base::Unretained(this)));
219 void AboutSigninInternals::Shutdown() {
220 signin_manager_->RemoveSigninDiagnosticsObserver(this);
221 token_service_->RemoveDiagnosticsObserver(this);
222 cookie_changed_subscription_.reset();
225 void AboutSigninInternals::NotifyObservers() {
226 if (!signin_observers_.might_have_observers())
227 return;
229 // TODO(vadimt): Remove ScopedTracker below once crbug.com/422460 is fixed.
230 tracked_objects::ScopedTracker tracking_profile(
231 FROM_HERE_WITH_EXPLICIT_FUNCTION(
232 "422460 AboutSigninInternals::NotifyObservers"));
234 const std::string product_version = client_->GetProductVersion();
236 // TODO(vadimt): Remove ScopedTracker below once crbug.com/422460 is fixed.
237 tracked_objects::ScopedTracker tracking_profile05(
238 FROM_HERE_WITH_EXPLICIT_FUNCTION(
239 "422460 AboutSigninInternals::NotifyObservers 0.5"));
241 scoped_ptr<base::DictionaryValue> signin_status_value =
242 signin_status_.ToValue(product_version);
244 tracked_objects::ScopedTracker tracking_profile1(
245 FROM_HERE_WITH_EXPLICIT_FUNCTION(
246 "422460 AboutSigninInternals::NotifyObservers1"));
248 FOR_EACH_OBSERVER(AboutSigninInternals::Observer,
249 signin_observers_,
250 OnSigninStateChanged(signin_status_value.get()));
253 scoped_ptr<base::DictionaryValue> AboutSigninInternals::GetSigninStatus() {
254 return signin_status_.ToValue(client_->GetProductVersion()).Pass();
257 void AboutSigninInternals::OnAccessTokenRequested(
258 const std::string& account_id,
259 const std::string& consumer_id,
260 const OAuth2TokenService::ScopeSet& scopes) {
261 // TODO(vadimt): Remove ScopedTracker below once crbug.com/422460 is fixed.
262 tracked_objects::ScopedTracker tracking_profile(
263 FROM_HERE_WITH_EXPLICIT_FUNCTION(
264 "422460 AboutSigninInternals::OnAccessTokenRequested"));
266 TokenInfo* token = signin_status_.FindToken(account_id, consumer_id, scopes);
267 if (token) {
268 *token = TokenInfo(consumer_id, scopes);
269 } else {
270 token = new TokenInfo(consumer_id, scopes);
271 signin_status_.token_info_map[account_id].push_back(token);
274 NotifyObservers();
277 void AboutSigninInternals::OnFetchAccessTokenComplete(
278 const std::string& account_id,
279 const std::string& consumer_id,
280 const OAuth2TokenService::ScopeSet& scopes,
281 GoogleServiceAuthError error,
282 base::Time expiration_time) {
283 TokenInfo* token = signin_status_.FindToken(account_id, consumer_id, scopes);
284 if (!token) {
285 DVLOG(1) << "Can't find token: " << account_id << ", " << consumer_id;
286 return;
289 token->receive_time = base::Time::Now();
290 token->error = error;
291 token->expiration_time = expiration_time;
293 NotifyObservers();
296 void AboutSigninInternals::OnTokenRemoved(
297 const std::string& account_id,
298 const OAuth2TokenService::ScopeSet& scopes) {
299 for (size_t i = 0; i < signin_status_.token_info_map[account_id].size();
300 ++i) {
301 TokenInfo* token = signin_status_.token_info_map[account_id][i];
302 if (token->scopes == scopes)
303 token->Invalidate();
305 NotifyObservers();
308 void AboutSigninInternals::OnRefreshTokenReceived(std::string status) {
309 NotifySigninValueChanged(REFRESH_TOKEN_RECEIVED, status);
312 void AboutSigninInternals::OnAuthenticationResultReceived(std::string status) {
313 NotifySigninValueChanged(AUTHENTICATION_RESULT_RECEIVED, status);
316 void AboutSigninInternals::OnCookieChanged(const net::CanonicalCookie& cookie,
317 bool removed) {
318 DCHECK_EQ("LSID", cookie.Name());
319 DCHECK_EQ(GaiaUrls::GetInstance()->gaia_url().host(), cookie.Domain());
320 if (cookie.IsSecure() && cookie.IsHttpOnly()) {
321 GetCookieAccountsAsync();
325 void AboutSigninInternals::GetCookieAccountsAsync() {
326 // Don't bother calling /ListAccounts if no one will observe the response.
327 if (!gaia_fetcher_ && signin_observers_.might_have_observers()) {
328 // There is no list account request in flight.
329 gaia_fetcher_.reset(new GaiaAuthFetcher(
330 this, GaiaConstants::kChromeSource, client_->GetURLRequestContext()));
331 gaia_fetcher_->StartListAccounts();
335 void AboutSigninInternals::OnListAccountsSuccess(const std::string& data) {
336 gaia_fetcher_.reset();
338 // Get account information from response data.
339 std::vector<std::pair<std::string, bool> > gaia_accounts;
340 bool valid_json = gaia::ParseListAccountsData(data, &gaia_accounts);
341 if (!valid_json) {
342 VLOG(1) << "AboutSigninInternals::OnListAccountsSuccess: parsing error";
343 } else {
344 OnListAccountsComplete(gaia_accounts);
348 void AboutSigninInternals::OnListAccountsFailure(
349 const GoogleServiceAuthError& error) {
350 gaia_fetcher_.reset();
351 VLOG(1) << "AboutSigninInternals::OnListAccountsFailure:" << error.ToString();
354 void AboutSigninInternals::OnListAccountsComplete(
355 std::vector<std::pair<std::string, bool> >& gaia_accounts) {
356 base::DictionaryValue signin_status;
357 base::ListValue* cookie_info = new base::ListValue();
358 signin_status.Set("cookie_info", cookie_info);
360 for (size_t i = 0; i < gaia_accounts.size(); ++i) {
361 AddCookieEntry(cookie_info,
362 gaia_accounts[i].first,
363 gaia_accounts[i].second ? "Valid" : "Invalid");
366 if (gaia_accounts.size() == 0)
367 AddCookieEntry(cookie_info, "No Accounts Present.", "");
369 // Update the observers that the cookie's accounts are updated.
370 FOR_EACH_OBSERVER(AboutSigninInternals::Observer,
371 signin_observers_,
372 OnCookieAccountsFetched(&signin_status));
375 AboutSigninInternals::TokenInfo::TokenInfo(
376 const std::string& consumer_id,
377 const OAuth2TokenService::ScopeSet& scopes)
378 : consumer_id(consumer_id),
379 scopes(scopes),
380 request_time(base::Time::Now()),
381 error(GoogleServiceAuthError::AuthErrorNone()),
382 removed_(false) {}
384 AboutSigninInternals::TokenInfo::~TokenInfo() {}
386 bool AboutSigninInternals::TokenInfo::LessThan(const TokenInfo* a,
387 const TokenInfo* b) {
388 return a->consumer_id < b->consumer_id ||
389 (a->consumer_id == b->consumer_id && a->scopes < b->scopes);
392 void AboutSigninInternals::TokenInfo::Invalidate() { removed_ = true; }
394 base::DictionaryValue* AboutSigninInternals::TokenInfo::ToValue() const {
395 scoped_ptr<base::DictionaryValue> token_info(new base::DictionaryValue());
396 token_info->SetString("service", consumer_id);
398 std::string scopes_str;
399 for (OAuth2TokenService::ScopeSet::const_iterator it = scopes.begin();
400 it != scopes.end();
401 ++it) {
402 scopes_str += *it + "<br/>";
404 token_info->SetString("scopes", scopes_str);
405 token_info->SetString("request_time", GetTimeStr(request_time).c_str());
407 if (removed_) {
408 token_info->SetString("status", "Token was revoked.");
409 } else if (!receive_time.is_null()) {
410 if (error == GoogleServiceAuthError::AuthErrorNone()) {
411 bool token_expired = expiration_time < base::Time::Now();
412 std::string status_str = "";
413 if (token_expired)
414 status_str = "<p style=\"color: #ffffff; background-color: #ff0000\">";
415 base::StringAppendF(&status_str,
416 "Received token at %s. Expire at %s",
417 GetTimeStr(receive_time).c_str(),
418 GetTimeStr(expiration_time).c_str());
419 if (token_expired)
420 base::StringAppendF(&status_str, "</p>");
421 token_info->SetString("status", status_str);
422 } else {
423 token_info->SetString(
424 "status",
425 base::StringPrintf("Failure: %s", error.ToString().c_str()));
427 } else {
428 token_info->SetString("status", "Waiting for response");
431 return token_info.release();
434 AboutSigninInternals::SigninStatus::SigninStatus()
435 : untimed_signin_fields(UNTIMED_FIELDS_COUNT),
436 timed_signin_fields(TIMED_FIELDS_COUNT) {}
438 AboutSigninInternals::SigninStatus::~SigninStatus() {
439 for (TokenInfoMap::iterator it = token_info_map.begin();
440 it != token_info_map.end();
441 ++it) {
442 STLDeleteElements(&it->second);
446 AboutSigninInternals::TokenInfo* AboutSigninInternals::SigninStatus::FindToken(
447 const std::string& account_id,
448 const std::string& consumer_id,
449 const OAuth2TokenService::ScopeSet& scopes) {
450 for (size_t i = 0; i < token_info_map[account_id].size(); ++i) {
451 TokenInfo* tmp = token_info_map[account_id][i];
452 if (tmp->consumer_id == consumer_id && tmp->scopes == scopes)
453 return tmp;
455 return NULL;
458 scoped_ptr<base::DictionaryValue> AboutSigninInternals::SigninStatus::ToValue(
459 std::string product_version) {
460 // TODO(vadimt): Remove ScopedTracker below once crbug.com/422460 is fixed.
461 tracked_objects::ScopedTracker tracking_profile1(
462 FROM_HERE_WITH_EXPLICIT_FUNCTION(
463 "422460 AboutSigninInternals::SigninStatus::ToValue1"));
465 scoped_ptr<base::DictionaryValue> signin_status(new base::DictionaryValue());
466 base::ListValue* signin_info = new base::ListValue();
467 signin_status->Set("signin_info", signin_info);
469 // A summary of signin related info first.
470 base::ListValue* basic_info = AddSection(signin_info, "Basic Information");
471 const std::string signin_status_string =
472 untimed_signin_fields[USERNAME - UNTIMED_FIELDS_BEGIN].empty()
473 ? "Not Signed In"
474 : "Signed In";
475 AddSectionEntry(basic_info, "Chrome Version", product_version);
476 AddSectionEntry(basic_info, "Signin Status", signin_status_string);
477 AddSectionEntry(basic_info, "Web Based Signin Enabled?",
478 switches::IsEnableWebBasedSignin() == true ? "True" : "False");
479 AddSectionEntry(basic_info, "Webview Based Signin Enabled?",
480 switches::IsEnableWebviewBasedSignin() == true ? "True" : "False");
481 AddSectionEntry(basic_info, "New Avatar Menu Enabled?",
482 switches::IsNewAvatarMenu() == true ? "True" : "False");
483 AddSectionEntry(basic_info, "New Profile Management Enabled?",
484 switches::IsNewProfileManagement() == true ? "True" : "False");
485 AddSectionEntry(basic_info, "Account Consistency Enabled?",
486 switches::IsEnableAccountConsistency() == true ? "True" : "False");
488 // TODO(vadimt): Remove ScopedTracker below once crbug.com/422460 is fixed.
489 tracked_objects::ScopedTracker tracking_profile2(
490 FROM_HERE_WITH_EXPLICIT_FUNCTION(
491 "422460 AboutSigninInternals::SigninStatus::ToValue2"));
493 // Only add username. SID and LSID have moved to tokens section.
494 const std::string field =
495 SigninStatusFieldToLabel(static_cast<UntimedSigninStatusField>(USERNAME));
496 AddSectionEntry(basic_info,
497 field,
498 untimed_signin_fields[USERNAME - UNTIMED_FIELDS_BEGIN]);
500 #if !defined(OS_CHROMEOS)
501 // TODO(vadimt): Remove ScopedTracker below once crbug.com/422460 is fixed.
502 tracked_objects::ScopedTracker tracking_profile3(
503 FROM_HERE_WITH_EXPLICIT_FUNCTION(
504 "422460 AboutSigninInternals::SigninStatus::ToValue3"));
506 // Time and status information of the possible sign in types.
507 base::ListValue* detailed_info =
508 AddSection(signin_info, "Last Signin Details");
509 for (int i = TIMED_FIELDS_BEGIN; i < TIMED_FIELDS_END; ++i) {
510 const std::string status_field_label =
511 SigninStatusFieldToLabel(static_cast<TimedSigninStatusField>(i));
513 AddSectionEntry(detailed_info,
514 status_field_label,
515 timed_signin_fields[i - TIMED_FIELDS_BEGIN].first,
516 timed_signin_fields[i - TIMED_FIELDS_BEGIN].second);
518 #endif // !defined(OS_CHROMEOS)
520 // TODO(vadimt): Remove ScopedTracker below once crbug.com/422460 is fixed.
521 tracked_objects::ScopedTracker tracking_profile4(
522 FROM_HERE_WITH_EXPLICIT_FUNCTION(
523 "422460 AboutSigninInternals::SigninStatus::ToValue4"));
525 // Token information for all services.
526 base::ListValue* token_info = new base::ListValue();
527 signin_status->Set("token_info", token_info);
528 for (TokenInfoMap::iterator it = token_info_map.begin();
529 it != token_info_map.end();
530 ++it) {
531 // TODO(vadimt): Remove ScopedTracker below once crbug.com/422460 is fixed.
532 tracked_objects::ScopedTracker tracking_profile41(
533 FROM_HERE_WITH_EXPLICIT_FUNCTION(
534 "422460 AboutSigninInternals::SigninStatus::ToValue41"));
536 base::ListValue* token_details = AddSection(token_info, it->first);
538 // TODO(vadimt): Remove ScopedTracker below once crbug.com/422460 is fixed.
539 tracked_objects::ScopedTracker tracking_profile42(
540 FROM_HERE_WITH_EXPLICIT_FUNCTION(
541 "422460 AboutSigninInternals::SigninStatus::ToValue42"));
543 std::sort(it->second.begin(), it->second.end(), TokenInfo::LessThan);
544 const std::vector<TokenInfo*>& tokens = it->second;
546 // TODO(vadimt): Remove ScopedTracker below once crbug.com/422460 is fixed.
547 tracked_objects::ScopedTracker tracking_profile43(
548 FROM_HERE_WITH_EXPLICIT_FUNCTION(
549 "422460 AboutSigninInternals::SigninStatus::ToValue43"));
551 for (size_t i = 0; i < tokens.size(); ++i) {
552 base::DictionaryValue* token_info = tokens[i]->ToValue();
553 token_details->Append(token_info);
557 return signin_status.Pass();