Revert of Add button to add new FSP services to Files app. (patchset #8 id:140001...
[chromium-blink-merge.git] / chrome / browser / supervised_user / supervised_user_service.cc
blob440fa1cc8fd6534d1e29926d37abfa6542cf0030
1 // Copyright 2014 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/supervised_user/supervised_user_service.h"
7 #include "base/command_line.h"
8 #include "base/files/file_path.h"
9 #include "base/memory/ref_counted.h"
10 #include "base/prefs/pref_service.h"
11 #include "base/strings/utf_string_conversions.h"
12 #include "base/version.h"
13 #include "chrome/browser/browser_process.h"
14 #include "chrome/browser/component_updater/supervised_user_whitelist_installer.h"
15 #include "chrome/browser/profiles/profile.h"
16 #include "chrome/browser/profiles/profile_info_cache.h"
17 #include "chrome/browser/profiles/profile_manager.h"
18 #include "chrome/browser/signin/profile_oauth2_token_service_factory.h"
19 #include "chrome/browser/signin/signin_manager_factory.h"
20 #include "chrome/browser/supervised_user/experimental/supervised_user_blacklist_downloader.h"
21 #include "chrome/browser/supervised_user/legacy/custodian_profile_downloader_service.h"
22 #include "chrome/browser/supervised_user/legacy/custodian_profile_downloader_service_factory.h"
23 #include "chrome/browser/supervised_user/legacy/permission_request_creator_sync.h"
24 #include "chrome/browser/supervised_user/legacy/supervised_user_pref_mapping_service.h"
25 #include "chrome/browser/supervised_user/legacy/supervised_user_pref_mapping_service_factory.h"
26 #include "chrome/browser/supervised_user/legacy/supervised_user_registration_utility.h"
27 #include "chrome/browser/supervised_user/legacy/supervised_user_shared_settings_service_factory.h"
28 #include "chrome/browser/supervised_user/supervised_user_constants.h"
29 #include "chrome/browser/supervised_user/supervised_user_service_observer.h"
30 #include "chrome/browser/supervised_user/supervised_user_settings_service.h"
31 #include "chrome/browser/supervised_user/supervised_user_settings_service_factory.h"
32 #include "chrome/browser/supervised_user/supervised_user_site_list.h"
33 #include "chrome/browser/supervised_user/supervised_user_whitelist_service.h"
34 #include "chrome/browser/sync/profile_sync_service.h"
35 #include "chrome/browser/sync/profile_sync_service_factory.h"
36 #include "chrome/browser/ui/browser.h"
37 #include "chrome/browser/ui/browser_list.h"
38 #include "chrome/common/chrome_switches.h"
39 #include "chrome/common/pref_names.h"
40 #include "chrome/grit/generated_resources.h"
41 #include "components/pref_registry/pref_registry_syncable.h"
42 #include "components/signin/core/browser/profile_oauth2_token_service.h"
43 #include "components/signin/core/browser/signin_manager.h"
44 #include "components/signin/core/browser/signin_manager_base.h"
45 #include "content/public/browser/browser_thread.h"
46 #include "content/public/browser/user_metrics.h"
47 #include "ui/base/l10n/l10n_util.h"
49 #if defined(OS_CHROMEOS)
50 #include "chrome/browser/chromeos/login/users/chrome_user_manager.h"
51 #include "chrome/browser/chromeos/login/users/supervised_user_manager.h"
52 #include "components/user_manager/user_manager.h"
53 #endif
55 #if defined(ENABLE_EXTENSIONS)
56 #include "extensions/browser/extension_registry.h"
57 #include "extensions/browser/extension_system.h"
58 #endif
60 #if defined(ENABLE_THEMES)
61 #include "chrome/browser/themes/theme_service.h"
62 #include "chrome/browser/themes/theme_service_factory.h"
63 #endif
65 using base::DictionaryValue;
66 using base::UserMetricsAction;
67 using content::BrowserThread;
69 namespace {
71 const char* const kCustodianInfoPrefs[] = {
72 prefs::kSupervisedUserCustodianName,
73 prefs::kSupervisedUserCustodianEmail,
74 prefs::kSupervisedUserCustodianProfileImageURL,
75 prefs::kSupervisedUserCustodianProfileURL,
76 prefs::kSupervisedUserSecondCustodianName,
77 prefs::kSupervisedUserSecondCustodianEmail,
78 prefs::kSupervisedUserSecondCustodianProfileImageURL,
79 prefs::kSupervisedUserSecondCustodianProfileURL,
82 void CreateURLAccessRequest(
83 const GURL& url,
84 PermissionRequestCreator* creator,
85 const SupervisedUserService::SuccessCallback& callback) {
86 creator->CreateURLAccessRequest(url, callback);
89 void CreateExtensionUpdateRequest(
90 const std::string& id,
91 PermissionRequestCreator* creator,
92 const SupervisedUserService::SuccessCallback& callback) {
93 creator->CreateExtensionUpdateRequest(id, callback);
96 #if defined(ENABLE_EXTENSIONS)
97 enum ExtensionState {
98 EXTENSION_FORCED,
99 EXTENSION_BLOCKED,
100 EXTENSION_ALLOWED
103 ExtensionState GetExtensionState(const extensions::Extension* extension) {
104 if (extension->is_theme())
105 return EXTENSION_ALLOWED;
107 bool was_installed_by_default = extension->was_installed_by_default();
108 bool was_installed_by_custodian = extension->was_installed_by_custodian();
109 #if defined(OS_CHROMEOS)
110 // On Chrome OS all external sources are controlled by us so it means that
111 // they are "default". Method was_installed_by_default returns false because
112 // extensions creation flags are ignored in case of default extensions with
113 // update URL(the flags aren't passed to OnExternalExtensionUpdateUrlFound).
114 // TODO(dpolukhin): remove this Chrome OS specific code as soon as creation
115 // flags are not ignored.
116 was_installed_by_default =
117 extensions::Manifest::IsExternalLocation(extension->location());
118 #endif
119 if (extensions::Manifest::IsComponentLocation(extension->location()) ||
120 was_installed_by_default ||
121 was_installed_by_custodian) {
122 // Enforce default extensions as well as custodian-installed extensions
123 // (if we'd allow the supervised user to uninstall them, there'd be no way
124 // to get them back).
125 return EXTENSION_FORCED;
128 return EXTENSION_BLOCKED;
130 #endif
132 } // namespace
134 base::FilePath SupervisedUserService::Delegate::GetBlacklistPath() const {
135 return base::FilePath();
138 GURL SupervisedUserService::Delegate::GetBlacklistURL() const {
139 return GURL();
142 std::string SupervisedUserService::Delegate::GetSafeSitesCx() const {
143 return std::string();
146 SupervisedUserService::URLFilterContext::URLFilterContext()
147 : ui_url_filter_(new SupervisedUserURLFilter),
148 io_url_filter_(new SupervisedUserURLFilter) {}
149 SupervisedUserService::URLFilterContext::~URLFilterContext() {}
151 SupervisedUserURLFilter*
152 SupervisedUserService::URLFilterContext::ui_url_filter() const {
153 return ui_url_filter_.get();
156 SupervisedUserURLFilter*
157 SupervisedUserService::URLFilterContext::io_url_filter() const {
158 return io_url_filter_.get();
161 void SupervisedUserService::URLFilterContext::SetDefaultFilteringBehavior(
162 SupervisedUserURLFilter::FilteringBehavior behavior) {
163 ui_url_filter_->SetDefaultFilteringBehavior(behavior);
164 BrowserThread::PostTask(
165 BrowserThread::IO,
166 FROM_HERE,
167 base::Bind(&SupervisedUserURLFilter::SetDefaultFilteringBehavior,
168 io_url_filter_.get(), behavior));
171 void SupervisedUserService::URLFilterContext::LoadWhitelists(
172 const std::vector<scoped_refptr<SupervisedUserSiteList> >& site_lists) {
173 ui_url_filter_->LoadWhitelists(site_lists);
174 BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
175 base::Bind(&SupervisedUserURLFilter::LoadWhitelists,
176 io_url_filter_, site_lists));
179 void SupervisedUserService::URLFilterContext::LoadBlacklist(
180 const base::FilePath& path,
181 const base::Closure& callback) {
182 // For now, support loading only once. If we want to support re-load, we'll
183 // have to clear the blacklist pointer in the url filters first.
184 DCHECK_EQ(0u, blacklist_.GetEntryCount());
185 blacklist_.ReadFromFile(
186 path,
187 base::Bind(&SupervisedUserService::URLFilterContext::OnBlacklistLoaded,
188 base::Unretained(this), callback));
191 void SupervisedUserService::URLFilterContext::SetManualHosts(
192 scoped_ptr<std::map<std::string, bool> > host_map) {
193 ui_url_filter_->SetManualHosts(host_map.get());
194 BrowserThread::PostTask(
195 BrowserThread::IO,
196 FROM_HERE,
197 base::Bind(&SupervisedUserURLFilter::SetManualHosts,
198 io_url_filter_, base::Owned(host_map.release())));
201 void SupervisedUserService::URLFilterContext::SetManualURLs(
202 scoped_ptr<std::map<GURL, bool> > url_map) {
203 ui_url_filter_->SetManualURLs(url_map.get());
204 BrowserThread::PostTask(
205 BrowserThread::IO,
206 FROM_HERE,
207 base::Bind(&SupervisedUserURLFilter::SetManualURLs,
208 io_url_filter_, base::Owned(url_map.release())));
211 void SupervisedUserService::URLFilterContext::Clear() {
212 ui_url_filter_->Clear();
213 BrowserThread::PostTask(
214 BrowserThread::IO,
215 FROM_HERE,
216 base::Bind(&SupervisedUserURLFilter::Clear,
217 io_url_filter_));
220 void SupervisedUserService::URLFilterContext::OnBlacklistLoaded(
221 const base::Closure& callback) {
222 ui_url_filter_->SetBlacklist(&blacklist_);
223 BrowserThread::PostTask(
224 BrowserThread::IO,
225 FROM_HERE,
226 base::Bind(&SupervisedUserURLFilter::SetBlacklist,
227 io_url_filter_,
228 &blacklist_));
229 callback.Run();
232 void SupervisedUserService::URLFilterContext::InitAsyncURLChecker(
233 const scoped_refptr<net::URLRequestContextGetter>& context,
234 const std::string& cx) {
235 ui_url_filter_->InitAsyncURLChecker(context.get(), cx);
236 BrowserThread::PostTask(
237 BrowserThread::IO,
238 FROM_HERE,
239 base::Bind(&SupervisedUserURLFilter::InitAsyncURLChecker,
240 io_url_filter_, context, cx));
243 SupervisedUserService::SupervisedUserService(Profile* profile)
244 : includes_sync_sessions_type_(true),
245 profile_(profile),
246 active_(false),
247 delegate_(NULL),
248 waiting_for_sync_initialization_(false),
249 is_profile_active_(false),
250 did_init_(false),
251 did_shutdown_(false),
252 weak_ptr_factory_(this) {
253 url_filter_context_.ui_url_filter()->AddObserver(this);
256 SupervisedUserService::~SupervisedUserService() {
257 DCHECK(!did_init_ || did_shutdown_);
258 url_filter_context_.ui_url_filter()->RemoveObserver(this);
261 void SupervisedUserService::Shutdown() {
262 if (!did_init_)
263 return;
264 DCHECK(!did_shutdown_);
265 did_shutdown_ = true;
266 if (ProfileIsSupervised()) {
267 content::RecordAction(UserMetricsAction("ManagedUsers_QuitBrowser"));
269 SetActive(false);
271 ProfileSyncService* sync_service =
272 ProfileSyncServiceFactory::GetForProfile(profile_);
273 // Can be null in tests.
274 if (sync_service)
275 sync_service->RemovePreferenceProvider(this);
278 bool SupervisedUserService::ProfileIsSupervised() const {
279 return profile_->IsSupervised();
282 void SupervisedUserService::OnCustodianInfoChanged() {
283 FOR_EACH_OBSERVER(
284 SupervisedUserServiceObserver, observer_list_, OnCustodianInfoChanged());
287 // static
288 void SupervisedUserService::RegisterProfilePrefs(
289 user_prefs::PrefRegistrySyncable* registry) {
290 registry->RegisterDictionaryPref(
291 prefs::kSupervisedUserManualHosts,
292 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
293 registry->RegisterDictionaryPref(
294 prefs::kSupervisedUserManualURLs,
295 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
296 registry->RegisterIntegerPref(
297 prefs::kDefaultSupervisedUserFilteringBehavior,
298 SupervisedUserURLFilter::ALLOW,
299 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
300 registry->RegisterBooleanPref(prefs::kSupervisedUserCreationAllowed, true,
301 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
302 for (const char* pref : kCustodianInfoPrefs) {
303 registry->RegisterStringPref(pref, std::string(),
304 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
308 void SupervisedUserService::SetDelegate(Delegate* delegate) {
309 if (delegate) {
310 // Changing delegates isn't allowed.
311 DCHECK(!delegate_);
312 } else {
313 // If the delegate is removed, deactivate first to give the old delegate a
314 // chance to clean up.
315 SetActive(false);
317 delegate_ = delegate;
320 scoped_refptr<const SupervisedUserURLFilter>
321 SupervisedUserService::GetURLFilterForIOThread() {
322 return url_filter_context_.io_url_filter();
325 SupervisedUserURLFilter* SupervisedUserService::GetURLFilterForUIThread() {
326 return url_filter_context_.ui_url_filter();
329 SupervisedUserWhitelistService* SupervisedUserService::GetWhitelistService() {
330 return whitelist_service_.get();
333 std::string SupervisedUserService::GetCustodianEmailAddress() const {
334 std::string custodian_email = profile_->GetPrefs()->GetString(
335 prefs::kSupervisedUserCustodianEmail);
336 #if defined(OS_CHROMEOS)
337 if (custodian_email.empty()) {
338 custodian_email = chromeos::ChromeUserManager::Get()
339 ->GetSupervisedUserManager()
340 ->GetManagerDisplayEmail(
341 user_manager::UserManager::Get()->GetActiveUser()->email());
343 #endif
344 return custodian_email;
347 std::string SupervisedUserService::GetCustodianName() const {
348 std::string name = profile_->GetPrefs()->GetString(
349 prefs::kSupervisedUserCustodianName);
350 #if defined(OS_CHROMEOS)
351 if (name.empty()) {
352 name = base::UTF16ToUTF8(chromeos::ChromeUserManager::Get()
353 ->GetSupervisedUserManager()
354 ->GetManagerDisplayName(
355 user_manager::UserManager::Get()->GetActiveUser()->email()));
357 #endif
358 return name.empty() ? GetCustodianEmailAddress() : name;
361 std::string SupervisedUserService::GetSecondCustodianEmailAddress() const {
362 return profile_->GetPrefs()->GetString(
363 prefs::kSupervisedUserSecondCustodianEmail);
366 std::string SupervisedUserService::GetSecondCustodianName() const {
367 std::string name = profile_->GetPrefs()->GetString(
368 prefs::kSupervisedUserSecondCustodianName);
369 return name.empty() ? GetSecondCustodianEmailAddress() : name;
372 void SupervisedUserService::AddNavigationBlockedCallback(
373 const NavigationBlockedCallback& callback) {
374 navigation_blocked_callbacks_.push_back(callback);
377 void SupervisedUserService::DidBlockNavigation(
378 content::WebContents* web_contents) {
379 for (const auto& callback : navigation_blocked_callbacks_)
380 callback.Run(web_contents);
383 void SupervisedUserService::AddObserver(
384 SupervisedUserServiceObserver* observer) {
385 observer_list_.AddObserver(observer);
388 void SupervisedUserService::RemoveObserver(
389 SupervisedUserServiceObserver* observer) {
390 observer_list_.RemoveObserver(observer);
393 void SupervisedUserService::AddPermissionRequestCreator(
394 scoped_ptr<PermissionRequestCreator> creator) {
395 permissions_creators_.push_back(creator.release());
398 syncer::ModelTypeSet SupervisedUserService::GetPreferredDataTypes() const {
399 if (!ProfileIsSupervised())
400 return syncer::ModelTypeSet();
402 syncer::ModelTypeSet result;
403 if (IncludesSyncSessionsType())
404 result.Put(syncer::SESSIONS);
405 result.Put(syncer::EXTENSIONS);
406 result.Put(syncer::EXTENSION_SETTINGS);
407 result.Put(syncer::APPS);
408 result.Put(syncer::APP_SETTINGS);
409 result.Put(syncer::APP_NOTIFICATIONS);
410 result.Put(syncer::APP_LIST);
411 return result;
414 void SupervisedUserService::OnHistoryRecordingStateChanged() {
415 bool record_history =
416 profile_->GetPrefs()->GetBoolean(prefs::kRecordHistory);
417 includes_sync_sessions_type_ = record_history;
418 ProfileSyncServiceFactory::GetForProfile(profile_)
419 ->ReconfigureDatatypeManager();
422 bool SupervisedUserService::IncludesSyncSessionsType() const {
423 return includes_sync_sessions_type_;
426 void SupervisedUserService::OnStateChanged() {
427 ProfileSyncService* service =
428 ProfileSyncServiceFactory::GetForProfile(profile_);
429 if (waiting_for_sync_initialization_ && service->backend_initialized() &&
430 service->backend_mode() == ProfileSyncService::SYNC) {
431 waiting_for_sync_initialization_ = false;
432 service->RemoveObserver(this);
433 FinishSetupSync();
434 return;
437 DLOG_IF(ERROR, service->GetAuthError().state() ==
438 GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS)
439 << "Credentials rejected";
442 void SupervisedUserService::SetupSync() {
443 StartSetupSync();
444 FinishSetupSyncWhenReady();
447 void SupervisedUserService::StartSetupSync() {
448 // Tell the sync service that setup is in progress so we don't start syncing
449 // until we've finished configuration.
450 ProfileSyncServiceFactory::GetForProfile(profile_)->SetSetupInProgress(true);
453 void SupervisedUserService::FinishSetupSyncWhenReady() {
454 // If we're already waiting for the Sync backend, there's nothing to do here.
455 if (waiting_for_sync_initialization_)
456 return;
458 // Continue in FinishSetupSync() once the Sync backend has been initialized.
459 ProfileSyncService* service =
460 ProfileSyncServiceFactory::GetForProfile(profile_);
461 if (service->backend_initialized() &&
462 service->backend_mode() == ProfileSyncService::SYNC) {
463 FinishSetupSync();
464 } else {
465 service->AddObserver(this);
466 waiting_for_sync_initialization_ = true;
470 void SupervisedUserService::FinishSetupSync() {
471 ProfileSyncService* service =
472 ProfileSyncServiceFactory::GetForProfile(profile_);
473 DCHECK(service->backend_initialized());
474 DCHECK(service->backend_mode() == ProfileSyncService::SYNC);
476 // Sync nothing (except types which are set via GetPreferredDataTypes).
477 bool sync_everything = false;
478 syncer::ModelTypeSet synced_datatypes;
479 service->OnUserChoseDatatypes(sync_everything, synced_datatypes);
481 // Notify ProfileSyncService that we are done with configuration.
482 service->SetSetupInProgress(false);
483 service->SetSyncSetupCompleted();
486 #if defined(ENABLE_EXTENSIONS)
487 std::string SupervisedUserService::GetDebugPolicyProviderName() const {
488 // Save the string space in official builds.
489 #ifdef NDEBUG
490 NOTREACHED();
491 return std::string();
492 #else
493 return "Supervised User Service";
494 #endif
497 bool SupervisedUserService::UserMayLoad(const extensions::Extension* extension,
498 base::string16* error) const {
499 DCHECK(ProfileIsSupervised());
500 ExtensionState result = GetExtensionState(extension);
501 bool may_load = (result != EXTENSION_BLOCKED);
502 if (!may_load && error)
503 *error = l10n_util::GetStringUTF16(IDS_EXTENSIONS_LOCKED_SUPERVISED_USER);
504 return may_load;
507 bool SupervisedUserService::UserMayModifySettings(
508 const extensions::Extension* extension,
509 base::string16* error) const {
510 DCHECK(ProfileIsSupervised());
511 ExtensionState result = GetExtensionState(extension);
512 bool may_modify = (result == EXTENSION_ALLOWED);
513 if (!may_modify && error)
514 *error = l10n_util::GetStringUTF16(IDS_EXTENSIONS_LOCKED_SUPERVISED_USER);
515 return may_modify;
518 // Note: Having MustRemainInstalled always say "true" for custodian-installed
519 // extensions does NOT prevent remote uninstalls (which is a bit unexpected, but
520 // exactly what we want).
521 bool SupervisedUserService::MustRemainInstalled(
522 const extensions::Extension* extension,
523 base::string16* error) const {
524 DCHECK(ProfileIsSupervised());
525 ExtensionState result = GetExtensionState(extension);
526 bool may_not_uninstall = (result == EXTENSION_FORCED);
527 if (may_not_uninstall && error)
528 *error = l10n_util::GetStringUTF16(IDS_EXTENSIONS_LOCKED_SUPERVISED_USER);
529 return may_not_uninstall;
532 void SupervisedUserService::SetExtensionsActive() {
533 extensions::ExtensionSystem* extension_system =
534 extensions::ExtensionSystem::Get(profile_);
535 extensions::ManagementPolicy* management_policy =
536 extension_system->management_policy();
538 if (management_policy) {
539 if (active_)
540 management_policy->RegisterProvider(this);
541 else
542 management_policy->UnregisterProvider(this);
545 #endif // defined(ENABLE_EXTENSIONS)
547 SupervisedUserSettingsService* SupervisedUserService::GetSettingsService() {
548 return SupervisedUserSettingsServiceFactory::GetForProfile(profile_);
551 size_t SupervisedUserService::FindEnabledPermissionRequestCreator(
552 size_t start) {
553 for (size_t i = start; i < permissions_creators_.size(); ++i) {
554 if (permissions_creators_[i]->IsEnabled())
555 return i;
557 return permissions_creators_.size();
560 void SupervisedUserService::AddPermissionRequestInternal(
561 const CreatePermissionRequestCallback& create_request,
562 const SuccessCallback& callback,
563 size_t index) {
564 // Find a permission request creator that is enabled.
565 size_t next_index = FindEnabledPermissionRequestCreator(index);
566 if (next_index >= permissions_creators_.size()) {
567 callback.Run(false);
568 return;
571 create_request.Run(
572 permissions_creators_[next_index],
573 base::Bind(&SupervisedUserService::OnPermissionRequestIssued,
574 weak_ptr_factory_.GetWeakPtr(), create_request,
575 callback, next_index));
578 void SupervisedUserService::OnPermissionRequestIssued(
579 const CreatePermissionRequestCallback& create_request,
580 const SuccessCallback& callback,
581 size_t index,
582 bool success) {
583 if (success) {
584 callback.Run(true);
585 return;
588 AddPermissionRequestInternal(create_request, callback, index + 1);
591 void SupervisedUserService::OnSupervisedUserIdChanged() {
592 SetActive(ProfileIsSupervised());
595 void SupervisedUserService::OnDefaultFilteringBehaviorChanged() {
596 DCHECK(ProfileIsSupervised());
598 int behavior_value = profile_->GetPrefs()->GetInteger(
599 prefs::kDefaultSupervisedUserFilteringBehavior);
600 SupervisedUserURLFilter::FilteringBehavior behavior =
601 SupervisedUserURLFilter::BehaviorFromInt(behavior_value);
602 url_filter_context_.SetDefaultFilteringBehavior(behavior);
604 FOR_EACH_OBSERVER(
605 SupervisedUserServiceObserver, observer_list_, OnURLFilterChanged());
608 void SupervisedUserService::OnSiteListsChanged(
609 const std::vector<scoped_refptr<SupervisedUserSiteList> >& site_lists) {
610 url_filter_context_.LoadWhitelists(site_lists);
613 void SupervisedUserService::OnSiteListUpdated() {
614 FOR_EACH_OBSERVER(
615 SupervisedUserServiceObserver, observer_list_, OnURLFilterChanged());
618 void SupervisedUserService::LoadBlacklist(const base::FilePath& path,
619 const GURL& url) {
620 if (!url.is_valid()) {
621 LoadBlacklistFromFile(path);
622 return;
625 DCHECK(!blacklist_downloader_);
626 blacklist_downloader_.reset(new SupervisedUserBlacklistDownloader(
627 url,
628 path,
629 profile_->GetRequestContext(),
630 base::Bind(&SupervisedUserService::OnBlacklistDownloadDone,
631 base::Unretained(this), path)));
634 void SupervisedUserService::LoadBlacklistFromFile(const base::FilePath& path) {
635 // This object is guaranteed to outlive the URLFilterContext, so we can bind a
636 // raw pointer to it in the callback.
637 url_filter_context_.LoadBlacklist(
638 path, base::Bind(&SupervisedUserService::OnBlacklistLoaded,
639 base::Unretained(this)));
642 void SupervisedUserService::OnBlacklistDownloadDone(const base::FilePath& path,
643 bool success) {
644 if (success) {
645 LoadBlacklistFromFile(path);
646 } else {
647 LOG(WARNING) << "Blacklist download failed";
649 blacklist_downloader_.reset();
652 void SupervisedUserService::OnBlacklistLoaded() {
653 FOR_EACH_OBSERVER(
654 SupervisedUserServiceObserver, observer_list_, OnURLFilterChanged());
657 bool SupervisedUserService::AccessRequestsEnabled() {
658 return FindEnabledPermissionRequestCreator(0) < permissions_creators_.size();
661 void SupervisedUserService::AddURLAccessRequest(
662 const GURL& url,
663 const SuccessCallback& callback) {
664 AddPermissionRequestInternal(
665 base::Bind(CreateURLAccessRequest,
666 SupervisedUserURLFilter::Normalize(url)),
667 callback, 0);
670 void SupervisedUserService::AddExtensionUpdateRequest(
671 const std::string& extension_id,
672 const base::Version& version,
673 const SuccessCallback& callback) {
674 std::string id = extension_id + ":" + version.GetString();
675 AddPermissionRequestInternal(
676 base::Bind(CreateExtensionUpdateRequest, id),
677 callback, 0);
680 void SupervisedUserService::InitSync(const std::string& refresh_token) {
681 StartSetupSync();
683 ProfileOAuth2TokenService* token_service =
684 ProfileOAuth2TokenServiceFactory::GetForProfile(profile_);
685 token_service->UpdateCredentials(supervised_users::kSupervisedUserPseudoEmail,
686 refresh_token);
688 FinishSetupSyncWhenReady();
691 void SupervisedUserService::Init() {
692 DCHECK(!did_init_);
693 did_init_ = true;
694 DCHECK(GetSettingsService()->IsReady());
696 pref_change_registrar_.Init(profile_->GetPrefs());
697 pref_change_registrar_.Add(
698 prefs::kSupervisedUserId,
699 base::Bind(&SupervisedUserService::OnSupervisedUserIdChanged,
700 base::Unretained(this)));
701 pref_change_registrar_.Add(
702 prefs::kRecordHistory,
703 base::Bind(&SupervisedUserService::OnHistoryRecordingStateChanged,
704 base::Unretained(this)));
706 ProfileSyncService* sync_service =
707 ProfileSyncServiceFactory::GetForProfile(profile_);
708 // Can be null in tests.
709 if (sync_service)
710 sync_service->AddPreferenceProvider(this);
712 std::string client_id = component_updater::SupervisedUserWhitelistInstaller::
713 ClientIdForProfilePath(profile_->GetPath());
714 whitelist_service_.reset(new SupervisedUserWhitelistService(
715 profile_->GetPrefs(),
716 g_browser_process->supervised_user_whitelist_installer(), client_id));
717 whitelist_service_->AddSiteListsChangedCallback(
718 base::Bind(&SupervisedUserService::OnSiteListsChanged,
719 weak_ptr_factory_.GetWeakPtr()));
721 SetActive(ProfileIsSupervised());
724 void SupervisedUserService::SetActive(bool active) {
725 if (active_ == active)
726 return;
727 active_ = active;
729 if (!delegate_ || !delegate_->SetActive(active_)) {
730 if (active_) {
731 SupervisedUserPrefMappingServiceFactory::GetForBrowserContext(profile_)
732 ->Init();
734 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
735 if (command_line->HasSwitch(switches::kSupervisedUserSyncToken)) {
736 InitSync(
737 command_line->GetSwitchValueASCII(
738 switches::kSupervisedUserSyncToken));
741 ProfileOAuth2TokenService* token_service =
742 ProfileOAuth2TokenServiceFactory::GetForProfile(profile_);
743 token_service->LoadCredentials(
744 supervised_users::kSupervisedUserPseudoEmail);
746 permissions_creators_.push_back(new PermissionRequestCreatorSync(
747 GetSettingsService(),
748 SupervisedUserSharedSettingsServiceFactory::GetForBrowserContext(
749 profile_),
750 ProfileSyncServiceFactory::GetForProfile(profile_),
751 GetSupervisedUserName(),
752 profile_->GetPrefs()->GetString(prefs::kSupervisedUserId)));
754 SetupSync();
758 // Now activate/deactivate anything not handled by the delegate yet.
760 #if defined(ENABLE_THEMES)
761 // Re-set the default theme to turn the SU theme on/off.
762 ThemeService* theme_service = ThemeServiceFactory::GetForProfile(profile_);
763 if (theme_service->UsingDefaultTheme() || theme_service->UsingSystemTheme()) {
764 ThemeServiceFactory::GetForProfile(profile_)->UseDefaultTheme();
766 #endif
768 ProfileSyncService* sync_service =
769 ProfileSyncServiceFactory::GetForProfile(profile_);
770 sync_service->SetEncryptEverythingAllowed(!active_);
772 GetSettingsService()->SetActive(active_);
774 #if defined(ENABLE_EXTENSIONS)
775 SetExtensionsActive();
776 #endif
778 if (active_) {
779 pref_change_registrar_.Add(
780 prefs::kDefaultSupervisedUserFilteringBehavior,
781 base::Bind(&SupervisedUserService::OnDefaultFilteringBehaviorChanged,
782 base::Unretained(this)));
783 pref_change_registrar_.Add(prefs::kSupervisedUserManualHosts,
784 base::Bind(&SupervisedUserService::UpdateManualHosts,
785 base::Unretained(this)));
786 pref_change_registrar_.Add(prefs::kSupervisedUserManualURLs,
787 base::Bind(&SupervisedUserService::UpdateManualURLs,
788 base::Unretained(this)));
789 for (const char* pref : kCustodianInfoPrefs) {
790 pref_change_registrar_.Add(pref,
791 base::Bind(&SupervisedUserService::OnCustodianInfoChanged,
792 base::Unretained(this)));
795 // Initialize the filter.
796 OnDefaultFilteringBehaviorChanged();
797 whitelist_service_->Init();
798 UpdateManualHosts();
799 UpdateManualURLs();
800 bool use_blacklist = base::CommandLine::ForCurrentProcess()->HasSwitch(
801 switches::kEnableSupervisedUserBlacklist);
802 if (delegate_ && use_blacklist) {
803 base::FilePath blacklist_path = delegate_->GetBlacklistPath();
804 if (!blacklist_path.empty())
805 LoadBlacklist(blacklist_path, delegate_->GetBlacklistURL());
807 bool use_safesites = base::CommandLine::ForCurrentProcess()->HasSwitch(
808 switches::kEnableSupervisedUserSafeSites);
809 if (delegate_ && use_safesites) {
810 const std::string& cx = delegate_->GetSafeSitesCx();
811 if (!cx.empty()) {
812 url_filter_context_.InitAsyncURLChecker(
813 profile_->GetRequestContext(), cx);
817 #if !defined(OS_ANDROID)
818 // TODO(bauerb): Get rid of the platform-specific #ifdef here.
819 // http://crbug.com/313377
820 BrowserList::AddObserver(this);
821 #endif
822 } else {
823 permissions_creators_.clear();
825 pref_change_registrar_.Remove(
826 prefs::kDefaultSupervisedUserFilteringBehavior);
827 pref_change_registrar_.Remove(prefs::kSupervisedUserManualHosts);
828 pref_change_registrar_.Remove(prefs::kSupervisedUserManualURLs);
829 for (const char* pref : kCustodianInfoPrefs) {
830 pref_change_registrar_.Remove(pref);
833 url_filter_context_.Clear();
834 FOR_EACH_OBSERVER(
835 SupervisedUserServiceObserver, observer_list_, OnURLFilterChanged());
837 if (waiting_for_sync_initialization_)
838 ProfileSyncServiceFactory::GetForProfile(profile_)->RemoveObserver(this);
840 #if !defined(OS_ANDROID)
841 // TODO(bauerb): Get rid of the platform-specific #ifdef here.
842 // http://crbug.com/313377
843 BrowserList::RemoveObserver(this);
844 #endif
848 void SupervisedUserService::RegisterAndInitSync(
849 SupervisedUserRegistrationUtility* registration_utility,
850 Profile* custodian_profile,
851 const std::string& supervised_user_id,
852 const AuthErrorCallback& callback) {
853 DCHECK(ProfileIsSupervised());
854 DCHECK(!custodian_profile->IsSupervised());
856 base::string16 name = base::UTF8ToUTF16(
857 profile_->GetPrefs()->GetString(prefs::kProfileName));
858 int avatar_index = profile_->GetPrefs()->GetInteger(
859 prefs::kProfileAvatarIndex);
860 SupervisedUserRegistrationInfo info(name, avatar_index);
861 registration_utility->Register(
862 supervised_user_id,
863 info,
864 base::Bind(&SupervisedUserService::OnSupervisedUserRegistered,
865 weak_ptr_factory_.GetWeakPtr(), callback, custodian_profile));
867 // Fetch the custodian's profile information, to store the name.
868 // TODO(pamg): If --google-profile-info (flag: switches::kGoogleProfileInfo)
869 // is ever enabled, take the name from the ProfileInfoCache instead.
870 CustodianProfileDownloaderService* profile_downloader_service =
871 CustodianProfileDownloaderServiceFactory::GetForProfile(
872 custodian_profile);
873 profile_downloader_service->DownloadProfile(
874 base::Bind(&SupervisedUserService::OnCustodianProfileDownloaded,
875 weak_ptr_factory_.GetWeakPtr()));
878 void SupervisedUserService::OnCustodianProfileDownloaded(
879 const base::string16& full_name) {
880 profile_->GetPrefs()->SetString(prefs::kSupervisedUserCustodianName,
881 base::UTF16ToUTF8(full_name));
884 void SupervisedUserService::OnSupervisedUserRegistered(
885 const AuthErrorCallback& callback,
886 Profile* custodian_profile,
887 const GoogleServiceAuthError& auth_error,
888 const std::string& token) {
889 if (auth_error.state() == GoogleServiceAuthError::NONE) {
890 InitSync(token);
891 SigninManagerBase* signin =
892 SigninManagerFactory::GetForProfile(custodian_profile);
893 profile_->GetPrefs()->SetString(prefs::kSupervisedUserCustodianEmail,
894 signin->GetAuthenticatedUsername());
896 // The supervised user profile is now ready for use.
897 ProfileManager* profile_manager = g_browser_process->profile_manager();
898 ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();
899 size_t index = cache.GetIndexOfProfileWithPath(profile_->GetPath());
900 cache.SetIsOmittedProfileAtIndex(index, false);
901 } else {
902 DCHECK_EQ(std::string(), token);
905 callback.Run(auth_error);
908 void SupervisedUserService::UpdateManualHosts() {
909 const base::DictionaryValue* dict =
910 profile_->GetPrefs()->GetDictionary(prefs::kSupervisedUserManualHosts);
911 scoped_ptr<std::map<std::string, bool> > host_map(
912 new std::map<std::string, bool>());
913 for (base::DictionaryValue::Iterator it(*dict); !it.IsAtEnd(); it.Advance()) {
914 bool allow = false;
915 bool result = it.value().GetAsBoolean(&allow);
916 DCHECK(result);
917 (*host_map)[it.key()] = allow;
919 url_filter_context_.SetManualHosts(host_map.Pass());
921 FOR_EACH_OBSERVER(
922 SupervisedUserServiceObserver, observer_list_, OnURLFilterChanged());
925 void SupervisedUserService::UpdateManualURLs() {
926 const base::DictionaryValue* dict =
927 profile_->GetPrefs()->GetDictionary(prefs::kSupervisedUserManualURLs);
928 scoped_ptr<std::map<GURL, bool> > url_map(new std::map<GURL, bool>());
929 for (base::DictionaryValue::Iterator it(*dict); !it.IsAtEnd(); it.Advance()) {
930 bool allow = false;
931 bool result = it.value().GetAsBoolean(&allow);
932 DCHECK(result);
933 (*url_map)[GURL(it.key())] = allow;
935 url_filter_context_.SetManualURLs(url_map.Pass());
937 FOR_EACH_OBSERVER(
938 SupervisedUserServiceObserver, observer_list_, OnURLFilterChanged());
941 void SupervisedUserService::OnBrowserSetLastActive(Browser* browser) {
942 bool profile_became_active = profile_->IsSameProfile(browser->profile());
943 if (!is_profile_active_ && profile_became_active)
944 content::RecordAction(UserMetricsAction("ManagedUsers_OpenProfile"));
945 else if (is_profile_active_ && !profile_became_active)
946 content::RecordAction(UserMetricsAction("ManagedUsers_SwitchProfile"));
948 is_profile_active_ = profile_became_active;
951 std::string SupervisedUserService::GetSupervisedUserName() const {
952 #if defined(OS_CHROMEOS)
953 // The active user can be NULL in unit tests.
954 if (user_manager::UserManager::Get()->GetActiveUser()) {
955 return UTF16ToUTF8(user_manager::UserManager::Get()->GetUserDisplayName(
956 user_manager::UserManager::Get()->GetActiveUser()->GetUserID()));
958 return std::string();
959 #else
960 return profile_->GetPrefs()->GetString(prefs::kProfileName);
961 #endif