Merge Chromium + Blink git repositories
[chromium-blink-merge.git] / chrome / browser / chromeos / policy / user_policy_token_loader.cc
bloba928f722a95ea4c090aff51bbafc0b11e167249c
1 // Copyright (c) 2011 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/chromeos/policy/user_policy_token_loader.h"
7 #include "base/bind.h"
8 #include "base/files/file_util.h"
9 #include "base/location.h"
10 #include "base/metrics/histogram.h"
11 #include "base/sequenced_task_runner.h"
12 #include "base/single_thread_task_runner.h"
13 #include "base/thread_task_runner_handle.h"
14 #include "components/policy/core/common/cloud/enterprise_metrics.h"
15 #include "policy/proto/device_management_local.pb.h"
17 namespace policy {
19 namespace em = enterprise_management;
21 UserPolicyTokenLoader::Delegate::~Delegate() {}
23 UserPolicyTokenLoader::UserPolicyTokenLoader(
24 const base::WeakPtr<Delegate>& delegate,
25 const base::FilePath& cache_file,
26 scoped_refptr<base::SequencedTaskRunner> background_task_runner)
27 : delegate_(delegate),
28 cache_file_(cache_file),
29 origin_task_runner_(base::ThreadTaskRunnerHandle::Get()),
30 background_task_runner_(background_task_runner) {
33 void UserPolicyTokenLoader::Load() {
34 DCHECK(origin_task_runner_->RunsTasksOnCurrentThread());
35 background_task_runner_->PostTask(
36 FROM_HERE,
37 base::Bind(&UserPolicyTokenLoader::LoadOnBackgroundThread, this));
40 UserPolicyTokenLoader::~UserPolicyTokenLoader() {
43 void UserPolicyTokenLoader::LoadOnBackgroundThread() {
44 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
45 std::string device_token;
46 std::string device_id;
48 if (base::PathExists(cache_file_)) {
49 std::string data;
50 em::DeviceCredentials device_credentials;
51 if (base::ReadFileToString(cache_file_, &data) &&
52 device_credentials.ParseFromArray(data.c_str(), data.size())) {
53 device_token = device_credentials.device_token();
54 device_id = device_credentials.device_id();
55 UMA_HISTOGRAM_ENUMERATION(policy::kMetricToken,
56 kMetricTokenLoadSucceeded,
57 policy::kMetricTokenSize);
58 } else {
59 UMA_HISTOGRAM_ENUMERATION(policy::kMetricToken,
60 kMetricTokenLoadFailed,
61 policy::kMetricTokenSize);
65 origin_task_runner_->PostTask(
66 FROM_HERE,
67 base::Bind(&UserPolicyTokenLoader::NotifyOnOriginThread,
68 this,
69 device_token,
70 device_id));
73 void UserPolicyTokenLoader::NotifyOnOriginThread(const std::string& token,
74 const std::string& device_id) {
75 DCHECK(origin_task_runner_->RunsTasksOnCurrentThread());
76 if (delegate_.get())
77 delegate_->OnTokenLoaded(token, device_id);
80 } // namespace policy