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
3 // found in the LICENSE file.
5 // The signin manager encapsulates some functionality tracking
6 // which user is signed in. See SigninManagerBase for full description of
7 // responsibilities. The class defined in this file provides functionality
8 // required by all platforms except Chrome OS.
10 // When a user is signed in, a ClientLogin request is run on their behalf.
11 // Auth tokens are fetched from Google and the results are stored in the
13 // TODO(tim): Bug 92948, 226464. ClientLogin is all but gone from use.
15 #ifndef CHROME_BROWSER_SIGNIN_SIGNIN_MANAGER_H_
16 #define CHROME_BROWSER_SIGNIN_SIGNIN_MANAGER_H_
18 #if defined(OS_CHROMEOS)
19 // On Chrome OS, SigninManagerBase is all that exists.
20 #include "chrome/browser/signin/signin_manager_base.h"
26 #include "base/compiler_specific.h"
27 #include "base/gtest_prod_util.h"
28 #include "base/logging.h"
29 #include "base/memory/scoped_ptr.h"
30 #include "base/observer_list.h"
31 #include "base/prefs/pref_change_registrar.h"
32 #include "base/prefs/pref_member.h"
33 #include "chrome/browser/profiles/profile.h"
34 #include "chrome/browser/signin/signin_internals_util.h"
35 #include "chrome/browser/signin/signin_manager_base.h"
36 #include "components/browser_context_keyed_service/browser_context_keyed_service.h"
37 #include "content/public/browser/notification_observer.h"
38 #include "content/public/browser/notification_registrar.h"
39 #include "google_apis/gaia/gaia_auth_consumer.h"
40 #include "google_apis/gaia/google_service_auth_error.h"
41 #include "net/cookies/canonical_cookie.h"
44 class GaiaAuthFetcher;
47 class SigninGlobalError;
48 class SigninManagerDelegate;
50 class SigninManager : public SigninManagerBase,
51 public GaiaAuthConsumer,
52 public content::NotificationObserver {
54 // The callback invoked once the OAuth token has been fetched during signin,
55 // but before the profile transitions to the "signed-in" state. This allows
56 // callers to load policy and prompt the user appropriately before completing
57 // signin. The callback is passed the just-fetched OAuth login refresh token.
58 typedef base::Callback<void(const std::string&)> OAuthTokenFetchedCallback;
60 // Returns true if |url| is a web signin URL and should be hosted in an
61 // isolated, privileged signin process.
62 static bool IsWebBasedSigninFlowURL(const GURL& url);
64 // This is used to distinguish URLs belonging to the special web signin flow
65 // running in the special signin process from other URLs on the same domain.
66 // We do not grant WebUI privilieges / bindings to this process or to URLs of
67 // this scheme; enforcement of privileges is handled separately by
68 // OneClickSigninHelper.
69 static const char* kChromeSigninEffectiveSite;
71 explicit SigninManager(scoped_ptr<SigninManagerDelegate> delegate);
72 virtual ~SigninManager();
74 // Returns true if the username is allowed based on the policy string.
75 static bool IsUsernameAllowedByPolicy(const std::string& username,
76 const std::string& policy);
78 // Attempt to sign in this user with existing credentials from the cookie jar.
79 // |session_index| indicates which user account to use if the cookie jar
80 // contains a multi-login session. Otherwise the end result of this call is
81 // the same as StartSignIn().
82 // If non-null, the passed |signin_complete| callback is invoked once signin
83 // has been completed and the oauth login token has been generated - the
84 // callback will not be invoked if no token is generated (either because of
85 // a failed signin or because web-based signin is not enabled).
86 // The callback should invoke SignOut() or CompletePendingSignin() to either
87 // continue or cancel the in-process signin.
88 virtual void StartSignInWithCredentials(
89 const std::string& session_index,
90 const std::string& username,
91 const std::string& password,
92 const OAuthTokenFetchedCallback& oauth_fetched_callback);
94 // Attempt to sign in this user with the given oauth code. The cookie jar
95 // may not be set up properly for the same user, thus will call the
96 // mergeSession endpoint to populate the cookie jar.
97 virtual void StartSignInWithOAuthCode(
98 const std::string& username,
99 const std::string& password,
100 const std::string& oauth_code,
101 const OAuthTokenFetchedCallback& callback);
103 // Copies auth credentials from one SigninManager to this one. This is used
104 // when creating a new profile during the signin process to transfer the
105 // in-progress credentials to the new profile.
106 virtual void CopyCredentialsFrom(const SigninManager& source);
108 // Sign a user out, removing the preference, erasing all keys
109 // associated with the user, and canceling all auth in progress.
110 virtual void SignOut();
112 // On platforms where SigninManager is responsible for dealing with
113 // invalid username policy updates, we need to check this during
114 // initialization and sign the user out.
115 virtual void Initialize(Profile* profile, PrefService* local_state) OVERRIDE;
116 virtual void Shutdown() OVERRIDE;
118 // Invoked from an OAuthTokenFetchedCallback to complete user signin.
119 virtual void CompletePendingSignin();
121 // Invoked from SigninManagerAndroid to indicate that the sign-in process
122 // has completed for |username|.
123 void OnExternalSigninCompleted(const std::string& username);
125 // Returns true if there's a signin in progress.
126 virtual bool AuthInProgress() const OVERRIDE;
128 virtual bool IsSigninAllowed() const OVERRIDE;
130 // Returns true if the passed username is allowed by policy. Virtual for
132 virtual bool IsAllowedUsername(const std::string& username) const;
134 // If an authentication is in progress, return the username being
135 // authenticated. Returns an empty string if no auth is in progress.
136 const std::string& GetUsernameForAuthInProgress() const;
138 // Handles errors if a required user info key is not returned from the
140 void OnGetUserInfoKeyNotFound(const std::string& key);
142 // Set the profile preference to turn off one-click sign-in so that it won't
143 // ever show it again in this profile (even if the user tries a new account).
144 static void DisableOneClickSignIn(Profile* profile);
147 virtual void OnClientLoginSuccess(const ClientLoginResult& result) OVERRIDE;
148 virtual void OnClientLoginFailure(
149 const GoogleServiceAuthError& error) OVERRIDE;
150 virtual void OnClientOAuthSuccess(const ClientOAuthResult& result) OVERRIDE;
151 virtual void OnClientOAuthFailure(
152 const GoogleServiceAuthError& error) OVERRIDE;
153 virtual void OnOAuth2RevokeTokenCompleted() OVERRIDE;
154 virtual void OnGetUserInfoSuccess(const UserInfoMap& data) OVERRIDE;
155 virtual void OnGetUserInfoFailure(
156 const GoogleServiceAuthError& error) OVERRIDE;
157 virtual void OnUberAuthTokenSuccess(const std::string& token) OVERRIDE;
158 virtual void OnUberAuthTokenFailure(
159 const GoogleServiceAuthError& error) OVERRIDE;
160 virtual void OnMergeSessionSuccess(const std::string& data) OVERRIDE;
161 virtual void OnMergeSessionFailure(
162 const GoogleServiceAuthError& error) OVERRIDE;
164 // content::NotificationObserver
165 virtual void Observe(int type,
166 const content::NotificationSource& source,
167 const content::NotificationDetails& details) OVERRIDE;
170 // Tells the SigninManager whether to prohibit signout for this profile.
171 // If |prohibit_signout| is true, then signout will be prohibited.
172 void ProhibitSignout(bool prohibit_signout);
174 // If true, signout is prohibited for this profile (calls to SignOut() are
176 bool IsSignoutProhibited() const;
178 // Checks if signin is allowed for the profile that owns |io_data|. This must
179 // be invoked on the IO thread, and can be used to check if signin is enabled
181 static bool IsSigninAllowedOnIOThread(ProfileIOData* io_data);
183 // Allows the SigninManager to track the privileged signin process
184 // identified by |process_id| so that we can later ask (via IsSigninProcess)
185 // if it is safe to sign the user in from the current context (see
186 // OneClickSigninHelper). All of this tracking state is reset once the
187 // renderer process terminates.
188 void SetSigninProcess(int process_id);
189 void ClearSigninProcess();
190 bool IsSigninProcess(int process_id) const;
191 bool HasSigninProcess() const;
194 // If user was signed in, load tokens from DB if available.
195 virtual void InitTokenService() OVERRIDE;
197 // Flag saying whether signing out is allowed.
198 bool prohibit_signout_;
203 SIGNIN_TYPE_WITH_CREDENTIALS,
204 SIGNIN_TYPE_WITH_OAUTH_CODE
207 std::string SigninTypeToString(SigninType type);
208 friend class FakeSigninManager;
209 FRIEND_TEST_ALL_PREFIXES(SigninManagerTest, ClearTransientSigninData);
210 FRIEND_TEST_ALL_PREFIXES(SigninManagerTest, ProvideSecondFactorSuccess);
211 FRIEND_TEST_ALL_PREFIXES(SigninManagerTest, ProvideSecondFactorFailure);
213 // Called to setup the transient signin data during one of the
214 // StartSigninXXX methods. |type| indicates which of the methods is being
215 // used to perform the signin while |username| and |password| identify the
216 // account to be signed in. Returns false and generates an auth error if the
217 // passed |username| is not allowed by policy.
218 bool PrepareForSignin(SigninType type,
219 const std::string& username,
220 const std::string& password);
222 // Called to verify GAIA cookies asynchronously before starting auto sign-in
224 void VerifyGaiaCookiesBeforeSignIn(const std::string& session_index);
226 // Called when GAIA cookies are fetched. If LSID cookie is valid, then start
227 // auto sign-in by exchanging cookies for an oauth code.
228 void OnGaiaCookiesFetched(
229 const std::string session_index, const net::CookieList& cookie_list);
231 // Persists |username| as the currently signed-in account, and triggers
232 // a sign-in success notification.
233 void OnSignedIn(const std::string& username);
235 // Called when a new request to re-authenticate a user is in progress.
236 // Will clear in memory data but leaves the db as such so when the browser
237 // restarts we can use the old token(which might throw a password error).
238 void ClearTransientSigninData();
240 // Called to handle an error from a GAIA auth fetch. Sets the last error
241 // to |error|, sends out a notification of login failure, and clears the
242 // transient signin data if |clear_transient_data| is true.
243 void HandleAuthError(const GoogleServiceAuthError& error,
244 bool clear_transient_data);
246 // Called to tell GAIA that we will no longer be using the current refresh
248 void RevokeOAuthLoginToken();
250 void OnSigninAllowedPrefChanged();
251 void OnGoogleServicesUsernamePatternChanged();
253 // ClientLogin identity.
254 std::string possibly_invalid_username_;
255 std::string password_; // This is kept empty whenever possible.
256 bool had_two_factor_error_;
258 // Result of the last client login, kept pending the lookup of the
260 ClientLoginResult last_result_;
262 // Actual client login handler.
263 scoped_ptr<GaiaAuthFetcher> client_login_;
265 // Registrar for notifications from the TokenService.
266 content::NotificationRegistrar registrar_;
268 // OAuth revocation fetcher for sign outs.
269 scoped_ptr<GaiaAuthFetcher> revoke_token_fetcher_;
271 // The type of sign being performed. This value is valid only between a call
272 // to one of the StartSigninXXX methods and when the sign in is either
273 // successful or not.
276 // Temporarily saves the oauth2 refresh and access tokens when signing in
277 // with credentials. These will be passed to TokenService so that it does
278 // not need to mint new ones.
279 ClientOAuthResult temp_oauth_login_tokens_;
281 base::WeakPtrFactory<SigninManager> weak_pointer_factory_;
283 // See SetSigninProcess. Tracks the currently active signin process
284 // by ID, if there is one.
285 int signin_process_id_;
287 // Callback invoked during signin after an OAuth token has been fetched
288 // but before signin is complete.
289 OAuthTokenFetchedCallback oauth_token_fetched_callback_;
291 scoped_ptr<SigninManagerDelegate> delegate_;
293 // Helper object to listen for changes to signin preferences stored in non-
294 // profile-specific local prefs (like kGoogleServicesUsernamePattern).
295 PrefChangeRegistrar local_state_pref_registrar_;
297 // Helper object to listen for changes to the signin allowed preference.
298 BooleanPrefMember signin_allowed_;
300 DISALLOW_COPY_AND_ASSIGN(SigninManager);
303 #endif // !defined(OS_CHROMEOS)
305 #endif // CHROME_BROWSER_SIGNIN_SIGNIN_MANAGER_H_