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

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

Powered by Google App Engine
This is Rietveld 408576698