- add sources.
[platform/framework/web/crosswalk.git] / src / chrome / browser / chromeos / login / oauth2_login_manager.h
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.
4
5 #ifndef CHROME_BROWSER_CHROMEOS_LOGIN_OAUTH2_LOGIN_MANAGER_H_
6 #define CHROME_BROWSER_CHROMEOS_LOGIN_OAUTH2_LOGIN_MANAGER_H_
7
8 #include <string>
9
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/oauth2_token_service.h"
17 #include "net/url_request/url_request_context_getter.h"
18
19 class GoogleServiceAuthError;
20 class Profile;
21 class TokenService;
22
23 namespace chromeos {
24
25 // This class is responsible for restoring authenticated web sessions out of
26 // OAuth2 refresh tokens or pre-authenticated cookie jar.
27 class OAuth2LoginManager : public BrowserContextKeyedService,
28                            public OAuth2LoginVerifier::Delegate,
29                            public OAuth2TokenFetcher::Delegate,
30                            public OAuth2TokenService::Observer {
31  public:
32   // Session restore states.
33   enum SessionRestoreState {
34     // Session restore is not started.
35     SESSION_RESTORE_NOT_STARTED,
36     // Session restore is being prepared.
37     SESSION_RESTORE_PREPARING,
38     // Session restore is in progress. We are currently issuing calls to verify
39     // stored OAuth tokens and populate cookie jar with GAIA credentials.
40     SESSION_RESTORE_IN_PROGRESS,
41     // Session restore is completed.
42     SESSION_RESTORE_DONE,
43     // Session restore failed.
44     SESSION_RESTORE_FAILED,
45     // Session restore failed due to connection or service errors.
46     SESSION_RESTORE_CONNECTION_FAILED,
47   };
48
49   // Session restore strategy.
50   enum SessionRestoreStrategy {
51     // Generate OAuth2 refresh token from authentication profile's cookie jar.
52     // Restore session from generated OAuth2 refresh token.
53     RESTORE_FROM_COOKIE_JAR,
54     // Restore session from saved OAuth2 refresh token from TokenServices.
55     RESTORE_FROM_SAVED_OAUTH2_REFRESH_TOKEN,
56     // Restore session from OAuth2 refresh token passed via command line.
57     RESTORE_FROM_PASSED_OAUTH2_REFRESH_TOKEN,
58     // Restore session from authentication code passed via command line.
59     RESTORE_FROM_AUTH_CODE,
60   };
61
62   class Observer {
63    public:
64     virtual ~Observer() {}
65
66     // Raised when merge session state changes.
67     virtual void OnSessionRestoreStateChanged(Profile* user_profile,
68                                               SessionRestoreState state) {}
69
70     // Raised when a new OAuth2 refresh token is avaialble.
71     virtual void OnNewRefreshTokenAvaiable(Profile* user_profile) {}
72
73     // Raised when session's GAIA credentials (SID+LSID) are available to
74     // other signed in services.
75     virtual void OnSessionAuthenticated(Profile* user_profile) {}
76   };
77
78   explicit OAuth2LoginManager(Profile* user_profile);
79   virtual ~OAuth2LoginManager();
80
81   void AddObserver(OAuth2LoginManager::Observer* observer);
82   void RemoveObserver(OAuth2LoginManager::Observer* observer);
83
84   // Restores and verifies OAuth tokens either following specified
85   // |restore_strategy|. For |restore_strategy| with values
86   // RESTORE_FROM_PASSED_OAUTH2_REFRESH_TOKEN or
87   // RESTORE_FROM_AUTH_CODE, respectively
88   // parameters |oauth2_refresh_token| or |auth_code| need to have non-empty
89   // value.
90   void RestoreSession(
91       net::URLRequestContextGetter* auth_request_context,
92       SessionRestoreStrategy restore_strategy,
93       const std::string& oauth2_refresh_token,
94       const std::string& auth_code);
95
96   // Continues session restore after transient network errors.
97   void ContinueSessionRestore();
98
99   // Stops all background authentication requests.
100   void Stop();
101
102   // Returns session restore state.
103   SessionRestoreState state() { return state_; }
104
105   const base::Time& session_restore_start() { return session_restore_start_; }
106
107   // Returns true if the tab loading should block until session restore
108   // finishes.
109   bool ShouldBlockTabLoading();
110
111  private:
112   friend class MergeSessionLoadPageTest;
113
114   // Session restore outcomes (for UMA).
115   enum {
116     SESSION_RESTORE_UNDEFINED = 0,
117     SESSION_RESTORE_SUCCESS = 1,
118     SESSION_RESTORE_TOKEN_FETCH_FAILED = 2,
119     SESSION_RESTORE_NO_REFRESH_TOKEN_FAILED = 3,
120     SESSION_RESTORE_OAUTHLOGIN_FAILED = 4,
121     SESSION_RESTORE_MERGE_SESSION_FAILED = 5,
122     SESSION_RESTORE_COUNT = SESSION_RESTORE_MERGE_SESSION_FAILED,
123   };
124
125   // BrowserContextKeyedService implementation.
126   virtual void Shutdown() OVERRIDE;
127
128   // OAuth2LoginVerifier::Delegate overrides.
129   virtual void OnOAuthLoginSuccess(
130       const GaiaAuthConsumer::ClientLoginResult& gaia_credentials) OVERRIDE;
131   virtual void OnOAuthLoginFailure(bool connection_error) OVERRIDE;
132   virtual void OnSessionMergeSuccess() OVERRIDE;
133   virtual void OnSessionMergeFailure(bool connection_error) OVERRIDE;
134
135   // OAuth2TokenFetcher::Delegate overrides.
136   virtual void OnOAuth2TokensAvailable(
137       const GaiaAuthConsumer::ClientOAuthResult& oauth2_tokens) OVERRIDE;
138   virtual void OnOAuth2TokensFetchFailed() OVERRIDE;
139
140   // OAuth2TokenService::Observer implementation:
141   virtual void OnRefreshTokenAvailable(const std::string& account_id) OVERRIDE;
142
143   // Signals delegate that authentication is completed, kicks off token fetching
144   // process in TokenService.
145   void CompleteAuthentication();
146
147   // Retrieves TokenService for |user_profile_| and sets up notification
148   // observer events.
149   TokenService* SetupTokenService();
150
151   // Records OAuth2 tokens fetched through cookies-to-token exchange into
152   // TokenService.
153   void StoreOAuth2Tokens(
154       const GaiaAuthConsumer::ClientOAuthResult& oauth2_tokens);
155
156   // Loads previously stored OAuth2 tokens and kicks off its validation.
157   void LoadAndVerifyOAuth2Tokens();
158
159   // Attempts to fetch OAuth2 tokens by using pre-authenticated cookie jar from
160   // provided |auth_profile|.
161   void FetchOAuth2Tokens();
162
163   // Reports when all tokens are loaded.
164   void ReportOAuth2TokensLoaded();
165
166   // Issue GAIA cookie recovery (MergeSession) from |refresh_token_|.
167   void RestoreSessionCookies();
168
169   // Checks GAIA error and figures out whether the request should be
170   // re-attempted.
171   bool RetryOnError(const GoogleServiceAuthError& error);
172
173   // On successfuly OAuthLogin, starts token service token fetching process.
174   void StartTokenService(
175       const GaiaAuthConsumer::ClientLoginResult& gaia_credentials);
176
177   // Changes |state_|, if needed fires observers (OnSessionRestoreStateChanged).
178   void SetSessionRestoreState(SessionRestoreState state);
179
180   // Testing helper.
181   void SetSessionRestoreStartForTesting(const base::Time& time);
182
183   // Keeps the track if we have already reported OAuth2 token being loaded
184   // by TokenService.
185   Profile* user_profile_;
186   scoped_refptr<net::URLRequestContextGetter> auth_request_context_;
187   SessionRestoreStrategy restore_strategy_;
188   SessionRestoreState state_;
189
190   bool loading_reported_;
191
192   scoped_ptr<OAuth2TokenFetcher> oauth2_token_fetcher_;
193   scoped_ptr<OAuth2LoginVerifier> login_verifier_;
194
195   // OAuth2 refresh token.
196   std::string refresh_token_;
197
198   // Authorization code for fetching OAuth2 tokens.
199   std::string auth_code_;
200
201   // Session restore start time.
202   base::Time session_restore_start_;
203
204   // List of observers to notify when token availability changes.
205   // Makes sure list is empty on destruction.
206   // TODO(zelidrag|gspencer): Figure out how to get rid of ProfileHelper so we
207   // can change the line below to ObserverList<Observer, true>.
208   ObserverList<Observer, false> observer_list_;
209
210   DISALLOW_COPY_AND_ASSIGN(OAuth2LoginManager);
211 };
212
213 }  // namespace chromeos
214
215 #endif  // CHROME_BROWSER_CHROMEOS_LOGIN_OAUTH2_LOGIN_MANAGER_H_