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

Side by Side Diff: chrome/browser/policy/user_policy_signin_service.cc

Issue 12220060: Load policy before signin completes. (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src
Patch Set: Merge with ToT. Created 7 years, 10 months 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 | Annotate | Revision Log
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/policy/user_policy_signin_service.h" 5 #include "chrome/browser/policy/user_policy_signin_service.h"
6 6
7 #include <vector>
8
7 #include "base/values.h" 9 #include "base/values.h"
8 #include "chrome/browser/browser_process.h" 10 #include "chrome/browser/browser_process.h"
9 #include "chrome/browser/policy/browser_policy_connector.h" 11 #include "chrome/browser/policy/browser_policy_connector.h"
12 #include "chrome/browser/policy/cloud_policy_client.h"
10 #include "chrome/browser/policy/cloud_policy_service.h" 13 #include "chrome/browser/policy/cloud_policy_service.h"
11 #include "chrome/browser/policy/user_cloud_policy_manager.h" 14 #include "chrome/browser/policy/user_cloud_policy_manager.h"
12 #include "chrome/browser/policy/user_cloud_policy_manager_factory.h" 15 #include "chrome/browser/policy/user_cloud_policy_manager_factory.h"
16 #include "chrome/browser/policy/user_info_fetcher.h"
13 #include "chrome/browser/prefs/pref_service.h" 17 #include "chrome/browser/prefs/pref_service.h"
14 #include "chrome/browser/profiles/profile.h" 18 #include "chrome/browser/profiles/profile.h"
15 #include "chrome/browser/signin/signin_manager.h" 19 #include "chrome/browser/signin/signin_manager.h"
16 #include "chrome/browser/signin/signin_manager_factory.h" 20 #include "chrome/browser/signin/signin_manager_factory.h"
17 #include "chrome/browser/signin/token_service.h" 21 #include "chrome/browser/signin/token_service.h"
18 #include "chrome/browser/signin/token_service_factory.h" 22 #include "chrome/browser/signin/token_service_factory.h"
19 #include "chrome/common/chrome_notification_types.h" 23 #include "chrome/common/chrome_notification_types.h"
20 #include "chrome/common/pref_names.h" 24 #include "chrome/common/pref_names.h"
21 #include "content/public/browser/notification_details.h" 25 #include "content/public/browser/notification_details.h"
22 #include "content/public/browser/notification_source.h" 26 #include "content/public/browser/notification_source.h"
23 #include "google_apis/gaia/gaia_constants.h" 27 #include "google_apis/gaia/gaia_constants.h"
24 #include "google_apis/gaia/gaia_urls.h" 28 #include "google_apis/gaia/gaia_urls.h"
29 #include "google_apis/gaia/oauth2_access_token_consumer.h"
25 #include "google_apis/gaia/oauth2_access_token_fetcher.h" 30 #include "google_apis/gaia/oauth2_access_token_fetcher.h"
26 31
32 namespace em = enterprise_management;
33
27 namespace { 34 namespace {
35
28 // Various OAuth service scopes required to do CloudPolicyClient registration. 36 // Various OAuth service scopes required to do CloudPolicyClient registration.
29 const char kServiceScopeChromeOSDeviceManagement[] = 37 const char kServiceScopeChromeOSDeviceManagement[] =
30 "https://www.googleapis.com/auth/chromeosdevicemanagement"; 38 "https://www.googleapis.com/auth/chromeosdevicemanagement";
31 const char kServiceScopeGetUserInfo[] = 39 const char kServiceScopeGetUserInfo[] =
32 "https://www.googleapis.com/auth/userinfo.email"; 40 "https://www.googleapis.com/auth/userinfo.email";
33 41
34 // The key under which the hosted-domain value is stored in the UserInfo 42 // The key under which the hosted-domain value is stored in the UserInfo
35 // response. 43 // response.
36 const char kGetHostedDomainKey[] = "hd"; 44 const char kGetHostedDomainKey[] = "hd";
45
37 } // namespace 46 } // namespace
38 47
39 namespace policy { 48 namespace policy {
40 49
50 // Helper class that registers a CloudPolicyClient and returns the associated
51 // DMToken to the caller.
52 class CloudPolicyClientRegistrationHelper
53 : public policy::CloudPolicyClient::Observer,
54 public OAuth2AccessTokenConsumer,
55 public policy::UserInfoFetcher::Delegate {
56 public:
57 explicit CloudPolicyClientRegistrationHelper(
58 net::URLRequestContextGetter* context);
59
60 virtual ~CloudPolicyClientRegistrationHelper();
61
62 // Starts the client registration process. Callback is invoked when the
63 // registration is complete.
64 void StartRegistration(policy::CloudPolicyClient* client,
65 const std::string& oauth2_login_token,
66 base::Closure callback);
67
68 // OAuth2AccessTokenConsumer implementation.
69 virtual void OnGetTokenSuccess(const std::string& access_token,
70 const base::Time& expiration_time) OVERRIDE;
71 virtual void OnGetTokenFailure(const GoogleServiceAuthError& error) OVERRIDE;
72
73 // UserInfoFetcher::Delegate implementation:
74 virtual void OnGetUserInfoSuccess(const DictionaryValue* response) OVERRIDE;
75 virtual void OnGetUserInfoFailure(
76 const GoogleServiceAuthError& error) OVERRIDE;
77
78 // CloudPolicyClient::Observer implementation.
79 virtual void OnPolicyFetched(policy::CloudPolicyClient* client) OVERRIDE {}
80 virtual void OnRegistrationStateChanged(
81 policy::CloudPolicyClient* client) OVERRIDE;
82 virtual void OnClientError(policy::CloudPolicyClient* client) OVERRIDE;
83
84 private:
85 // Invoked when the registration request has been completed.
86 void RequestCompleted();
87
88 // Fetcher used while obtaining an OAuth token for client registration.
89 scoped_ptr<OAuth2AccessTokenFetcher> oauth2_access_token_fetcher_;
90
91 // Helper class for fetching information from GAIA about the currently
92 // signed-in user.
93 scoped_ptr<policy::UserInfoFetcher> user_info_fetcher_;
94
95 // Access token used to register the CloudPolicyClient and also access
96 // GAIA to get information about the signed in user.
97 std::string oauth_access_token_;
98
99 net::URLRequestContextGetter* context_;
100 policy::CloudPolicyClient* client_;
101 base::Closure callback_;
102 };
103
104 CloudPolicyClientRegistrationHelper::CloudPolicyClientRegistrationHelper(
105 net::URLRequestContextGetter* context) : context_(context) {
106 DCHECK(context_);
107 }
108
109 CloudPolicyClientRegistrationHelper::~CloudPolicyClientRegistrationHelper() {
110 // Clean up any pending observers in case the browser is shutdown while
111 // trying to register for policy.
112 if (client_)
113 client_->RemoveObserver(this);
114 }
115
116 void CloudPolicyClientRegistrationHelper::RequestCompleted() {
117 if (client_) {
118 client_->RemoveObserver(this);
119 // |client_| may be freed by the callback so clear it now.
120 client_ = NULL;
121 callback_.Run();
122 }
123 }
124
125 void CloudPolicyClientRegistrationHelper::StartRegistration(
126 policy::CloudPolicyClient* client,
127 const std::string& login_token,
128 base::Closure callback) {
129 DVLOG(1) << "Starting registration process";
130 DCHECK(client);
131 DCHECK(!client->is_registered());
132 client_ = client;
133 callback_ = callback;
134 client_->AddObserver(this);
135
136 // Start fetching an OAuth2 access token for the device management and
137 // userinfo services.
138 oauth2_access_token_fetcher_.reset(
139 new OAuth2AccessTokenFetcher(this, context_));
140 std::vector<std::string> scopes;
141 scopes.push_back(kServiceScopeChromeOSDeviceManagement);
142 scopes.push_back(kServiceScopeGetUserInfo);
143 GaiaUrls* gaia_urls = GaiaUrls::GetInstance();
144 oauth2_access_token_fetcher_->Start(
145 gaia_urls->oauth2_chrome_client_id(),
146 gaia_urls->oauth2_chrome_client_secret(),
147 login_token,
148 scopes);
149 }
150
151 void CloudPolicyClientRegistrationHelper::OnGetTokenFailure(
152 const GoogleServiceAuthError& error) {
153 DLOG(WARNING) << "Could not fetch access token for "
154 << kServiceScopeChromeOSDeviceManagement;
155 oauth2_access_token_fetcher_.reset();
156
157 // Invoke the callback to let them know the fetch failed.
158 RequestCompleted();
159 }
160
161 void CloudPolicyClientRegistrationHelper::OnGetTokenSuccess(
162 const std::string& access_token,
163 const base::Time& expiration_time) {
164 // Cache the access token to be used after the GetUserInfo call.
165 oauth_access_token_ = access_token;
166 DVLOG(1) << "Fetched new scoped OAuth token:" << oauth_access_token_;
167 oauth2_access_token_fetcher_.reset();
168 // Now we've gotten our access token - contact GAIA to see if this is a
169 // hosted domain.
170 user_info_fetcher_.reset(new policy::UserInfoFetcher(this, context_));
171 user_info_fetcher_->Start(oauth_access_token_);
172 }
173
174 void CloudPolicyClientRegistrationHelper::OnGetUserInfoFailure(
175 const GoogleServiceAuthError& error) {
176 user_info_fetcher_.reset();
177 RequestCompleted();
178 }
179
180 void CloudPolicyClientRegistrationHelper::OnGetUserInfoSuccess(
181 const DictionaryValue* data) {
182 user_info_fetcher_.reset();
183 if (!data->HasKey(kGetHostedDomainKey)) {
184 VLOG(1) << "User not from a hosted domain - skipping registration";
185 RequestCompleted();
186 return;
187 }
188 VLOG(1) << "Registering CloudPolicyClient for user from hosted domain";
189 // The user is from a hosted domain, so it's OK to register the
190 // CloudPolicyClient and make requests to DMServer.
191 if (client_->is_registered()) {
192 // Client should not be registered yet.
193 NOTREACHED();
194 RequestCompleted();
195 return;
196 }
197
198 // Kick off registration of the CloudPolicyClient with our newly minted
199 // oauth_access_token_.
200 client_->Register(em::DeviceRegisterRequest::BROWSER, oauth_access_token_,
201 std::string(), false);
202 }
203
204 void CloudPolicyClientRegistrationHelper::OnRegistrationStateChanged(
205 policy::CloudPolicyClient* client) {
206 DCHECK_EQ(client, client_);
207 DCHECK(client->is_registered());
208 RequestCompleted();
209 }
210
211 void CloudPolicyClientRegistrationHelper::OnClientError(
212 policy::CloudPolicyClient* client) {
213 DCHECK_EQ(client, client_);
214 RequestCompleted();
215 }
216
41 UserPolicySigninService::UserPolicySigninService( 217 UserPolicySigninService::UserPolicySigninService(
42 Profile* profile) 218 Profile* profile)
43 : ALLOW_THIS_IN_INITIALIZER_LIST(weak_factory_(this)), 219 : profile_(profile) {
44 profile_(profile),
45 pending_fetch_(false) {
46
47 if (profile_->GetPrefs()->GetBoolean(prefs::kDisableCloudPolicyOnSignin)) 220 if (profile_->GetPrefs()->GetBoolean(prefs::kDisableCloudPolicyOnSignin))
48 return; 221 return;
49 222
50 // Initialize/shutdown the UserCloudPolicyManager when the user signs out. 223 // Initialize/shutdown the UserCloudPolicyManager when the user signs out.
51 registrar_.Add(this, 224 registrar_.Add(this,
52 chrome::NOTIFICATION_GOOGLE_SIGNED_OUT, 225 chrome::NOTIFICATION_GOOGLE_SIGNED_OUT,
53 content::Source<Profile>(profile)); 226 content::Source<Profile>(profile));
54 227
55 // Listen for an OAuth token to become available so we can register a client 228 // Listen for an OAuth token to become available so we can register a client
56 // if for some reason the client is not already registered (for example, if 229 // if for some reason the client is not already registered (for example, if
(...skipping 10 matching lines...) Expand all
67 240
68 // Register a listener to be called back once the current profile has finished 241 // Register a listener to be called back once the current profile has finished
69 // initializing, so we can startup the UserCloudPolicyManager. 242 // initializing, so we can startup the UserCloudPolicyManager.
70 registrar_.Add(this, 243 registrar_.Add(this,
71 chrome::NOTIFICATION_PROFILE_ADDED, 244 chrome::NOTIFICATION_PROFILE_ADDED,
72 content::Source<Profile>(profile)); 245 content::Source<Profile>(profile));
73 } 246 }
74 247
75 UserPolicySigninService::~UserPolicySigninService() {} 248 UserPolicySigninService::~UserPolicySigninService() {}
76 249
77 void UserPolicySigninService::FetchPolicyForSignedInUser( 250 void UserPolicySigninService::RegisterPolicyClient(
78 const std::string& oauth2_access_token, 251 const std::string& username,
79 const PolicyFetchCallback& callback) { 252 const std::string& oauth2_refresh_token,
80 if (!ShouldLoadPolicyForSignedInUser()) { 253 const PolicyRegistrationCallback& callback) {
81 callback.Run(false); 254 DCHECK(!username.empty());
255 DCHECK(!oauth2_refresh_token.empty());
256 // We should not be called with a client already initialized.
257 DCHECK(!GetManager() || !GetManager()->core()->client());
258
259 // If the user should not get policy, just bail out.
260 if (!GetManager() || !ShouldLoadPolicyForUser(username)) {
261 DVLOG(1) << "Signed in user is not in the whitelist";
262 callback.Run(scoped_ptr<CloudPolicyClient>().Pass());
82 return; 263 return;
83 } 264 }
84 265
85 // If the DeviceManagementService is not yet initialized, start it up now. 266 // If the DeviceManagementService is not yet initialized, start it up now.
86 g_browser_process->browser_policy_connector()-> 267 g_browser_process->browser_policy_connector()->
87 ScheduleServiceInitialization(0); 268 ScheduleServiceInitialization(0);
88 269
270 // Create a new CloudPolicyClient for fetching the DMToken.
271 scoped_ptr<CloudPolicyClient> policy_client(
272 UserCloudPolicyManager::CreateCloudPolicyClient(
273 g_browser_process->browser_policy_connector()->
274 device_management_service()));
275
276 registration_helper_.reset(
277 new CloudPolicyClientRegistrationHelper(profile_->GetRequestContext()));
278
279 // Fire off the registration process. Callback keeps the CloudPolicyClient
280 // alive for the length of the registration process.
281 // Grab a pointer to the client before base::Bind() clears the reference in
282 // |policy_client|.
283 CloudPolicyClient* client = policy_client.get();
284 base::Closure registration_callback =
285 base::Bind(&UserPolicySigninService::CallPolicyRegistrationCallback,
286 base::Unretained(this), base::Passed(&policy_client),
287 callback);
288 registration_helper_->StartRegistration(
289 client, oauth2_refresh_token, registration_callback);
290 }
291
292 void UserPolicySigninService::CallPolicyRegistrationCallback(
293 scoped_ptr<CloudPolicyClient> client,
294 PolicyRegistrationCallback callback) {
295 registration_helper_.reset();
296 if (!client->is_registered()) {
297 // Registration failed, so free the client and pass NULL to the callback.
298 client.reset();
299 }
300 callback.Run(client.Pass());
301 }
302
303 void UserPolicySigninService::FetchPolicyForSignedInUser(
304 scoped_ptr<CloudPolicyClient> client,
305 const PolicyFetchCallback& callback) {
306 DCHECK(client);
307 DCHECK(client->is_registered());
89 // The user has just signed in, so the UserCloudPolicyManager should not yet 308 // The user has just signed in, so the UserCloudPolicyManager should not yet
90 // be initialized, and the client should not be registered because there 309 // be initialized. This routine will initialize the UserCloudPolicyManager
91 // should be no cached policy. This routine will proactively ask the client 310 // with the passed client and will proactively ask the client to fetch
92 // to register itself without waiting for the CloudPolicyService to finish 311 // policy without waiting for the CloudPolicyService to finish initialization.
93 // initialization. 312 UserCloudPolicyManager* manager = GetManager();
94 DCHECK(!GetManager()->core()->service()); 313 DCHECK(manager);
95 InitializeUserCloudPolicyManager(); 314 DCHECK(!manager->core()->client());
96 DCHECK(!GetManager()->IsClientRegistered()); 315 InitializeUserCloudPolicyManager(client.Pass());
316 DCHECK(manager->IsClientRegistered());
97 317
98 DCHECK(!pending_fetch_); 318 // Now initiate a policy fetch.
99 pending_fetch_ = true; 319 manager->core()->service()->RefreshPolicy(callback);
100 pending_fetch_callback_ = callback;
101
102 // Register the client using this access token.
103 RegisterCloudPolicyService(oauth2_access_token);
104 } 320 }
105 321
106 void UserPolicySigninService::StopObserving() { 322 void UserPolicySigninService::StopObserving() {
107 UserCloudPolicyManager* manager = GetManager(); 323 UserCloudPolicyManager* manager = GetManager();
108 if (manager) { 324 if (manager && manager->core()->service())
109 if (manager->core()->service()) 325 manager->core()->service()->RemoveObserver(this);
110 manager->core()->service()->RemoveObserver(this);
111 if (manager->core()->client())
112 manager->core()->client()->RemoveObserver(this);
113 }
114 } 326 }
115 327
116 void UserPolicySigninService::StartObserving() { 328 void UserPolicySigninService::StartObserving() {
117 UserCloudPolicyManager* manager = GetManager(); 329 UserCloudPolicyManager* manager = GetManager();
118 // Manager should be fully initialized by now. 330 // Manager should be fully initialized by now.
119 DCHECK(manager); 331 DCHECK(manager);
120 DCHECK(manager->core()->service()); 332 DCHECK(manager->core()->service());
121 DCHECK(manager->core()->client());
122 manager->core()->service()->AddObserver(this); 333 manager->core()->service()->AddObserver(this);
123 manager->core()->client()->AddObserver(this);
124 } 334 }
125 335
126 void UserPolicySigninService::Observe( 336 void UserPolicySigninService::Observe(
127 int type, 337 int type,
128 const content::NotificationSource& source, 338 const content::NotificationSource& source,
129 const content::NotificationDetails& details) { 339 const content::NotificationDetails& details) {
130 // If using a TestingProfile with no SigninManager or UserCloudPolicyManager, 340 // If using a TestingProfile with no SigninManager or UserCloudPolicyManager,
131 // skip initialization. 341 // skip initialization.
132 if (!GetManager() || !SigninManagerFactory::GetForProfile(profile_)) { 342 if (!GetManager() || !SigninManagerFactory::GetForProfile(profile_)) {
133 DVLOG(1) << "Skipping initialization for tests due to missing components."; 343 DVLOG(1) << "Skipping initialization for tests due to missing components.";
134 return; 344 return;
135 } 345 }
136 346
137 switch (type) { 347 switch (type) {
138 case chrome::NOTIFICATION_GOOGLE_SIGNED_OUT: 348 case chrome::NOTIFICATION_GOOGLE_SIGNED_OUT:
139 ShutdownUserCloudPolicyManager(); 349 ShutdownUserCloudPolicyManager();
140 break; 350 break;
141 case chrome::NOTIFICATION_PROFILE_ADDED: { 351 case chrome::NOTIFICATION_PROFILE_ADDED: {
142 // A new profile has been loaded - if it's signed in, then initialize the 352 // A new profile has been loaded - if it's signed in, then initialize the
143 // UCPM, otherwise shut down the UCPM (which deletes any cached policy 353 // UCPM, otherwise shut down the UCPM (which deletes any cached policy
144 // data). This must be done here instead of at constructor time because 354 // data). This must be done here instead of at constructor time because
145 // the Profile is not fully initialized when this object is constructed 355 // the Profile is not fully initialized when this object is constructed
146 // (DoFinalInit() has not yet been called, so ProfileIOData and 356 // (DoFinalInit() has not yet been called, so ProfileIOData and
147 // SSLConfigServiceManager have not been created yet). 357 // SSLConfigServiceManager have not been created yet).
148 // TODO(atwilson): Switch to using a timer instead, to avoid contention 358 // TODO(atwilson): Switch to using a timer instead, to avoid contention
149 // with other services at startup (http://crbug.com/165468). 359 // with other services at startup (http://crbug.com/165468).
150 SigninManager* signin_manager = 360 SigninManager* signin_manager =
151 SigninManagerFactory::GetForProfile(profile_); 361 SigninManagerFactory::GetForProfile(profile_);
152 if (signin_manager->GetAuthenticatedUsername().empty()) 362 std::string username = signin_manager->GetAuthenticatedUsername();
363 if (username.empty())
153 ShutdownUserCloudPolicyManager(); 364 ShutdownUserCloudPolicyManager();
154 else 365 else
155 InitializeUserCloudPolicyManager(); 366 InitializeForSignedInUser();
156 break; 367 break;
157 } 368 }
158 case chrome::NOTIFICATION_TOKEN_AVAILABLE: { 369 case chrome::NOTIFICATION_TOKEN_AVAILABLE: {
159 const TokenService::TokenAvailableDetails& token_details = 370 const TokenService::TokenAvailableDetails& token_details =
160 *(content::Details<const TokenService::TokenAvailableDetails>( 371 *(content::Details<const TokenService::TokenAvailableDetails>(
161 details).ptr()); 372 details).ptr());
162 if (token_details.service() == 373 if (token_details.service() ==
163 GaiaConstants::kGaiaOAuth2LoginRefreshToken) { 374 GaiaConstants::kGaiaOAuth2LoginRefreshToken) {
375 SigninManager* signin_manager =
376 SigninManagerFactory::GetForProfile(profile_);
377 std::string username = signin_manager->GetAuthenticatedUsername();
378 // Should not have GAIA tokens if the user isn't signed in.
379 DCHECK(!username.empty());
164 // TokenService now has a refresh token (implying that the user is 380 // TokenService now has a refresh token (implying that the user is
165 // signed in) so initialize the UserCloudPolicyManager. 381 // signed in) so initialize the UserCloudPolicyManager.
166 InitializeUserCloudPolicyManager(); 382 InitializeForSignedInUser();
167 } 383 }
168 break; 384 break;
169 } 385 }
170 default: 386 default:
171 NOTREACHED(); 387 NOTREACHED();
172 } 388 }
173 } 389 }
174 390
175 bool UserPolicySigninService::ShouldLoadPolicyForSignedInUser() { 391 bool UserPolicySigninService::ShouldLoadPolicyForUser(
392 const std::string& username) {
176 if (profile_->GetPrefs()->GetBoolean(prefs::kDisableCloudPolicyOnSignin)) 393 if (profile_->GetPrefs()->GetBoolean(prefs::kDisableCloudPolicyOnSignin))
177 return false; // Cloud policy is disabled. 394 return false; // Cloud policy is disabled.
178 395
179 const std::string& username = SigninManagerFactory::GetForProfile(profile_)->
180 GetAuthenticatedUsername();
181
182 if (username.empty()) 396 if (username.empty())
183 return false; // Not signed in. 397 return false; // Not signed in.
184 398
185 return !BrowserPolicyConnector::IsNonEnterpriseUser(username); 399 return !BrowserPolicyConnector::IsNonEnterpriseUser(username);
186 } 400 }
187 401
188 void UserPolicySigninService::InitializeUserCloudPolicyManager() { 402 void UserPolicySigninService::InitializeUserCloudPolicyManager(
189 if (!ShouldLoadPolicyForSignedInUser()) { 403 scoped_ptr<CloudPolicyClient> client) {
190 VLOG(1) << "Policy load not enabled for user: " << 404 UserCloudPolicyManager* manager = GetManager();
191 SigninManagerFactory::GetForProfile(profile_)-> 405 DCHECK(!manager->core()->client());
192 GetAuthenticatedUsername(); 406 // If there is no cached DMToken then we can detect this below (or when
407 // the OnInitializationCompleted() callback is invoked).
408 manager->Connect(g_browser_process->local_state(), client.Pass());
409 DCHECK(manager->core()->service());
410 StartObserving();
411 }
412
413 void UserPolicySigninService::InitializeForSignedInUser() {
414 SigninManager* signin_manager =
415 SigninManagerFactory::GetForProfile(profile_);
416 std::string username = signin_manager->GetAuthenticatedUsername();
417
418 if (!ShouldLoadPolicyForUser(username)) {
419 VLOG(1) << "Policy load not enabled for user: " << username;
193 return; 420 return;
194 } 421 }
422 DCHECK(!username.empty());
195 423
196 UserCloudPolicyManager* manager = GetManager(); 424 UserCloudPolicyManager* manager = GetManager();
197 DCHECK(!SigninManagerFactory::GetForProfile(profile_)-> 425 // Initialize the UCPM if it is not already initialized.
198 GetAuthenticatedUsername().empty());
199 if (!manager->core()->service()) { 426 if (!manager->core()->service()) {
200 // If there is no cached DMToken then we can detect this below (or when 427 // If there is no cached DMToken then we can detect this when the
201 // the OnInitializationCompleted() callback is invoked). 428 // OnInitializationCompleted() callback is invoked and this will
429 // initiate a policy fetch.
202 BrowserPolicyConnector* connector = 430 BrowserPolicyConnector* connector =
203 g_browser_process->browser_policy_connector(); 431 g_browser_process->browser_policy_connector();
204 manager->Connect(g_browser_process->local_state(), 432 InitializeUserCloudPolicyManager(
205 connector->device_management_service()); 433 UserCloudPolicyManager::CreateCloudPolicyClient(
206 DCHECK(manager->core()->service()); 434 connector->device_management_service()).Pass());
207 StartObserving();
208 } 435 }
209 436
210 // If the CloudPolicyService is initialized, kick off registration. If the 437 // If the CloudPolicyService is initialized, kick off registration. If the
211 // TokenService doesn't have an OAuth token yet (e.g. this is during initial 438 // TokenService doesn't have an OAuth token yet (e.g. this is during initial
212 // signin, or when dynamically loading a signed-in policy) this does nothing 439 // signin, or when dynamically loading a signed-in policy) this does nothing
213 // until the OAuth token is loaded. 440 // until the OAuth token is loaded.
214 if (manager->core()->service()->IsInitializationComplete()) 441 if (manager->core()->service()->IsInitializationComplete())
215 OnInitializationCompleted(manager->core()->service()); 442 OnInitializationCompleted(manager->core()->service());
216 } 443 }
217 444
218 void UserPolicySigninService::ShutdownUserCloudPolicyManager() { 445 void UserPolicySigninService::ShutdownUserCloudPolicyManager() {
219 // Stop any in-progress token fetch. 446 // Stop any in-progress token fetch.
220 oauth2_access_token_fetcher_.reset(); 447 registration_helper_.reset();
221 user_info_fetcher_.reset();
222 oauth_access_token_.clear();
223 448
224 StopObserving(); 449 StopObserving();
225 NotifyPendingFetchCallback(false);
226 450
227 UserCloudPolicyManager* manager = GetManager(); 451 UserCloudPolicyManager* manager = GetManager();
228 if (manager) // Can be null in unit tests. 452 if (manager) // Can be null in unit tests.
229 manager->DisconnectAndRemovePolicy(); 453 manager->DisconnectAndRemovePolicy();
230 } 454 }
231 455
232 void UserPolicySigninService::OnInitializationCompleted( 456 void UserPolicySigninService::OnInitializationCompleted(
233 CloudPolicyService* service) { 457 CloudPolicyService* service) {
234 UserCloudPolicyManager* manager = GetManager(); 458 UserCloudPolicyManager* manager = GetManager();
235 DCHECK_EQ(service, manager->core()->service()); 459 DCHECK_EQ(service, manager->core()->service());
(...skipping 14 matching lines...) Expand all
250 } 474 }
251 RegisterCloudPolicyService(token); 475 RegisterCloudPolicyService(token);
252 } 476 }
253 } 477 }
254 478
255 void UserPolicySigninService::RegisterCloudPolicyService( 479 void UserPolicySigninService::RegisterCloudPolicyService(
256 std::string login_token) { 480 std::string login_token) {
257 DCHECK(!GetManager()->IsClientRegistered()); 481 DCHECK(!GetManager()->IsClientRegistered());
258 DVLOG(1) << "Fetching new DM Token"; 482 DVLOG(1) << "Fetching new DM Token";
259 // Do nothing if already starting the registration process. 483 // Do nothing if already starting the registration process.
260 if (oauth2_access_token_fetcher_.get() || 484 if (registration_helper_)
261 user_info_fetcher_.get() ||
262 !oauth_access_token_.empty()) {
263 return; 485 return;
264 }
265 486
266 // Start fetching an OAuth2 access token for the device management and 487 // Start the process of registering the CloudPolicyClient. Once it completes,
267 // userinfo services. 488 // policy fetch will automatically happen.
268 oauth2_access_token_fetcher_.reset( 489 registration_helper_.reset(
269 new OAuth2AccessTokenFetcher(this, profile_->GetRequestContext())); 490 new CloudPolicyClientRegistrationHelper(profile_->GetRequestContext()));
270 std::vector<std::string> scopes; 491 registration_helper_->StartRegistration(
271 scopes.push_back(kServiceScopeChromeOSDeviceManagement); 492 GetManager()->core()->client(),
272 scopes.push_back(kServiceScopeGetUserInfo);
273 GaiaUrls* gaia_urls = GaiaUrls::GetInstance();
274 oauth2_access_token_fetcher_->Start(
275 gaia_urls->oauth2_chrome_client_id(),
276 gaia_urls->oauth2_chrome_client_secret(),
277 login_token, 493 login_token,
278 scopes); 494 base::Bind(&UserPolicySigninService::OnRegistrationComplete,
495 base::Unretained(this)));
279 } 496 }
280 497
281 void UserPolicySigninService::OnGetTokenFailure( 498 void UserPolicySigninService::OnRegistrationComplete() {
282 const GoogleServiceAuthError& error) { 499 registration_helper_.reset();
283 DLOG(WARNING) << "Could not fetch access token for "
284 << kServiceScopeChromeOSDeviceManagement;
285 oauth2_access_token_fetcher_.reset();
286 // If there was a pending fetch request, let them know the fetch failed.
287 NotifyPendingFetchCallback(false);
288 }
289
290 void UserPolicySigninService::OnGetTokenSuccess(
291 const std::string& access_token,
292 const base::Time& expiration_time) {
293 oauth_access_token_ = access_token;
294 DVLOG(1) << "Fetched new scoped OAuth token:" << oauth_access_token_;
295 oauth2_access_token_fetcher_.reset();
296 // Now we've gotten our access token - contact GAIA to see if this is a
297 // hosted domain.
298 user_info_fetcher_.reset(new UserInfoFetcher(this,
299 profile_->GetRequestContext()));
300 user_info_fetcher_->Start(oauth_access_token_);
301 }
302
303 void UserPolicySigninService::OnGetUserInfoFailure(
304 const GoogleServiceAuthError& error) {
305 user_info_fetcher_.reset();
306 NotifyPendingFetchCallback(false);
307 }
308
309 void UserPolicySigninService::OnGetUserInfoSuccess(
310 const DictionaryValue* data) {
311 user_info_fetcher_.reset();
312 if (!data->HasKey(kGetHostedDomainKey)) {
313 VLOG(1) << "User not from a hosted domain - skipping registration";
314 NotifyPendingFetchCallback(false);
315 return;
316 }
317 VLOG(1) << "Registering CloudPolicyClient for user from hosted domain";
318 // The user is from a hosted domain, so it's OK to register the
319 // CloudPolicyClient and make requests from DMServer.
320 GetManager()->RegisterClient(oauth_access_token_);
321 }
322
323 void UserPolicySigninService::OnRegistrationStateChanged(
324 CloudPolicyClient* client) {
325 DCHECK_EQ(GetManager()->core()->client(), client);
326 if (pending_fetch_) {
327 UserCloudPolicyManager* manager = GetManager();
328 if (manager->IsClientRegistered()) {
329 // Request a policy fetch.
330 manager->core()->service()->RefreshPolicy(
331 base::Bind(
332 &UserPolicySigninService::NotifyPendingFetchCallback,
333 weak_factory_.GetWeakPtr()));
334 } else {
335 // Shouldn't be possible for the client to get unregistered.
336 NOTREACHED() << "Client unregistered while waiting for policy fetch";
337 }
338 }
339 }
340
341 void UserPolicySigninService::NotifyPendingFetchCallback(bool success) {
342 if (pending_fetch_) {
343 pending_fetch_ = false;
344 pending_fetch_callback_.Run(success);
345 }
346 }
347
348 void UserPolicySigninService::OnPolicyFetched(CloudPolicyClient* client) {
349 // Do nothing when policy is fetched - if the policy fetch is successful,
350 // NotifyPendingFetchCallback will be invoked.
351 }
352
353 void UserPolicySigninService::OnClientError(CloudPolicyClient* client) {
354 NotifyPendingFetchCallback(false);
355 } 500 }
356 501
357 void UserPolicySigninService::Shutdown() { 502 void UserPolicySigninService::Shutdown() {
503 // Stop any pending registration helper activity. We do this here instead of
504 // in the destructor because we want to shutdown the registration helper
505 // before UserCloudPolicyManager shuts down the CloudPolicyClient.
506 registration_helper_.reset();
358 StopObserving(); 507 StopObserving();
359 } 508 }
360 509
361 UserCloudPolicyManager* UserPolicySigninService::GetManager() { 510 UserCloudPolicyManager* UserPolicySigninService::GetManager() {
362 return UserCloudPolicyManagerFactory::GetForProfile(profile_); 511 return UserCloudPolicyManagerFactory::GetForProfile(profile_);
363 } 512 }
364 513
365 } // namespace policy 514 } // namespace policy
OLDNEW
« no previous file with comments | « chrome/browser/policy/user_policy_signin_service.h ('k') | chrome/browser/policy/user_policy_signin_service_unittest.cc » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698