1 // Copyright 2014 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_SIGNIN_OAUTH2_LOGIN_MANAGER_H_
6 #define CHROME_BROWSER_CHROMEOS_LOGIN_SIGNIN_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/signin/oauth2_login_verifier.h"
14 #include "chrome/browser/chromeos/login/signin/oauth2_token_fetcher.h"
15 #include "components/keyed_service/core/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 KeyedService
,
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
= 0,
38 // Session restore is being prepared.
39 SESSION_RESTORE_PREPARING
= 1,
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
= 2,
43 // Session restore is completed.
44 SESSION_RESTORE_DONE
= 3,
45 // Session restore failed.
46 SESSION_RESTORE_FAILED
= 4,
47 // Session restore failed due to connection or service errors.
48 SESSION_RESTORE_CONNECTION_FAILED
= 5,
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
,
64 virtual ~Observer() {}
66 // Raised when merge session state changes.
67 virtual void OnSessionRestoreStateChanged(Profile
* user_profile
,
68 SessionRestoreState state
) {}
70 // Raised when a new OAuth2 refresh token is avaialble.
71 virtual void OnNewRefreshTokenAvaiable(Profile
* user_profile
) {}
73 // Raised when session's GAIA credentials (SID+LSID) are available to
74 // other signed in services.
75 virtual void OnSessionAuthenticated(Profile
* user_profile
) {}
78 explicit OAuth2LoginManager(Profile
* user_profile
);
79 ~OAuth2LoginManager() override
;
81 void AddObserver(OAuth2LoginManager::Observer
* observer
);
82 void RemoveObserver(OAuth2LoginManager::Observer
* observer
);
84 // Restores and verifies OAuth tokens following specified |restore_strategy|.
85 // For |restore_strategy| RESTORE_FROM_PASSED_OAUTH2_REFRESH_TOKEN, parameter
86 // |oauth2_refresh_token| needs to have a non-empty value.
87 // For |restore_strategy| RESTORE_FROM_COOKIE_JAR |auth_request_context| must
89 void RestoreSession(net::URLRequestContextGetter
* auth_request_context
,
90 SessionRestoreStrategy restore_strategy
,
91 const std::string
& oauth2_refresh_token
,
92 const std::string
& oauth2_access_token
);
94 // Continues session restore after transient network errors.
95 void ContinueSessionRestore();
97 // Start restoring session from saved OAuth2 refresh token.
98 void RestoreSessionFromSavedTokens();
100 // Stops all background authentication requests.
103 // Returns session restore state.
104 SessionRestoreState
state() { return state_
; }
106 const base::Time
& session_restore_start() { return session_restore_start_
; }
108 bool SessionRestoreIsRunning() const;
110 // Returns true if the tab loading should block until session restore
112 bool ShouldBlockTabLoading() const;
115 friend class MergeSessionLoadPageTest
;
116 friend class OAuth2Test
;
118 // Session restore outcomes (for UMA).
119 enum SessionRestoreOutcome
{
120 SESSION_RESTORE_UNDEFINED
= 0,
121 SESSION_RESTORE_SUCCESS
= 1,
122 SESSION_RESTORE_TOKEN_FETCH_FAILED
= 2,
123 SESSION_RESTORE_NO_REFRESH_TOKEN_FAILED
= 3,
124 SESSION_RESTORE_OAUTHLOGIN_FAILED
= 4,
125 SESSION_RESTORE_MERGE_SESSION_FAILED
= 5,
126 SESSION_RESTORE_LISTACCOUNTS_FAILED
= 6,
127 SESSION_RESTORE_NOT_NEEDED
= 7,
128 SESSION_RESTORE_COUNT
= 8,
131 // Outcomes of post-merge session verification.
132 // This enum is used for an UMA histogram, and hence new items should only be
133 // appended at the end.
134 enum MergeVerificationOutcome
{
135 POST_MERGE_UNDEFINED
= 0,
136 POST_MERGE_SUCCESS
= 1,
137 POST_MERGE_NO_ACCOUNTS
= 2,
138 POST_MERGE_MISSING_PRIMARY_ACCOUNT
= 3,
139 POST_MERGE_PRIMARY_NOT_FIRST_ACCOUNT
= 4,
140 POST_MERGE_VERIFICATION_FAILED
= 5,
141 POST_MERGE_CONNECTION_FAILED
= 6,
142 POST_MERGE_COUNT
= 7,
145 // KeyedService implementation.
146 void Shutdown() override
;
148 // gaia::GaiaOAuthClient::Delegate overrides.
149 void OnRefreshTokenResponse(const std::string
& access_token
,
150 int expires_in_seconds
) override
;
151 void OnGetUserInfoResponse(
152 scoped_ptr
<base::DictionaryValue
> user_info
) override
;
153 void OnOAuthError() override
;
154 void OnNetworkError(int response_code
) override
;
156 // OAuth2LoginVerifier::Delegate overrides.
157 void OnSessionMergeSuccess() override
;
158 void OnSessionMergeFailure(bool connection_error
) override
;
159 void OnListAccountsSuccess(
160 const std::vector
<gaia::ListedAccount
>& accounts
) override
;
161 void OnListAccountsFailure(bool connection_error
) override
;
163 // OAuth2TokenFetcher::Delegate overrides.
164 void OnOAuth2TokensAvailable(
165 const GaiaAuthConsumer::ClientOAuthResult
& oauth2_tokens
) override
;
166 void OnOAuth2TokensFetchFailed() override
;
168 // OAuth2TokenService::Observer implementation:
169 void OnRefreshTokenAvailable(const std::string
& account_id
) override
;
171 // Signals delegate that authentication is completed, kicks off token fetching
173 void CompleteAuthentication();
175 // Retrieves ProfileOAuth2TokenService for |user_profile_|.
176 ProfileOAuth2TokenService
* GetTokenService();
178 // Retrieves the primary account for |user_profile_|.
179 const std::string
& GetPrimaryAccountId();
181 // Records |refresh_token_| to token service. The associated account id is
182 // assumed to be the primary account id of the user profile. If the primary
183 // account id is not present, GetAccountInfoOfRefreshToken will be called to
184 // retrieve the associated account info.
185 void StoreOAuth2Token();
187 // Get the account info corresponding to the specified refresh token.
188 void GetAccountInfoOfRefreshToken(const std::string
& refresh_token
);
190 // Update the token service and inform listeners of a new refresh token.
191 void UpdateCredentials(const std::string
& account_id
);
193 // Attempts to fetch OAuth2 tokens by using pre-authenticated cookie jar from
194 // provided |auth_profile|.
195 void FetchOAuth2Tokens();
197 // Reports when all tokens are loaded.
198 void ReportOAuth2TokensLoaded();
200 // Checks if primary account sessions cookies are stale and restores them
202 void VerifySessionCookies();
204 // Issue GAIA cookie recovery (MergeSession) from |refresh_token_|.
205 void RestoreSessionCookies();
207 // Checks GAIA error and figures out whether the request should be
209 bool RetryOnError(const GoogleServiceAuthError
& error
);
211 // Changes |state_|, if needed fires observers (OnSessionRestoreStateChanged).
212 void SetSessionRestoreState(SessionRestoreState state
);
215 void SetSessionRestoreStartForTesting(const base::Time
& time
);
217 // Records |outcome| of session restore process and sets new |state|.
218 void RecordSessionRestoreOutcome(SessionRestoreOutcome outcome
,
219 SessionRestoreState state
);
221 // Records |outcome| of merge verification check. |is_pre_merge| specifies
222 // if this is pre or post merge session verification.
223 static void RecordCookiesCheckOutcome(
225 MergeVerificationOutcome outcome
);
227 // Keeps the track if we have already reported OAuth2 token being loaded
228 // by OAuth2TokenService.
229 Profile
* user_profile_
;
230 scoped_refptr
<net::URLRequestContextGetter
> auth_request_context_
;
231 SessionRestoreStrategy restore_strategy_
;
232 SessionRestoreState state_
;
234 scoped_ptr
<OAuth2TokenFetcher
> oauth2_token_fetcher_
;
235 scoped_ptr
<OAuth2LoginVerifier
> login_verifier_
;
236 scoped_ptr
<gaia::GaiaOAuthClient
> account_info_fetcher_
;
238 // OAuth2 refresh token.
239 std::string refresh_token_
;
241 // OAuthLogin scoped access token.
242 std::string oauthlogin_access_token_
;
244 // Session restore start time.
245 base::Time session_restore_start_
;
247 // List of observers to notify when token availability changes.
248 // Makes sure list is empty on destruction.
249 // TODO(zelidrag|gspencer): Figure out how to get rid of ProfileHelper so we
250 // can change the line below to base::ObserverList<Observer, true>.
251 base::ObserverList
<Observer
, false> observer_list_
;
253 DISALLOW_COPY_AND_ASSIGN(OAuth2LoginManager
);
256 } // namespace chromeos
258 #endif // CHROME_BROWSER_CHROMEOS_LOGIN_SIGNIN_OAUTH2_LOGIN_MANAGER_H_