- add sources.
[platform/framework/web/crosswalk.git] / src / chrome / browser / policy / cloud / user_policy_signin_service_android.cc
1 // Copyright 2013 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.
4
5 #include "chrome/browser/policy/cloud/user_policy_signin_service_android.h"
6
7 #include "base/bind.h"
8 #include "base/bind_helpers.h"
9 #include "base/callback.h"
10 #include "base/command_line.h"
11 #include "base/logging.h"
12 #include "base/message_loop/message_loop.h"
13 #include "base/prefs/pref_service.h"
14 #include "base/time/time.h"
15 #include "chrome/browser/policy/cloud/cloud_policy_client_registration_helper.h"
16 #include "chrome/browser/policy/cloud/user_cloud_policy_manager.h"
17 #include "chrome/browser/policy/proto/cloud/device_management_backend.pb.h"
18 #include "chrome/browser/profiles/profile.h"
19 #include "chrome/browser/signin/profile_oauth2_token_service_factory.h"
20 #include "chrome/browser/signin/signin_manager.h"
21 #include "chrome/common/pref_names.h"
22 #include "components/policy/core/common/policy_switches.h"
23 #include "net/base/network_change_notifier.h"
24 #include "net/url_request/url_request_context_getter.h"
25
26 namespace policy {
27
28 namespace {
29
30 enterprise_management::DeviceRegisterRequest::Type GetRegistrationType() {
31   CommandLine* command_line = CommandLine::ForCurrentProcess();
32   if (command_line->HasSwitch(switches::kFakeCloudPolicyType))
33     return enterprise_management::DeviceRegisterRequest::BROWSER;
34   return enterprise_management::DeviceRegisterRequest::ANDROID_BROWSER;
35 }
36
37 }  // namespace
38
39 UserPolicySigninService::UserPolicySigninService(
40     Profile* profile,
41     PrefService* local_state,
42     scoped_refptr<net::URLRequestContextGetter> request_context,
43     DeviceManagementService* device_management_service,
44     ProfileOAuth2TokenService* token_service)
45     : UserPolicySigninServiceBase(profile,
46                                   local_state,
47                                   request_context,
48                                   device_management_service),
49       weak_factory_(this),
50       oauth2_token_service_(token_service) {}
51
52 UserPolicySigninService::~UserPolicySigninService() {}
53
54 void UserPolicySigninService::RegisterPolicyClient(
55     const std::string& username,
56     const PolicyRegistrationCallback& callback) {
57   // Create a new CloudPolicyClient for fetching the DMToken.
58   scoped_ptr<CloudPolicyClient> policy_client = PrepareToRegister(username);
59   if (!policy_client) {
60     callback.Run(policy_client.Pass());
61     return;
62   }
63
64   CancelPendingRegistration();
65
66   // Fire off the registration process. Callback keeps the CloudPolicyClient
67   // alive for the length of the registration process.
68   const bool force_load_policy = false;
69   registration_helper_.reset(new CloudPolicyClientRegistrationHelper(
70       profile()->GetRequestContext(),
71       policy_client.get(),
72       force_load_policy,
73       GetRegistrationType()));
74   registration_helper_->StartRegistration(
75       oauth2_token_service_,
76       username,
77       base::Bind(&UserPolicySigninService::CallPolicyRegistrationCallback,
78                  base::Unretained(this),
79                  base::Passed(&policy_client),
80                  callback));
81 }
82
83 void UserPolicySigninService::CallPolicyRegistrationCallback(
84     scoped_ptr<CloudPolicyClient> client,
85     PolicyRegistrationCallback callback) {
86   registration_helper_.reset();
87   if (!client->is_registered()) {
88     // Registration failed, so free the client and pass NULL to the callback.
89     client.reset();
90   }
91   callback.Run(client.Pass());
92 }
93
94 void UserPolicySigninService::Shutdown() {
95   CancelPendingRegistration();
96   registration_helper_.reset();
97   UserPolicySigninServiceBase::Shutdown();
98 }
99
100 void UserPolicySigninService::OnInitializationCompleted(
101     CloudPolicyService* service) {
102   UserCloudPolicyManager* manager = GetManager();
103   DCHECK_EQ(service, manager->core()->service());
104   DCHECK(service->IsInitializationComplete());
105   // The service is now initialized - if the client is not yet registered, then
106   // it means that there is no cached policy and so we need to initiate a new
107   // client registration.
108   if (manager->IsClientRegistered()) {
109     DVLOG(1) << "Client already registered - not fetching DMToken";
110     return;
111   }
112
113   net::NetworkChangeNotifier::ConnectionType connection_type =
114       net::NetworkChangeNotifier::GetConnectionType();
115   base::TimeDelta retry_delay = base::TimeDelta::FromDays(3);
116   if (connection_type == net::NetworkChangeNotifier::CONNECTION_ETHERNET ||
117       connection_type == net::NetworkChangeNotifier::CONNECTION_WIFI) {
118     retry_delay = base::TimeDelta::FromDays(1);
119   }
120
121   base::Time last_check_time = base::Time::FromInternalValue(
122       profile()->GetPrefs()->GetInt64(prefs::kLastPolicyCheckTime));
123   base::Time now = base::Time::Now();
124   base::Time next_check_time = last_check_time + retry_delay;
125
126   // Check immediately if no check was ever done before (last_check_time == 0),
127   // or if the last check was in the future (?), or if we're already past the
128   // next check time. Otherwise, delay checking until the next check time.
129   base::TimeDelta try_registration_delay = base::TimeDelta::FromSeconds(5);
130   if (now > last_check_time && now < next_check_time)
131     try_registration_delay = next_check_time - now;
132
133   base::MessageLoop::current()->PostDelayedTask(
134       FROM_HERE,
135       base::Bind(&UserPolicySigninService::RegisterCloudPolicyService,
136                  weak_factory_.GetWeakPtr()),
137       try_registration_delay);
138 }
139
140 void UserPolicySigninService::RegisterCloudPolicyService() {
141   // If the user signed-out while this task was waiting then Shutdown() would
142   // have been called, which would have invalidated this task. Since we're here
143   // then the user must still be signed-in.
144   const std::string& username = GetSigninManager()->GetAuthenticatedUsername();
145   DCHECK(!username.empty());
146   DCHECK(!GetManager()->IsClientRegistered());
147   DCHECK(GetManager()->core()->client());
148
149   // Persist the current time as the last policy registration attempt time.
150   profile()->GetPrefs()->SetInt64(prefs::kLastPolicyCheckTime,
151                                   base::Time::Now().ToInternalValue());
152
153   const bool force_load_policy = false;
154   registration_helper_.reset(new CloudPolicyClientRegistrationHelper(
155       profile()->GetRequestContext(),
156       GetManager()->core()->client(),
157       force_load_policy,
158       GetRegistrationType()));
159   registration_helper_->StartRegistration(
160       oauth2_token_service_,
161       username,
162       base::Bind(&UserPolicySigninService::OnRegistrationDone,
163                  base::Unretained(this)));
164 }
165
166 void UserPolicySigninService::CancelPendingRegistration() {
167   weak_factory_.InvalidateWeakPtrs();
168 }
169
170 void UserPolicySigninService::OnRegistrationDone() {
171   registration_helper_.reset();
172 }
173
174 }  // namespace policy