1 // Copyright (c) 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.
5 #ifndef CHROME_BROWSER_CHROMEOS_LOGIN_OAUTH2_LOGIN_MANAGER_H_
6 #define CHROME_BROWSER_CHROMEOS_LOGIN_OAUTH2_LOGIN_MANAGER_H_
10 #include "base/memory/scoped_ptr.h"
11 #include "base/observer_list.h"
12 #include "base/time/time.h"
13 #include "chrome/browser/chromeos/login/oauth2_login_verifier.h"
14 #include "chrome/browser/chromeos/login/oauth2_token_fetcher.h"
15 #include "components/browser_context_keyed_service/browser_context_keyed_service.h"
16 #include "google_apis/gaia/gaia_oauth_client.h"
17 #include "google_apis/gaia/oauth2_token_service.h"
18 #include "net/url_request/url_request_context_getter.h"
20 class GoogleServiceAuthError
;
22 class ProfileOAuth2TokenService
;
26 // This class is responsible for restoring authenticated web sessions out of
27 // OAuth2 refresh tokens or pre-authenticated cookie jar.
28 class OAuth2LoginManager
: public BrowserContextKeyedService
,
29 public gaia::GaiaOAuthClient::Delegate
,
30 public OAuth2LoginVerifier::Delegate
,
31 public OAuth2TokenFetcher::Delegate
,
32 public OAuth2TokenService::Observer
{
34 // Session restore states.
35 enum SessionRestoreState
{
36 // Session restore is not started.
37 SESSION_RESTORE_NOT_STARTED
,
38 // Session restore is being prepared.
39 SESSION_RESTORE_PREPARING
,
40 // Session restore is in progress. We are currently issuing calls to verify
41 // stored OAuth tokens and populate cookie jar with GAIA credentials.
42 SESSION_RESTORE_IN_PROGRESS
,
43 // Session restore is completed.
45 // Session restore failed.
46 SESSION_RESTORE_FAILED
,
47 // Session restore failed due to connection or service errors.
48 SESSION_RESTORE_CONNECTION_FAILED
,
51 // Session restore strategy.
52 enum SessionRestoreStrategy
{
53 // Generate OAuth2 refresh token from authentication profile's cookie jar.
54 // Restore session from generated OAuth2 refresh token.
55 RESTORE_FROM_COOKIE_JAR
,
56 // Restore session from saved OAuth2 refresh token from TokenServices.
57 RESTORE_FROM_SAVED_OAUTH2_REFRESH_TOKEN
,
58 // Restore session from OAuth2 refresh token passed via command line.
59 RESTORE_FROM_PASSED_OAUTH2_REFRESH_TOKEN
,
60 // Restore session from authentication code passed via command line.
61 RESTORE_FROM_AUTH_CODE
,
66 virtual ~Observer() {}
68 // Raised when merge session state changes.
69 virtual void OnSessionRestoreStateChanged(Profile
* user_profile
,
70 SessionRestoreState state
) {}
72 // Raised when a new OAuth2 refresh token is avaialble.
73 virtual void OnNewRefreshTokenAvaiable(Profile
* user_profile
) {}
75 // Raised when session's GAIA credentials (SID+LSID) are available to
76 // other signed in services.
77 virtual void OnSessionAuthenticated(Profile
* user_profile
) {}
80 explicit OAuth2LoginManager(Profile
* user_profile
);
81 virtual ~OAuth2LoginManager();
83 void AddObserver(OAuth2LoginManager::Observer
* observer
);
84 void RemoveObserver(OAuth2LoginManager::Observer
* observer
);
86 // Restores and verifies OAuth tokens either following specified
87 // |restore_strategy|. For |restore_strategy| with values
88 // RESTORE_FROM_PASSED_OAUTH2_REFRESH_TOKEN or
89 // RESTORE_FROM_AUTH_CODE, respectively
90 // parameters |oauth2_refresh_token| or |auth_code| need to have non-empty
93 net::URLRequestContextGetter
* auth_request_context
,
94 SessionRestoreStrategy restore_strategy
,
95 const std::string
& oauth2_refresh_token
,
96 const std::string
& auth_code
);
98 // Continues session restore after transient network errors.
99 void ContinueSessionRestore();
101 // Start resporting session from saved OAuth2 refresh token.
102 void RestoreSessionFromSavedTokens();
104 // Stops all background authentication requests.
107 // Returns session restore state.
108 SessionRestoreState
state() { return state_
; }
110 const base::Time
& session_restore_start() { return session_restore_start_
; }
112 // Returns true if the tab loading should block until session restore
114 bool ShouldBlockTabLoading();
117 friend class MergeSessionLoadPageTest
;
119 // Session restore outcomes (for UMA).
121 SESSION_RESTORE_UNDEFINED
= 0,
122 SESSION_RESTORE_SUCCESS
= 1,
123 SESSION_RESTORE_TOKEN_FETCH_FAILED
= 2,
124 SESSION_RESTORE_NO_REFRESH_TOKEN_FAILED
= 3,
125 SESSION_RESTORE_OAUTHLOGIN_FAILED
= 4,
126 SESSION_RESTORE_MERGE_SESSION_FAILED
= 5,
127 SESSION_RESTORE_COUNT
= SESSION_RESTORE_MERGE_SESSION_FAILED
,
130 // Outcomes of post-merge session verification.
131 // This enum is used for an UMA histogram, and hence new items should only be
132 // appended at the end.
133 enum PostMergeVerificationOutcome
{
134 POST_MERGE_UNDEFINED
= 0,
135 POST_MERGE_SUCCESS
= 1,
136 POST_MERGE_NO_ACCOUNTS
= 2,
137 POST_MERGE_MISSING_PRIMARY_ACCOUNT
= 3,
138 POST_MERGE_PRIMARY_NOT_FIRST_ACCOUNT
= 4,
139 POST_MERGE_VERIFICATION_FAILED
= 5,
140 POST_MERGE_CONNECTION_FAILED
= 6,
141 POST_MERGE_COUNT
= 7,
144 // BrowserContextKeyedService implementation.
145 virtual void Shutdown() OVERRIDE
;
147 // gaia::GaiaOAuthClient::Delegate overrides.
148 virtual void OnRefreshTokenResponse(const std::string
& access_token
,
149 int expires_in_seconds
) OVERRIDE
;
150 virtual void OnGetUserEmailResponse(const std::string
& user_email
) OVERRIDE
;
151 virtual void OnOAuthError() OVERRIDE
;
152 virtual void OnNetworkError(int response_code
) OVERRIDE
;
154 // OAuth2LoginVerifier::Delegate overrides.
155 virtual void OnSessionMergeSuccess() OVERRIDE
;
156 virtual void OnSessionMergeFailure(bool connection_error
) OVERRIDE
;
157 virtual void OnListAccountsSuccess(const std::string
& data
) OVERRIDE
;
158 virtual void OnListAccountsFailure(bool connection_error
) OVERRIDE
;
160 // OAuth2TokenFetcher::Delegate overrides.
161 virtual void OnOAuth2TokensAvailable(
162 const GaiaAuthConsumer::ClientOAuthResult
& oauth2_tokens
) OVERRIDE
;
163 virtual void OnOAuth2TokensFetchFailed() OVERRIDE
;
165 // OAuth2TokenService::Observer implementation:
166 virtual void OnRefreshTokenAvailable(const std::string
& account_id
) OVERRIDE
;
168 // Signals delegate that authentication is completed, kicks off token fetching
170 void CompleteAuthentication();
172 // Retrieves ProfileOAuth2TokenService for |user_profile_|.
173 ProfileOAuth2TokenService
* GetTokenService();
175 // Records |refresh_token_| to token service. The associated account id is
176 // assumed to be the primary account id of the user profile. If the primary
177 // account id is not present, GetAccountIdOfRefreshToken will be called to
178 // retrieve the associated account id.
179 void StoreOAuth2Token();
181 // Get the account id corresponding to the specified refresh token.
182 void GetAccountIdOfRefreshToken(const std::string
& refresh_token
);
184 // Attempts to fetch OAuth2 tokens by using pre-authenticated cookie jar from
185 // provided |auth_profile|.
186 void FetchOAuth2Tokens();
188 // Reports when all tokens are loaded.
189 void ReportOAuth2TokensLoaded();
191 // Issue GAIA cookie recovery (MergeSession) from |refresh_token_|.
192 void RestoreSessionCookies();
194 // Checks GAIA error and figures out whether the request should be
196 bool RetryOnError(const GoogleServiceAuthError
& error
);
198 // Changes |state_|, if needed fires observers (OnSessionRestoreStateChanged).
199 void SetSessionRestoreState(SessionRestoreState state
);
202 void SetSessionRestoreStartForTesting(const base::Time
& time
);
204 // Records |outcome| of post merge verification check.
205 static void RecordPostMergeOutcome(PostMergeVerificationOutcome outcome
);
207 // Keeps the track if we have already reported OAuth2 token being loaded
208 // by OAuth2TokenService.
209 Profile
* user_profile_
;
210 scoped_refptr
<net::URLRequestContextGetter
> auth_request_context_
;
211 SessionRestoreStrategy restore_strategy_
;
212 SessionRestoreState state_
;
214 scoped_ptr
<OAuth2TokenFetcher
> oauth2_token_fetcher_
;
215 scoped_ptr
<OAuth2LoginVerifier
> login_verifier_
;
216 scoped_ptr
<gaia::GaiaOAuthClient
> account_id_fetcher_
;
218 // OAuth2 refresh token.
219 std::string refresh_token_
;
221 // OAuthLogin scoped access token.
222 std::string oauthlogin_access_token_
;
224 // Authorization code for fetching OAuth2 tokens.
225 std::string auth_code_
;
227 // Session restore start time.
228 base::Time session_restore_start_
;
230 // List of observers to notify when token availability changes.
231 // Makes sure list is empty on destruction.
232 // TODO(zelidrag|gspencer): Figure out how to get rid of ProfileHelper so we
233 // can change the line below to ObserverList<Observer, true>.
234 ObserverList
<Observer
, false> observer_list_
;
236 DISALLOW_COPY_AND_ASSIGN(OAuth2LoginManager
);
239 } // namespace chromeos
241 #endif // CHROME_BROWSER_CHROMEOS_LOGIN_OAUTH2_LOGIN_MANAGER_H_