Merge Chromium + Blink git repositories
[chromium-blink-merge.git] / components / signin / core / browser / signin_manager.h
blobd5158084380f4dcc6dbbd3fd538fb4543906854c
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.
4 //
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.
9 //
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
12 // TokenService.
13 // TODO(tim): Bug 92948, 226464. ClientLogin is all but gone from use.
15 #ifndef COMPONENTS_SIGNIN_CORE_BROWSER_SIGNIN_MANAGER_H_
16 #define COMPONENTS_SIGNIN_CORE_BROWSER_SIGNIN_MANAGER_H_
18 #if defined(OS_CHROMEOS)
19 // On Chrome OS, SigninManagerBase is all that exists.
20 #include "components/signin/core/browser/signin_manager_base.h"
22 #else
24 #include <set>
25 #include <string>
27 #include "base/compiler_specific.h"
28 #include "base/gtest_prod_util.h"
29 #include "base/logging.h"
30 #include "base/memory/scoped_ptr.h"
31 #include "base/observer_list.h"
32 #include "base/prefs/pref_change_registrar.h"
33 #include "base/prefs/pref_member.h"
34 #include "components/keyed_service/core/keyed_service.h"
35 #include "components/signin/core/browser/account_info.h"
36 #include "components/signin/core/browser/account_tracker_service.h"
37 #include "components/signin/core/browser/profile_oauth2_token_service.h"
38 #include "components/signin/core/browser/signin_internals_util.h"
39 #include "components/signin/core/browser/signin_manager_base.h"
40 #include "components/signin/core/browser/signin_metrics.h"
41 #include "net/cookies/canonical_cookie.h"
43 class GaiaCookieManagerService;
44 class GoogleServiceAuthError;
45 class PrefService;
46 class ProfileOAuth2TokenService;
47 class SigninClient;
49 class SigninManager : public SigninManagerBase,
50 public AccountTrackerService::Observer,
51 public OAuth2TokenService::Observer {
52 public:
53 // The callback invoked once the OAuth token has been fetched during signin,
54 // but before the profile transitions to the "signed-in" state. This allows
55 // callers to load policy and prompt the user appropriately before completing
56 // signin. The callback is passed the just-fetched OAuth login refresh token.
57 typedef base::Callback<void(const std::string&)> OAuthTokenFetchedCallback;
59 // This is used to distinguish URLs belonging to the special web signin flow
60 // running in the special signin process from other URLs on the same domain.
61 // We do not grant WebUI privilieges / bindings to this process or to URLs of
62 // this scheme; enforcement of privileges is handled separately by
63 // OneClickSigninHelper.
64 static const char kChromeSigninEffectiveSite[];
66 SigninManager(SigninClient* client,
67 ProfileOAuth2TokenService* token_service,
68 AccountTrackerService* account_tracker_service,
69 GaiaCookieManagerService* cookie_manager_service);
70 ~SigninManager() override;
72 // Returns true if the username is allowed based on the policy string.
73 static bool IsUsernameAllowedByPolicy(const std::string& username,
74 const std::string& policy);
76 // Attempt to sign in this user with a refresh token.
77 // If non-null, the passed |oauth_fetched_callback| callback is invoked once
78 // signin has been completed.
79 // The callback should invoke SignOut() or CompletePendingSignin() to either
80 // continue or cancel the in-process signin.
81 virtual void StartSignInWithRefreshToken(
82 const std::string& refresh_token,
83 const std::string& gaia_id,
84 const std::string& username,
85 const std::string& password,
86 const OAuthTokenFetchedCallback& oauth_fetched_callback);
88 // Copies auth credentials from one SigninManager to this one. This is used
89 // when creating a new profile during the signin process to transfer the
90 // in-progress credentials to the new profile.
91 virtual void CopyCredentialsFrom(const SigninManager& source);
93 // Sign a user out, removing the preference, erasing all keys
94 // associated with the user, and canceling all auth in progress.
95 virtual void SignOut(signin_metrics::ProfileSignout signout_source_metric);
97 // On platforms where SigninManager is responsible for dealing with
98 // invalid username policy updates, we need to check this during
99 // initialization and sign the user out.
100 void Initialize(PrefService* local_state) override;
101 void Shutdown() override;
103 // If applicable, merge the signed in account into the cookie jar.
104 void MergeSigninCredentialIntoCookieJar();
106 // Invoked from an OAuthTokenFetchedCallback to complete user signin.
107 virtual void CompletePendingSignin();
109 // Invoked from SigninManagerAndroid to indicate that the sign-in process
110 // has completed for the email |username|. SigninManager assumes that
111 // |username| can be used to look up the corresponding account_id and gaia_id
112 // for this email.
113 void OnExternalSigninCompleted(const std::string& username);
115 // Returns true if there's a signin in progress.
116 bool AuthInProgress() const override;
118 bool IsSigninAllowed() const override;
120 // Returns true if the passed username is allowed by policy. Virtual for
121 // mocking in tests.
122 virtual bool IsAllowedUsername(const std::string& username) const;
124 // If an authentication is in progress, return the account id being
125 // authenticated. Returns an empty string if no auth is in progress.
126 const std::string& GetAccountIdForAuthInProgress() const;
128 // If an authentication is in progress, return the username being
129 // authenticated. Returns an empty string if no auth is in progress.
130 const std::string& GetUsernameForAuthInProgress() const;
132 // Set the preference to turn off one-click sign-in so that it won't ever
133 // show it again for the user associated with |prefs| (even if the user tries
134 // a new account).
135 static void DisableOneClickSignIn(PrefService* prefs);
137 // Tells the SigninManager whether to prohibit signout for this profile.
138 // If |prohibit_signout| is true, then signout will be prohibited.
139 void ProhibitSignout(bool prohibit_signout);
141 // If true, signout is prohibited for this profile (calls to SignOut() are
142 // ignored).
143 bool IsSignoutProhibited() const;
145 protected:
146 // Flag saying whether signing out is allowed.
147 bool prohibit_signout_;
149 private:
150 enum SigninType { SIGNIN_TYPE_NONE, SIGNIN_TYPE_WITH_REFRESH_TOKEN };
152 std::string SigninTypeToString(SigninType type);
153 friend class FakeSigninManager;
154 FRIEND_TEST_ALL_PREFIXES(SigninManagerTest, ClearTransientSigninData);
155 FRIEND_TEST_ALL_PREFIXES(SigninManagerTest, ProvideSecondFactorSuccess);
156 FRIEND_TEST_ALL_PREFIXES(SigninManagerTest, ProvideSecondFactorFailure);
158 // If user was signed in, load tokens from DB if available.
159 void InitTokenService();
161 // Called to setup the transient signin data during one of the
162 // StartSigninXXX methods. |type| indicates which of the methods is being
163 // used to perform the signin while |username| and |password| identify the
164 // account to be signed in. Returns false and generates an auth error if the
165 // passed |username| is not allowed by policy. |gaia_id| is the obfuscated
166 // gaia id corresponding to |username|.
167 bool PrepareForSignin(SigninType type,
168 const std::string& gaia_id,
169 const std::string& username,
170 const std::string& password);
172 // Persists |account_id| as the currently signed-in account, and triggers
173 // a sign-in success notification.
174 void OnSignedIn();
176 // Waits for the AccountTrackerService, then sends GoogleSigninSucceeded to
177 // the client and clears the local password.
178 void PostSignedIn();
180 // AccountTrackerService::Observer implementation.
181 void OnAccountUpdated(const AccountInfo& info) override;
182 void OnAccountUpdateFailed(const std::string& account_id) override;
184 // OAuth2TokenService::Observer
185 void OnRefreshTokensLoaded() override;
187 // Called when a new request to re-authenticate a user is in progress.
188 // Will clear in memory data but leaves the db as such so when the browser
189 // restarts we can use the old token(which might throw a password error).
190 void ClearTransientSigninData();
192 // Called to handle an error from a GAIA auth fetch. Sets the last error
193 // to |error|, sends out a notification of login failure and clears the
194 // transient signin data.
195 void HandleAuthError(const GoogleServiceAuthError& error);
197 void OnSigninAllowedPrefChanged();
198 void OnGoogleServicesUsernamePatternChanged();
200 std::string possibly_invalid_account_id_;
201 std::string possibly_invalid_gaia_id_;
202 std::string possibly_invalid_email_;
203 std::string password_; // This is kept empty whenever possible.
205 // The type of sign being performed. This value is valid only between a call
206 // to one of the StartSigninXXX methods and when the sign in is either
207 // successful or not.
208 SigninType type_;
210 // Temporarily saves the oauth2 refresh token. It will be passed to the
211 // token service so that it does not need to mint new ones.
212 std::string temp_refresh_token_;
214 // The SigninClient object associated with this object. Must outlive this
215 // object.
216 SigninClient* client_;
218 // The ProfileOAuth2TokenService instance associated with this object. Must
219 // outlive this object.
220 ProfileOAuth2TokenService* token_service_;
222 // Object used to use the token to push a GAIA cookie into the cookie jar.
223 GaiaCookieManagerService* cookie_manager_service_;
225 // Helper object to listen for changes to signin preferences stored in non-
226 // profile-specific local prefs (like kGoogleServicesUsernamePattern).
227 PrefChangeRegistrar local_state_pref_registrar_;
229 // Helper object to listen for changes to the signin allowed preference.
230 BooleanPrefMember signin_allowed_;
232 // Two gate conditions for when PostSignedIn should be called. Verify
233 // that the SigninManager has reached OnSignedIn() and the AccountTracker
234 // has completed calling GetUserInfo.
235 bool signin_manager_signed_in_;
236 bool user_info_fetched_by_account_tracker_;
238 base::WeakPtrFactory<SigninManager> weak_pointer_factory_;
240 DISALLOW_COPY_AND_ASSIGN(SigninManager);
243 #endif // !defined(OS_CHROMEOS)
245 #endif // COMPONENTS_SIGNIN_CORE_BROWSER_SIGNIN_MANAGER_H_