Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(251)

Side by Side Diff: chrome/browser/ui/webui/policy_ui.cc

Issue 1395073002: Policy Ui sends correct translations for risk tags. (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: Description corrected. Created 5 years, 1 month ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
« no previous file with comments | « chrome/browser/ui/webui/policy_ui.h ('k') | chrome/browser/ui/webui/policy_ui_handler.h » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. 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 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #include "chrome/browser/ui/webui/policy_ui.h" 5 #include "chrome/browser/ui/webui/policy_ui.h"
6 6
7 #include <stddef.h>
8
9 #include "base/bind.h"
10 #include "base/bind_helpers.h"
11 #include "base/callback.h"
12 #include "base/compiler_specific.h"
13 #include "base/json/json_writer.h"
14 #include "base/logging.h"
15 #include "base/macros.h"
16 #include "base/memory/weak_ptr.h"
17 #include "base/strings/string16.h"
18 #include "base/time/time.h"
19 #include "base/values.h"
20 #include "chrome/browser/browser_process.h"
21 #include "chrome/browser/policy/profile_policy_connector.h"
22 #include "chrome/browser/policy/profile_policy_connector_factory.h"
23 #include "chrome/browser/policy/schema_registry_service.h"
24 #include "chrome/browser/policy/schema_registry_service_factory.h"
25 #include "chrome/browser/profiles/profile.h" 7 #include "chrome/browser/profiles/profile.h"
8 #include "chrome/browser/ui/webui/policy_ui_handler.h"
26 #include "chrome/common/url_constants.h" 9 #include "chrome/common/url_constants.h"
27 #include "components/policy/core/browser/browser_policy_connector.h"
28 #include "components/policy/core/browser/cloud/message_util.h"
29 #include "components/policy/core/browser/configuration_policy_handler_list.h"
30 #include "components/policy/core/browser/policy_error_map.h"
31 #include "components/policy/core/common/cloud/cloud_policy_client.h"
32 #include "components/policy/core/common/cloud/cloud_policy_constants.h"
33 #include "components/policy/core/common/cloud/cloud_policy_core.h"
34 #include "components/policy/core/common/cloud/cloud_policy_refresh_scheduler.h"
35 #include "components/policy/core/common/cloud/cloud_policy_store.h"
36 #include "components/policy/core/common/cloud/cloud_policy_validator.h"
37 #include "components/policy/core/common/policy_map.h"
38 #include "components/policy/core/common/policy_namespace.h"
39 #include "components/policy/core/common/policy_service.h"
40 #include "components/policy/core/common/policy_types.h"
41 #include "components/policy/core/common/remote_commands/remote_commands_service. h"
42 #include "components/policy/core/common/schema.h"
43 #include "components/policy/core/common/schema_map.h"
44 #include "components/policy/core/common/schema_registry.h"
45 #include "content/public/browser/web_contents.h"
46 #include "content/public/browser/web_ui.h" 10 #include "content/public/browser/web_ui.h"
47 #include "content/public/browser/web_ui_data_source.h"
48 #include "content/public/browser/web_ui_message_handler.h"
49 #include "google_apis/gaia/gaia_auth_util.h"
50 #include "grit/browser_resources.h" 11 #include "grit/browser_resources.h"
51 #include "grit/components_strings.h" 12 #include "grit/components_strings.h"
52 #include "policy/policy_constants.h"
53 #include "policy/proto/device_management_backend.pb.h"
54 #include "ui/base/l10n/l10n_util.h"
55 #include "ui/base/l10n/time_format.h"
56
57 #if defined(OS_CHROMEOS)
58 #include "chrome/browser/browser_process_platform_part.h"
59 #include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h"
60 #include "chrome/browser/chromeos/policy/device_cloud_policy_manager_chromeos.h"
61 #include "chrome/browser/chromeos/policy/device_local_account_policy_service.h"
62 #include "chrome/browser/chromeos/policy/user_cloud_policy_manager_chromeos.h"
63 #include "chrome/browser/chromeos/policy/user_cloud_policy_manager_factory_chrom eos.h"
64 #include "components/user_manager/user_manager.h"
65 #else
66 #include "chrome/browser/policy/cloud/user_cloud_policy_manager_factory.h"
67 #include "components/policy/core/common/cloud/user_cloud_policy_manager.h"
68 #endif
69
70 #if defined(ENABLE_EXTENSIONS)
71 #include "extensions/browser/extension_registry.h"
72 #include "extensions/browser/extension_registry_observer.h"
73 #include "extensions/common/extension.h"
74 #include "extensions/common/manifest.h"
75 #include "extensions/common/manifest_constants.h"
76 #endif
77
78 namespace em = enterprise_management;
79 13
80 namespace { 14 namespace {
81 15
82 struct PolicySourceMap { 16 content::WebUIDataSource* CreatePolicyUIHtmlSource() {
83 const char* key; 17 content::WebUIDataSource* source =
84 int string_id; 18 content::WebUIDataSource::Create(chrome::kChromeUIPolicyHost);
85 }; 19 PolicyUIHandler::AddCommonLocalizedStringsToSource(source);
86
87 // Strings that map from PolicySource enum to i18n string keys and their IDs.
88 const PolicySourceMap kPolicySources[policy::POLICY_SOURCE_COUNT] = {
89 {"sourceEnterpriseDefault", IDS_POLICY_SOURCE_ENTERPRISE_DEFAULT},
90 {"sourceCloud", IDS_POLICY_SOURCE_CLOUD},
91 {"sourcePublicSessionOverride", IDS_POLICY_SOURCE_PUBLIC_SESSION_OVERRIDE},
92 {"sourcePlatform", IDS_POLICY_SOURCE_PLATFORM}
93 };
94
95 void AddLocalizedPoilcySourceStrings(content::WebUIDataSource* source) {
96 DCHECK_EQ(static_cast<size_t>(policy::POLICY_SOURCE_COUNT),
97 arraysize(kPolicySources));
98 for (size_t i = 0; i < arraysize(kPolicySources); ++i) {
99 source->AddLocalizedString(kPolicySources[i].key,
100 kPolicySources[i].string_id);
101 }
102 }
103
104 void AddCommonLocalizedStringsToSource(content::WebUIDataSource* source) {
105 source->AddLocalizedString("title", IDS_POLICY_TITLE);
106 source->AddLocalizedString("filterPlaceholder", 20 source->AddLocalizedString("filterPlaceholder",
107 IDS_POLICY_FILTER_PLACEHOLDER); 21 IDS_POLICY_FILTER_PLACEHOLDER);
108 source->AddLocalizedString("reloadPolicies", IDS_POLICY_RELOAD_POLICIES); 22 source->AddLocalizedString("reloadPolicies", IDS_POLICY_RELOAD_POLICIES);
109 source->AddLocalizedString("status", IDS_POLICY_STATUS); 23 source->AddLocalizedString("status", IDS_POLICY_STATUS);
110 source->AddLocalizedString("statusDevice", IDS_POLICY_STATUS_DEVICE); 24 source->AddLocalizedString("statusDevice", IDS_POLICY_STATUS_DEVICE);
111 source->AddLocalizedString("statusUser", IDS_POLICY_STATUS_USER); 25 source->AddLocalizedString("statusUser", IDS_POLICY_STATUS_USER);
112 source->AddLocalizedString("labelDomain", IDS_POLICY_LABEL_DOMAIN); 26 source->AddLocalizedString("labelDomain", IDS_POLICY_LABEL_DOMAIN);
113 source->AddLocalizedString("labelUsername", IDS_POLICY_LABEL_USERNAME); 27 source->AddLocalizedString("labelUsername", IDS_POLICY_LABEL_USERNAME);
114 source->AddLocalizedString("labelClientId", IDS_POLICY_LABEL_CLIENT_ID); 28 source->AddLocalizedString("labelClientId", IDS_POLICY_LABEL_CLIENT_ID);
115 source->AddLocalizedString("labelAssetId", IDS_POLICY_LABEL_ASSET_ID); 29 source->AddLocalizedString("labelAssetId", IDS_POLICY_LABEL_ASSET_ID);
116 source->AddLocalizedString("labelLocation", IDS_POLICY_LABEL_LOCATION); 30 source->AddLocalizedString("labelLocation", IDS_POLICY_LABEL_LOCATION);
117 source->AddLocalizedString("labelDirectoryApiId", 31 source->AddLocalizedString("labelDirectoryApiId",
118 IDS_POLICY_LABEL_DIRECTORY_API_ID); 32 IDS_POLICY_LABEL_DIRECTORY_API_ID);
119 source->AddLocalizedString("labelTimeSinceLastRefresh", 33 source->AddLocalizedString("labelTimeSinceLastRefresh",
120 IDS_POLICY_LABEL_TIME_SINCE_LAST_REFRESH); 34 IDS_POLICY_LABEL_TIME_SINCE_LAST_REFRESH);
121 source->AddLocalizedString("labelRefreshInterval", 35 source->AddLocalizedString("labelRefreshInterval",
122 IDS_POLICY_LABEL_REFRESH_INTERVAL); 36 IDS_POLICY_LABEL_REFRESH_INTERVAL);
123 source->AddLocalizedString("labelStatus", IDS_POLICY_LABEL_STATUS); 37 source->AddLocalizedString("labelStatus", IDS_POLICY_LABEL_STATUS);
124 source->AddLocalizedString("showUnset", IDS_POLICY_SHOW_UNSET); 38 source->AddLocalizedString("showUnset", IDS_POLICY_SHOW_UNSET);
125 source->AddLocalizedString("noPoliciesSet", IDS_POLICY_NO_POLICIES_SET); 39 source->AddLocalizedString("noPoliciesSet", IDS_POLICY_NO_POLICIES_SET);
126 source->AddLocalizedString("headerScope", IDS_POLICY_HEADER_SCOPE);
127 source->AddLocalizedString("headerLevel", IDS_POLICY_HEADER_LEVEL);
128 source->AddLocalizedString("headerName", IDS_POLICY_HEADER_NAME);
129 source->AddLocalizedString("headerValue", IDS_POLICY_HEADER_VALUE);
130 source->AddLocalizedString("headerStatus", IDS_POLICY_HEADER_STATUS);
131 source->AddLocalizedString("headerSource", IDS_POLICY_HEADER_SOURCE);
132 source->AddLocalizedString("showExpandedValue", 40 source->AddLocalizedString("showExpandedValue",
133 IDS_POLICY_SHOW_EXPANDED_VALUE); 41 IDS_POLICY_SHOW_EXPANDED_VALUE);
134 source->AddLocalizedString("hideExpandedValue", 42 source->AddLocalizedString("hideExpandedValue",
135 IDS_POLICY_HIDE_EXPANDED_VALUE); 43 IDS_POLICY_HIDE_EXPANDED_VALUE);
136 source->AddLocalizedString("scopeUser", IDS_POLICY_SCOPE_USER);
137 source->AddLocalizedString("scopeDevice", IDS_POLICY_SCOPE_DEVICE);
138 source->AddLocalizedString("levelRecommended", IDS_POLICY_LEVEL_RECOMMENDED);
139 source->AddLocalizedString("levelMandatory", IDS_POLICY_LEVEL_MANDATORY);
140 source->AddLocalizedString("ok", IDS_POLICY_OK);
141 source->AddLocalizedString("unset", IDS_POLICY_UNSET);
142 source->AddLocalizedString("unknown", IDS_POLICY_UNKNOWN);
143 source->AddLocalizedString("notSpecified", IDS_POLICY_NOT_SPECIFIED);
144 AddLocalizedPoilcySourceStrings(source);
145
146 source->SetJsonPath("strings.js");
147 }
148
149 content::WebUIDataSource* CreatePolicyMaterialDesignUIHtmlSource() {
150 content::WebUIDataSource* source =
151 content::WebUIDataSource::Create(chrome::kChromeUIMdPolicyHost);
152 AddCommonLocalizedStringsToSource(source);
153 source->SetDefaultResource(IDR_MD_POLICY_HTML);
154
155 return source;
156 }
157
158
159 content::WebUIDataSource* CreatePolicyUIHtmlSource() {
160 content::WebUIDataSource* source =
161 content::WebUIDataSource::Create(chrome::kChromeUIPolicyHost);
162 AddCommonLocalizedStringsToSource(source);
163 // Add required resources. 44 // Add required resources.
164 source->AddResourcePath("policy.css", IDR_POLICY_CSS); 45 source->AddResourcePath("policy.css", IDR_POLICY_CSS);
165 source->AddResourcePath("policy.js", IDR_POLICY_JS); 46 source->AddResourcePath("policy.js", IDR_POLICY_JS);
166 source->AddResourcePath("uber_utils.js", IDR_UBER_UTILS_JS); 47 source->AddResourcePath("uber_utils.js", IDR_UBER_UTILS_JS);
167 source->SetDefaultResource(IDR_POLICY_HTML); 48 source->SetDefaultResource(IDR_POLICY_HTML);
168
169 return source; 49 return source;
170 } 50 }
171 51
172 // Formats the association state indicated by |data|. If |data| is NULL, the
173 // state is considered to be UNMANAGED.
174 base::string16 FormatAssociationState(const em::PolicyData* data) {
175 if (data) {
176 switch (data->state()) {
177 case em::PolicyData::ACTIVE:
178 return l10n_util::GetStringUTF16(IDS_POLICY_ASSOCIATION_STATE_ACTIVE);
179 case em::PolicyData::UNMANAGED:
180 return l10n_util::GetStringUTF16(
181 IDS_POLICY_ASSOCIATION_STATE_UNMANAGED);
182 case em::PolicyData::DEPROVISIONED:
183 return l10n_util::GetStringUTF16(
184 IDS_POLICY_ASSOCIATION_STATE_DEPROVISIONED);
185 }
186 NOTREACHED() << "Unknown state " << data->state();
187 }
188
189 // Default to UNMANAGED for the case of missing policy or bad state enum.
190 return l10n_util::GetStringUTF16(IDS_POLICY_ASSOCIATION_STATE_UNMANAGED);
191 }
192
193 void GetStatusFromCore(const policy::CloudPolicyCore* core,
194 base::DictionaryValue* dict) {
195 const policy::CloudPolicyStore* store = core->store();
196 const policy::CloudPolicyClient* client = core->client();
197 const policy::CloudPolicyRefreshScheduler* refresh_scheduler =
198 core->refresh_scheduler();
199
200 // CloudPolicyStore errors take precedence to show in the status message.
201 // Other errors (such as transient policy fetching problems) get displayed
202 // only if CloudPolicyStore is in STATUS_OK.
203 base::string16 status =
204 policy::FormatStoreStatus(store->status(), store->validation_status());
205 if (store->status() == policy::CloudPolicyStore::STATUS_OK) {
206 if (client && client->status() != policy::DM_STATUS_SUCCESS)
207 status = policy::FormatDeviceManagementStatus(client->status());
208 else if (!store->is_managed())
209 status = FormatAssociationState(store->policy());
210 }
211
212 const em::PolicyData* policy = store->policy();
213 std::string client_id = policy ? policy->device_id() : std::string();
214 std::string username = policy ? policy->username() : std::string();
215
216 if (policy && policy->has_annotated_asset_id())
217 dict->SetString("assetId", policy->annotated_asset_id());
218 if (policy && policy->has_annotated_location())
219 dict->SetString("location", policy->annotated_location());
220 if (policy && policy->has_directory_api_id())
221 dict->SetString("directoryApiId", policy->directory_api_id());
222
223 base::TimeDelta refresh_interval =
224 base::TimeDelta::FromMilliseconds(refresh_scheduler ?
225 refresh_scheduler->refresh_delay() :
226 policy::CloudPolicyRefreshScheduler::kDefaultRefreshDelayMs);
227 base::Time last_refresh_time = refresh_scheduler ?
228 refresh_scheduler->last_refresh() : base::Time();
229
230 bool no_error = store->status() == policy::CloudPolicyStore::STATUS_OK &&
231 client && client->status() == policy::DM_STATUS_SUCCESS;
232 dict->SetBoolean("error", !no_error);
233 dict->SetString("status", status);
234 dict->SetString("clientId", client_id);
235 dict->SetString("username", username);
236 dict->SetString("refreshInterval",
237 ui::TimeFormat::Simple(ui::TimeFormat::FORMAT_DURATION,
238 ui::TimeFormat::LENGTH_SHORT,
239 refresh_interval));
240 dict->SetString("timeSinceLastRefresh", last_refresh_time.is_null() ?
241 l10n_util::GetStringUTF16(IDS_POLICY_NEVER_FETCHED) :
242 ui::TimeFormat::Simple(ui::TimeFormat::FORMAT_ELAPSED,
243 ui::TimeFormat::LENGTH_SHORT,
244 base::Time::NowFromSystemTime() -
245 last_refresh_time));
246 }
247
248 void ExtractDomainFromUsername(base::DictionaryValue* dict) {
249 std::string username;
250 dict->GetString("username", &username);
251 if (!username.empty())
252 dict->SetString("domain", gaia::ExtractDomainName(username));
253 }
254
255 // Utility function that returns a JSON serialization of the given |dict|.
256 scoped_ptr<base::StringValue> DictionaryToJSONString(
257 const base::DictionaryValue& dict) {
258 std::string json_string;
259 base::JSONWriter::WriteWithOptions(dict,
260 base::JSONWriter::OPTIONS_PRETTY_PRINT,
261 &json_string);
262 return make_scoped_ptr(new base::StringValue(json_string));
263 }
264
265 // Returns a copy of |value| with some values converted to a representation that
266 // i18n_template.js will display in a nicer way.
267 scoped_ptr<base::Value> CopyAndConvert(const base::Value* value) {
268 const base::DictionaryValue* dict = NULL;
269 if (value->GetAsDictionary(&dict))
270 return DictionaryToJSONString(*dict);
271
272 scoped_ptr<base::Value> copy(value->DeepCopy());
273 base::ListValue* list = NULL;
274 if (copy->GetAsList(&list)) {
275 for (size_t i = 0; i < list->GetSize(); ++i) {
276 if (list->GetDictionary(i, &dict))
277 list->Set(i, DictionaryToJSONString(*dict).release());
278 }
279 }
280
281 return copy.Pass();
282 }
283
284 } // namespace 52 } // namespace
285 53
286 // An interface for querying the status of cloud policy.
287 class CloudPolicyStatusProvider {
288 public:
289 CloudPolicyStatusProvider();
290 virtual ~CloudPolicyStatusProvider();
291
292 // Sets a callback to invoke upon status changes.
293 void SetStatusChangeCallback(const base::Closure& callback);
294
295 virtual void GetStatus(base::DictionaryValue* dict);
296
297 protected:
298 void NotifyStatusChange();
299
300 private:
301 base::Closure callback_;
302
303 DISALLOW_COPY_AND_ASSIGN(CloudPolicyStatusProvider);
304 };
305
306 // Status provider implementation that pulls cloud policy status from a
307 // CloudPolicyCore instance provided at construction time. Also listens for
308 // changes on that CloudPolicyCore and reports them through the status change
309 // callback.
310 class CloudPolicyCoreStatusProvider
311 : public CloudPolicyStatusProvider,
312 public policy::CloudPolicyStore::Observer {
313 public:
314 explicit CloudPolicyCoreStatusProvider(policy::CloudPolicyCore* core);
315 ~CloudPolicyCoreStatusProvider() override;
316
317 // policy::CloudPolicyStore::Observer implementation.
318 void OnStoreLoaded(policy::CloudPolicyStore* store) override;
319 void OnStoreError(policy::CloudPolicyStore* store) override;
320
321 protected:
322 // Policy status is read from the CloudPolicyClient, CloudPolicyStore and
323 // CloudPolicyRefreshScheduler hosted by this |core_|.
324 policy::CloudPolicyCore* core_;
325
326 private:
327 DISALLOW_COPY_AND_ASSIGN(CloudPolicyCoreStatusProvider);
328 };
329
330 // A cloud policy status provider for user policy.
331 class UserPolicyStatusProvider : public CloudPolicyCoreStatusProvider {
332 public:
333 explicit UserPolicyStatusProvider(policy::CloudPolicyCore* core);
334 ~UserPolicyStatusProvider() override;
335
336 // CloudPolicyCoreStatusProvider implementation.
337 void GetStatus(base::DictionaryValue* dict) override;
338
339 private:
340 DISALLOW_COPY_AND_ASSIGN(UserPolicyStatusProvider);
341 };
342
343 #if defined(OS_CHROMEOS)
344 // A cloud policy status provider for device policy.
345 class DevicePolicyStatusProvider : public CloudPolicyCoreStatusProvider {
346 public:
347 explicit DevicePolicyStatusProvider(
348 policy::BrowserPolicyConnectorChromeOS* connector);
349 ~DevicePolicyStatusProvider() override;
350
351 // CloudPolicyCoreStatusProvider implementation.
352 void GetStatus(base::DictionaryValue* dict) override;
353
354 private:
355 std::string domain_;
356
357 DISALLOW_COPY_AND_ASSIGN(DevicePolicyStatusProvider);
358 };
359
360 // A cloud policy status provider that reads policy status from the policy core
361 // associated with the device-local account specified by |user_id| at
362 // construction time. The indirection via user ID and
363 // DeviceLocalAccountPolicyService is necessary because the device-local account
364 // may go away any time behind the scenes, at which point the status message
365 // text will indicate CloudPolicyStore::STATUS_BAD_STATE.
366 class DeviceLocalAccountPolicyStatusProvider
367 : public CloudPolicyStatusProvider,
368 public policy::DeviceLocalAccountPolicyService::Observer {
369 public:
370 DeviceLocalAccountPolicyStatusProvider(
371 const std::string& user_id,
372 policy::DeviceLocalAccountPolicyService* service);
373 ~DeviceLocalAccountPolicyStatusProvider() override;
374
375 // CloudPolicyStatusProvider implementation.
376 void GetStatus(base::DictionaryValue* dict) override;
377
378 // policy::DeviceLocalAccountPolicyService::Observer implementation.
379 void OnPolicyUpdated(const std::string& user_id) override;
380 void OnDeviceLocalAccountsChanged() override;
381
382 private:
383 const std::string user_id_;
384 policy::DeviceLocalAccountPolicyService* service_;
385
386 DISALLOW_COPY_AND_ASSIGN(DeviceLocalAccountPolicyStatusProvider);
387 };
388 #endif
389
390 // The JavaScript message handler for the chrome://policy page.
391 class PolicyUIHandler : public content::WebUIMessageHandler,
392 #if defined(ENABLE_EXTENSIONS)
393 public extensions::ExtensionRegistryObserver,
394 #endif
395 public policy::PolicyService::Observer,
396 public policy::SchemaRegistry::Observer {
397 public:
398 PolicyUIHandler();
399 ~PolicyUIHandler() override;
400
401 // content::WebUIMessageHandler implementation.
402 void RegisterMessages() override;
403
404 #if defined(ENABLE_EXTENSIONS)
405 // extensions::ExtensionRegistryObserver implementation.
406 void OnExtensionLoaded(content::BrowserContext* browser_context,
407 const extensions::Extension* extension) override;
408 void OnExtensionUnloaded(
409 content::BrowserContext* browser_context,
410 const extensions::Extension* extension,
411 extensions::UnloadedExtensionInfo::Reason reason) override;
412 #endif
413
414 // policy::PolicyService::Observer implementation.
415 void OnPolicyUpdated(const policy::PolicyNamespace& ns,
416 const policy::PolicyMap& previous,
417 const policy::PolicyMap& current) override;
418
419 // policy::SchemaRegistry::Observer implementation.
420 void OnSchemaRegistryUpdated(bool has_new_schemas) override;
421
422 private:
423 // Send a dictionary containing the names of all known policies to the UI.
424 void SendPolicyNames() const;
425
426 // Send information about the current policy values to the UI. For each policy
427 // whose value has been set, a dictionary containing the value and additional
428 // metadata is sent.
429 void SendPolicyValues() const;
430
431 // Send the status of cloud policy to the UI. For each scope that has cloud
432 // policy enabled (device and/or user), a dictionary containing status
433 // information is sent.
434 void SendStatus() const;
435
436 // Inserts a description of each policy in |policy_map| into |values|, using
437 // the optional errors in |errors| to determine the status of each policy.
438 void GetPolicyValues(const policy::PolicyMap& policy_map,
439 policy::PolicyErrorMap* errors,
440 base::DictionaryValue* values) const;
441
442 void GetChromePolicyValues(base::DictionaryValue* values) const;
443
444 void HandleInitialized(const base::ListValue* args);
445 void HandleReloadPolicies(const base::ListValue* args);
446
447 void OnRefreshPoliciesDone() const;
448
449 policy::PolicyService* GetPolicyService() const;
450
451 std::string device_domain_;
452
453 // Providers that supply status dictionaries for user and device policy,
454 // respectively. These are created on initialization time as appropriate for
455 // the platform (Chrome OS / desktop) and type of policy that is in effect.
456 scoped_ptr<CloudPolicyStatusProvider> user_status_provider_;
457 scoped_ptr<CloudPolicyStatusProvider> device_status_provider_;
458
459 base::WeakPtrFactory<PolicyUIHandler> weak_factory_;
460
461 DISALLOW_COPY_AND_ASSIGN(PolicyUIHandler);
462 };
463
464 CloudPolicyStatusProvider::CloudPolicyStatusProvider() {
465 }
466
467 CloudPolicyStatusProvider::~CloudPolicyStatusProvider() {
468 }
469
470 void CloudPolicyStatusProvider::SetStatusChangeCallback(
471 const base::Closure& callback) {
472 callback_ = callback;
473 }
474
475 void CloudPolicyStatusProvider::GetStatus(base::DictionaryValue* dict) {
476 }
477
478 void CloudPolicyStatusProvider::NotifyStatusChange() {
479 if (!callback_.is_null())
480 callback_.Run();
481 }
482
483 CloudPolicyCoreStatusProvider::CloudPolicyCoreStatusProvider(
484 policy::CloudPolicyCore* core) : core_(core) {
485 core_->store()->AddObserver(this);
486 // TODO(bartfab): Add an observer that watches for client errors. Observing
487 // core_->client() directly is not safe as the client may be destroyed and
488 // (re-)created anytime if the user signs in or out on desktop platforms.
489 }
490
491 CloudPolicyCoreStatusProvider::~CloudPolicyCoreStatusProvider() {
492 core_->store()->RemoveObserver(this);
493 }
494
495 void CloudPolicyCoreStatusProvider::OnStoreLoaded(
496 policy::CloudPolicyStore* store) {
497 NotifyStatusChange();
498 }
499
500 void CloudPolicyCoreStatusProvider::OnStoreError(
501 policy::CloudPolicyStore* store) {
502 NotifyStatusChange();
503 }
504
505 UserPolicyStatusProvider::UserPolicyStatusProvider(
506 policy::CloudPolicyCore* core) : CloudPolicyCoreStatusProvider(core) {
507 }
508
509 UserPolicyStatusProvider::~UserPolicyStatusProvider() {
510 }
511
512 void UserPolicyStatusProvider::GetStatus(base::DictionaryValue* dict) {
513 if (!core_->store()->is_managed())
514 return;
515 GetStatusFromCore(core_, dict);
516 ExtractDomainFromUsername(dict);
517 }
518
519 #if defined(OS_CHROMEOS)
520 DevicePolicyStatusProvider::DevicePolicyStatusProvider(
521 policy::BrowserPolicyConnectorChromeOS* connector)
522 : CloudPolicyCoreStatusProvider(
523 connector->GetDeviceCloudPolicyManager()->core()) {
524 domain_ = connector->GetEnterpriseDomain();
525 }
526
527 DevicePolicyStatusProvider::~DevicePolicyStatusProvider() {
528 }
529
530 void DevicePolicyStatusProvider::GetStatus(base::DictionaryValue* dict) {
531 GetStatusFromCore(core_, dict);
532 dict->SetString("domain", domain_);
533 }
534
535 DeviceLocalAccountPolicyStatusProvider::DeviceLocalAccountPolicyStatusProvider(
536 const std::string& user_id,
537 policy::DeviceLocalAccountPolicyService* service)
538 : user_id_(user_id),
539 service_(service) {
540 service_->AddObserver(this);
541 }
542
543 DeviceLocalAccountPolicyStatusProvider::
544 ~DeviceLocalAccountPolicyStatusProvider() {
545 service_->RemoveObserver(this);
546 }
547
548 void DeviceLocalAccountPolicyStatusProvider::GetStatus(
549 base::DictionaryValue* dict) {
550 const policy::DeviceLocalAccountPolicyBroker* broker =
551 service_->GetBrokerForUser(user_id_);
552 if (broker) {
553 GetStatusFromCore(broker->core(), dict);
554 } else {
555 dict->SetBoolean("error", true);
556 dict->SetString("status",
557 policy::FormatStoreStatus(
558 policy::CloudPolicyStore::STATUS_BAD_STATE,
559 policy::CloudPolicyValidatorBase::VALIDATION_OK));
560 dict->SetString("username", std::string());
561 }
562 ExtractDomainFromUsername(dict);
563 dict->SetBoolean("publicAccount", true);
564 }
565
566 void DeviceLocalAccountPolicyStatusProvider::OnPolicyUpdated(
567 const std::string& user_id) {
568 if (user_id == user_id_)
569 NotifyStatusChange();
570 }
571
572 void DeviceLocalAccountPolicyStatusProvider::OnDeviceLocalAccountsChanged() {
573 NotifyStatusChange();
574 }
575 #endif
576
577 PolicyUIHandler::PolicyUIHandler()
578 : weak_factory_(this) {
579 }
580
581 PolicyUIHandler::~PolicyUIHandler() {
582 GetPolicyService()->RemoveObserver(policy::POLICY_DOMAIN_CHROME, this);
583 GetPolicyService()->RemoveObserver(policy::POLICY_DOMAIN_EXTENSIONS, this);
584 policy::SchemaRegistry* registry =
585 policy::SchemaRegistryServiceFactory::GetForContext(
586 Profile::FromWebUI(web_ui())->GetOriginalProfile())->registry();
587 registry->RemoveObserver(this);
588
589 #if defined(ENABLE_EXTENSIONS)
590 extensions::ExtensionRegistry::Get(Profile::FromWebUI(web_ui()))
591 ->RemoveObserver(this);
592 #endif
593 }
594
595 void PolicyUIHandler::RegisterMessages() {
596 #if defined(OS_CHROMEOS)
597 policy::BrowserPolicyConnectorChromeOS* connector =
598 g_browser_process->platform_part()->browser_policy_connector_chromeos();
599 if (connector->IsEnterpriseManaged())
600 device_status_provider_.reset(new DevicePolicyStatusProvider(connector));
601
602 const user_manager::UserManager* user_manager =
603 user_manager::UserManager::Get();
604 if (user_manager->IsLoggedInAsPublicAccount()) {
605 policy::DeviceLocalAccountPolicyService* local_account_service =
606 connector->GetDeviceLocalAccountPolicyService();
607 if (local_account_service) {
608 user_status_provider_.reset(
609 new DeviceLocalAccountPolicyStatusProvider(
610 user_manager->GetLoggedInUser()->email(), local_account_service));
611 }
612 } else {
613 policy::UserCloudPolicyManagerChromeOS* user_cloud_policy_manager =
614 policy::UserCloudPolicyManagerFactoryChromeOS::GetForProfile(
615 Profile::FromWebUI(web_ui()));
616 if (user_cloud_policy_manager) {
617 user_status_provider_.reset(
618 new UserPolicyStatusProvider(user_cloud_policy_manager->core()));
619 }
620 }
621 #else
622 policy::UserCloudPolicyManager* user_cloud_policy_manager =
623 policy::UserCloudPolicyManagerFactory::GetForBrowserContext(
624 web_ui()->GetWebContents()->GetBrowserContext());
625 if (user_cloud_policy_manager) {
626 user_status_provider_.reset(
627 new UserPolicyStatusProvider(user_cloud_policy_manager->core()));
628 }
629 #endif
630
631 if (!user_status_provider_.get())
632 user_status_provider_.reset(new CloudPolicyStatusProvider());
633 if (!device_status_provider_.get())
634 device_status_provider_.reset(new CloudPolicyStatusProvider());
635
636 base::Closure update_callback(base::Bind(&PolicyUIHandler::SendStatus,
637 base::Unretained(this)));
638 user_status_provider_->SetStatusChangeCallback(update_callback);
639 device_status_provider_->SetStatusChangeCallback(update_callback);
640 GetPolicyService()->AddObserver(policy::POLICY_DOMAIN_CHROME, this);
641 GetPolicyService()->AddObserver(policy::POLICY_DOMAIN_EXTENSIONS, this);
642
643 #if defined(ENABLE_EXTENSIONS)
644 extensions::ExtensionRegistry::Get(Profile::FromWebUI(web_ui()))
645 ->AddObserver(this);
646 #endif
647 policy::SchemaRegistry* registry =
648 policy::SchemaRegistryServiceFactory::GetForContext(
649 Profile::FromWebUI(web_ui())->GetOriginalProfile())->registry();
650 registry->AddObserver(this);
651
652 web_ui()->RegisterMessageCallback(
653 "initialized",
654 base::Bind(&PolicyUIHandler::HandleInitialized, base::Unretained(this)));
655 web_ui()->RegisterMessageCallback(
656 "reloadPolicies",
657 base::Bind(&PolicyUIHandler::HandleReloadPolicies,
658 base::Unretained(this)));
659 }
660
661 #if defined(ENABLE_EXTENSIONS)
662 void PolicyUIHandler::OnExtensionLoaded(
663 content::BrowserContext* browser_context,
664 const extensions::Extension* extension) {
665 SendPolicyNames();
666 SendPolicyValues();
667 }
668
669 void PolicyUIHandler::OnExtensionUnloaded(
670 content::BrowserContext* browser_context,
671 const extensions::Extension* extension,
672 extensions::UnloadedExtensionInfo::Reason reason) {
673 SendPolicyNames();
674 SendPolicyValues();
675 }
676 #endif
677
678 void PolicyUIHandler::OnSchemaRegistryUpdated(bool has_new_schemas) {
679 // Update UI when new schema is added.
680 if (has_new_schemas) {
681 SendPolicyNames();
682 SendPolicyValues();
683 }
684 }
685
686 void PolicyUIHandler::OnPolicyUpdated(const policy::PolicyNamespace& ns,
687 const policy::PolicyMap& previous,
688 const policy::PolicyMap& current) {
689 SendPolicyValues();
690 }
691
692 void PolicyUIHandler::SendPolicyNames() const {
693 base::DictionaryValue names;
694
695 Profile* profile = Profile::FromWebUI(web_ui());
696 policy::SchemaRegistry* registry =
697 policy::SchemaRegistryServiceFactory::GetForContext(
698 profile->GetOriginalProfile())->registry();
699 scoped_refptr<policy::SchemaMap> schema_map = registry->schema_map();
700
701 // Add Chrome policy names.
702 base::DictionaryValue* chrome_policy_names = new base::DictionaryValue;
703 policy::PolicyNamespace chrome_ns(policy::POLICY_DOMAIN_CHROME, "");
704 const policy::Schema* chrome_schema = schema_map->GetSchema(chrome_ns);
705 for (policy::Schema::Iterator it = chrome_schema->GetPropertiesIterator();
706 !it.IsAtEnd(); it.Advance()) {
707 chrome_policy_names->SetBoolean(it.key(), true);
708 }
709 names.Set("chromePolicyNames", chrome_policy_names);
710
711 #if defined(ENABLE_EXTENSIONS)
712 // Add extension policy names.
713 base::DictionaryValue* extension_policy_names = new base::DictionaryValue;
714
715 for (const scoped_refptr<const extensions::Extension>& extension :
716 extensions::ExtensionRegistry::Get(profile)->enabled_extensions()) {
717 // Skip this extension if it's not an enterprise extension.
718 if (!extension->manifest()->HasPath(
719 extensions::manifest_keys::kStorageManagedSchema))
720 continue;
721 base::DictionaryValue* extension_value = new base::DictionaryValue;
722 extension_value->SetString("name", extension->name());
723 const policy::Schema* schema =
724 schema_map->GetSchema(policy::PolicyNamespace(
725 policy::POLICY_DOMAIN_EXTENSIONS, extension->id()));
726 base::DictionaryValue* policy_names = new base::DictionaryValue;
727 if (schema && schema->valid()) {
728 // Get policy names from the extension's policy schema.
729 // Store in a map, not an array, for faster lookup on JS side.
730 for (policy::Schema::Iterator prop = schema->GetPropertiesIterator();
731 !prop.IsAtEnd(); prop.Advance()) {
732 policy_names->SetBoolean(prop.key(), true);
733 }
734 }
735 extension_value->Set("policyNames", policy_names);
736 extension_policy_names->Set(extension->id(), extension_value);
737 }
738 names.Set("extensionPolicyNames", extension_policy_names);
739 #endif // defined(ENABLE_EXTENSIONS)
740
741 web_ui()->CallJavascriptFunction("policy.Page.setPolicyNames", names);
742 }
743
744 void PolicyUIHandler::SendPolicyValues() const {
745 base::DictionaryValue all_policies;
746
747 // Add Chrome policy values.
748 base::DictionaryValue* chrome_policies = new base::DictionaryValue;
749 GetChromePolicyValues(chrome_policies);
750 all_policies.Set("chromePolicies", chrome_policies);
751
752 #if defined(ENABLE_EXTENSIONS)
753 // Add extension policy values.
754 extensions::ExtensionRegistry* registry =
755 extensions::ExtensionRegistry::Get(Profile::FromWebUI(web_ui()));
756 base::DictionaryValue* extension_values = new base::DictionaryValue;
757
758 for (const scoped_refptr<const extensions::Extension>& extension :
759 registry->enabled_extensions()) {
760 // Skip this extension if it's not an enterprise extension.
761 if (!extension->manifest()->HasPath(
762 extensions::manifest_keys::kStorageManagedSchema))
763 continue;
764 base::DictionaryValue* extension_policies = new base::DictionaryValue;
765 policy::PolicyNamespace policy_namespace = policy::PolicyNamespace(
766 policy::POLICY_DOMAIN_EXTENSIONS, extension->id());
767 policy::PolicyErrorMap empty_error_map;
768 GetPolicyValues(GetPolicyService()->GetPolicies(policy_namespace),
769 &empty_error_map, extension_policies);
770 extension_values->Set(extension->id(), extension_policies);
771 }
772 all_policies.Set("extensionPolicies", extension_values);
773 #endif
774 web_ui()->CallJavascriptFunction("policy.Page.setPolicyValues", all_policies);
775 }
776
777 void PolicyUIHandler::GetPolicyValues(const policy::PolicyMap& map,
778 policy::PolicyErrorMap* errors,
779 base::DictionaryValue* values) const {
780 for (policy::PolicyMap::const_iterator entry = map.begin();
781 entry != map.end(); ++entry) {
782 base::DictionaryValue* value = new base::DictionaryValue;
783 value->Set("value", CopyAndConvert(entry->second.value).release());
784 if (entry->second.scope == policy::POLICY_SCOPE_USER)
785 value->SetString("scope", "user");
786 else
787 value->SetString("scope", "machine");
788 if (entry->second.level == policy::POLICY_LEVEL_RECOMMENDED)
789 value->SetString("level", "recommended");
790 else
791 value->SetString("level", "mandatory");
792 value->SetString("source", kPolicySources[entry->second.source].key);
793 base::string16 error = errors->GetErrors(entry->first);
794 if (!error.empty())
795 value->SetString("error", error);
796 values->Set(entry->first, value);
797 }
798 }
799
800 void PolicyUIHandler::GetChromePolicyValues(
801 base::DictionaryValue* values) const {
802 policy::PolicyService* policy_service = GetPolicyService();
803 policy::PolicyMap map;
804
805 // Make a copy that can be modified, since some policy values are modified
806 // before being displayed.
807 map.CopyFrom(policy_service->GetPolicies(
808 policy::PolicyNamespace(policy::POLICY_DOMAIN_CHROME, std::string())));
809
810 // Get a list of all the errors in the policy values.
811 const policy::ConfigurationPolicyHandlerList* handler_list =
812 g_browser_process->browser_policy_connector()->GetHandlerList();
813 policy::PolicyErrorMap errors;
814 handler_list->ApplyPolicySettings(map, NULL, &errors);
815
816 // Convert dictionary values to strings for display.
817 handler_list->PrepareForDisplaying(&map);
818
819 GetPolicyValues(map, &errors, values);
820 }
821
822 void PolicyUIHandler::SendStatus() const {
823 scoped_ptr<base::DictionaryValue> device_status(new base::DictionaryValue);
824 device_status_provider_->GetStatus(device_status.get());
825 if (!device_domain_.empty())
826 device_status->SetString("domain", device_domain_);
827 scoped_ptr<base::DictionaryValue> user_status(new base::DictionaryValue);
828 user_status_provider_->GetStatus(user_status.get());
829 std::string username;
830 user_status->GetString("username", &username);
831 if (!username.empty())
832 user_status->SetString("domain", gaia::ExtractDomainName(username));
833
834 base::DictionaryValue status;
835 if (!device_status->empty())
836 status.Set("device", device_status.release());
837 if (!user_status->empty())
838 status.Set("user", user_status.release());
839
840 web_ui()->CallJavascriptFunction("policy.Page.setStatus", status);
841 }
842
843 void PolicyUIHandler::HandleInitialized(const base::ListValue* args) {
844 SendPolicyNames();
845 SendPolicyValues();
846 SendStatus();
847 }
848
849 void PolicyUIHandler::HandleReloadPolicies(const base::ListValue* args) {
850 #if defined(OS_CHROMEOS)
851 // Allow user to manually fetch remote commands, in case invalidation
852 // service is not working properly.
853 // TODO(binjin): evaluate and possibly remove this after invalidation
854 // service is landed and tested. http://crbug.com/480982
855 policy::BrowserPolicyConnectorChromeOS* connector =
856 g_browser_process->platform_part()->browser_policy_connector_chromeos();
857 policy::RemoteCommandsService* remote_commands_service =
858 connector->GetDeviceCloudPolicyManager()
859 ->core()
860 ->remote_commands_service();
861 if (remote_commands_service)
862 remote_commands_service->FetchRemoteCommands();
863 #endif
864 GetPolicyService()->RefreshPolicies(base::Bind(
865 &PolicyUIHandler::OnRefreshPoliciesDone, weak_factory_.GetWeakPtr()));
866 }
867
868 void PolicyUIHandler::OnRefreshPoliciesDone() const {
869 web_ui()->CallJavascriptFunction("policy.Page.reloadPoliciesDone");
870 }
871
872 policy::PolicyService* PolicyUIHandler::GetPolicyService() const {
873 return policy::ProfilePolicyConnectorFactory::GetForBrowserContext(
874 web_ui()->GetWebContents()->GetBrowserContext())->policy_service();
875 }
876
877 PolicyUI::PolicyUI(content::WebUI* web_ui) : WebUIController(web_ui) { 54 PolicyUI::PolicyUI(content::WebUI* web_ui) : WebUIController(web_ui) {
878 web_ui->AddMessageHandler(new PolicyUIHandler); 55 web_ui->AddMessageHandler(new PolicyUIHandler);
879 content::WebUIDataSource::Add(Profile::FromWebUI(web_ui), 56 content::WebUIDataSource::Add(Profile::FromWebUI(web_ui),
880 CreatePolicyUIHtmlSource()); 57 CreatePolicyUIHtmlSource());
881 } 58 }
882 59
883 PolicyUI::~PolicyUI() { 60 PolicyUI::~PolicyUI() {
884 } 61 }
885
886 PolicyMaterialDesignUI::PolicyMaterialDesignUI(content::WebUI* web_ui) :
887 WebUIController(web_ui) {
888 web_ui->AddMessageHandler(new PolicyUIHandler);
889 content::WebUIDataSource::Add(Profile::FromWebUI(web_ui),
890 CreatePolicyMaterialDesignUIHtmlSource());
891 }
892
893 PolicyMaterialDesignUI::~PolicyMaterialDesignUI() {
894 }
OLDNEW
« no previous file with comments | « chrome/browser/ui/webui/policy_ui.h ('k') | chrome/browser/ui/webui/policy_ui_handler.h » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698