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 #include "chrome/browser/chromeos/login/screen_locker.h"
10 #include "ash/ash_switches.h"
11 #include "ash/audio/sounds.h"
12 #include "ash/desktop_background/desktop_background_controller.h"
13 #include "ash/shell.h"
14 #include "ash/wm/lock_state_controller.h"
15 #include "ash/wm/window_state.h"
16 #include "ash/wm/window_util.h"
17 #include "base/bind.h"
18 #include "base/command_line.h"
19 #include "base/lazy_instance.h"
20 #include "base/memory/weak_ptr.h"
21 #include "base/message_loop/message_loop.h"
22 #include "base/metrics/histogram.h"
23 #include "base/strings/string_number_conversions.h"
24 #include "base/strings/string_util.h"
25 #include "base/timer/timer.h"
26 #include "chrome/browser/chrome_notification_types.h"
27 #include "chrome/browser/chromeos/login/authenticator.h"
28 #include "chrome/browser/chromeos/login/login_performer.h"
29 #include "chrome/browser/chromeos/login/login_utils.h"
30 #include "chrome/browser/chromeos/login/user_adding_screen.h"
31 #include "chrome/browser/chromeos/login/user_manager.h"
32 #include "chrome/browser/chromeos/login/webui_screen_locker.h"
33 #include "chrome/browser/lifetime/application_lifetime.h"
34 #include "chrome/browser/profiles/profile.h"
35 #include "chrome/browser/profiles/profile_manager.h"
36 #include "chrome/browser/signin/signin_manager.h"
37 #include "chrome/browser/signin/signin_manager_factory.h"
38 #include "chrome/browser/sync/profile_sync_service.h"
39 #include "chrome/browser/sync/profile_sync_service_factory.h"
40 #include "chrome/browser/ui/webui/chromeos/login/screenlock_icon_provider.h"
41 #include "chrome/browser/ui/webui/chromeos/login/screenlock_icon_source.h"
42 #include "chrome/common/chrome_switches.h"
43 #include "chromeos/audio/chromeos_sounds.h"
44 #include "chromeos/dbus/dbus_thread_manager.h"
45 #include "chromeos/dbus/session_manager_client.h"
46 #include "content/public/browser/browser_thread.h"
47 #include "content/public/browser/notification_service.h"
48 #include "content/public/browser/url_data_source.h"
49 #include "content/public/browser/user_metrics.h"
50 #include "grit/browser_resources.h"
51 #include "grit/generated_resources.h"
52 #include "media/audio/sounds/sounds_manager.h"
53 #include "ui/base/l10n/l10n_util.h"
54 #include "ui/base/resource/resource_bundle.h"
55 #include "ui/gfx/image/image.h"
58 using base::UserMetricsAction;
59 using content::BrowserThread;
63 // Timeout for unlock animation guard - some animations may be required to run
64 // on successful authentication before unlocking, but we want to be sure that
65 // unlock happens even if animations are broken.
66 const int kUnlockGuardTimeoutMs = 400;
68 // Observer to start ScreenLocker when the screen lock
69 class ScreenLockObserver : public chromeos::SessionManagerClient::Observer,
70 public content::NotificationObserver,
71 public chromeos::UserAddingScreen::Observer {
73 ScreenLockObserver() : session_started_(false) {
75 chrome::NOTIFICATION_LOGIN_USER_CHANGED,
76 content::NotificationService::AllSources());
78 chrome::NOTIFICATION_SESSION_STARTED,
79 content::NotificationService::AllSources());
82 // NotificationObserver overrides:
83 virtual void Observe(int type,
84 const content::NotificationSource& source,
85 const content::NotificationDetails& details) OVERRIDE {
87 case chrome::NOTIFICATION_LOGIN_USER_CHANGED: {
88 // Register Screen Lock only after a user has logged in.
89 chromeos::SessionManagerClient* session_manager =
90 chromeos::DBusThreadManager::Get()->GetSessionManagerClient();
91 if (!session_manager->HasObserver(this))
92 session_manager->AddObserver(this);
96 case chrome::NOTIFICATION_SESSION_STARTED: {
97 session_started_ = true;
106 virtual void LockScreen() OVERRIDE {
107 VLOG(1) << "Received LockScreen D-Bus signal from session manager";
108 if (chromeos::UserAddingScreen::Get()->IsRunning()) {
109 VLOG(1) << "Waiting for user adding screen to stop";
110 chromeos::UserAddingScreen::Get()->AddObserver(this);
111 chromeos::UserAddingScreen::Get()->Cancel();
114 if (session_started_ &&
115 chromeos::UserManager::Get()->CanCurrentUserLock()) {
116 chromeos::ScreenLocker::Show();
118 // If the current user's session cannot be locked or the user has not
119 // completed all sign-in steps yet, log out instead. The latter is done to
120 // avoid complications with displaying the lock screen over the login
121 // screen while remaining secure in the case the user walks away during
122 // the sign-in steps. See crbug.com/112225 and crbug.com/110933.
123 VLOG(1) << "Calling session manager's StopSession D-Bus method";
124 chromeos::DBusThreadManager::Get()->
125 GetSessionManagerClient()->StopSession();
129 virtual void OnUserAddingFinished() OVERRIDE {
130 chromeos::UserAddingScreen::Get()->RemoveObserver(this);
135 bool session_started_;
136 content::NotificationRegistrar registrar_;
137 std::string saved_previous_input_method_id_;
138 std::string saved_current_input_method_id_;
139 std::vector<std::string> saved_active_input_method_list_;
141 DISALLOW_COPY_AND_ASSIGN(ScreenLockObserver);
144 static base::LazyInstance<ScreenLockObserver> g_screen_lock_observer =
145 LAZY_INSTANCE_INITIALIZER;
152 ScreenLocker* ScreenLocker::screen_locker_ = NULL;
154 //////////////////////////////////////////////////////////////////////////////
155 // ScreenLocker, public:
157 ScreenLocker::ScreenLocker(const UserList& users)
160 start_time_(base::Time::Now()),
161 login_status_consumer_(NULL),
162 incorrect_passwords_count_(0),
163 weak_factory_(this) {
164 DCHECK(!screen_locker_);
165 screen_locker_ = this;
167 ui::ResourceBundle& bundle = ui::ResourceBundle::GetSharedInstance();
168 media::SoundsManager* manager = media::SoundsManager::Get();
169 manager->Initialize(SOUND_LOCK,
170 bundle.GetRawDataResource(IDR_SOUND_LOCK_WAV));
171 manager->Initialize(SOUND_UNLOCK,
172 bundle.GetRawDataResource(IDR_SOUND_UNLOCK_WAV));
174 ash::Shell::GetInstance()->
175 lock_state_controller()->SetLockScreenDisplayedCallback(
176 base::Bind(base::IgnoreResult(&ash::PlaySystemSound),
177 static_cast<media::SoundsManager::SoundKey>(
178 chromeos::SOUND_LOCK),
179 true /* honor_spoken_feedback */));
182 void ScreenLocker::Init() {
183 authenticator_ = LoginUtils::Get()->CreateAuthenticator(this);
184 delegate_.reset(new WebUIScreenLocker(this));
185 delegate_->LockScreen();
187 // Ownership of |icon_image_source| is passed.
188 screenlock_icon_provider_.reset(new ScreenlockIconProvider);
189 ScreenlockIconSource* screenlock_icon_source =
190 new ScreenlockIconSource(screenlock_icon_provider_->AsWeakPtr());
191 content::URLDataSource::Add(
192 Profile::FromWebUI(GetAssociatedWebUI()),
193 screenlock_icon_source);
196 void ScreenLocker::OnLoginFailure(const LoginFailure& error) {
197 content::RecordAction(UserMetricsAction("ScreenLocker_OnLoginFailure"));
198 if (authentication_start_time_.is_null()) {
199 LOG(ERROR) << "Start time is not set at authentication failure";
201 base::TimeDelta delta = base::Time::Now() - authentication_start_time_;
202 VLOG(1) << "Authentication failure: " << delta.InSecondsF() << " second(s)";
203 UMA_HISTOGRAM_TIMES("ScreenLocker.AuthenticationFailureTime", delta);
207 // Don't enable signout button here as we're showing
210 delegate_->ShowErrorMessage(incorrect_passwords_count_++ ?
211 IDS_LOGIN_ERROR_AUTHENTICATING_2ND_TIME :
212 IDS_LOGIN_ERROR_AUTHENTICATING,
213 HelpAppLauncher::HELP_CANT_ACCESS_ACCOUNT);
215 if (login_status_consumer_)
216 login_status_consumer_->OnLoginFailure(error);
219 void ScreenLocker::OnLoginSuccess(const UserContext& user_context) {
220 incorrect_passwords_count_ = 0;
221 if (authentication_start_time_.is_null()) {
222 if (!user_context.username.empty())
223 LOG(ERROR) << "Start time is not set at authentication success";
225 base::TimeDelta delta = base::Time::Now() - authentication_start_time_;
226 VLOG(1) << "Authentication success: " << delta.InSecondsF() << " second(s)";
227 UMA_HISTOGRAM_TIMES("ScreenLocker.AuthenticationSuccessTime", delta);
230 if (const User* user = UserManager::Get()->FindUser(user_context.username)) {
231 if (!user->is_active())
232 UserManager::Get()->SwitchActiveUser(user_context.username);
234 NOTREACHED() << "Logged in user not found.";
237 authentication_capture_.reset(new AuthenticationParametersCapture());
238 authentication_capture_->user_context = user_context;
240 // Add guard for case when something get broken in call chain to unlock
242 base::MessageLoop::current()->PostDelayedTask(
244 base::Bind(&ScreenLocker::UnlockOnLoginSuccess,
245 weak_factory_.GetWeakPtr()),
246 base::TimeDelta::FromMilliseconds(kUnlockGuardTimeoutMs));
247 delegate_->AnimateAuthenticationSuccess();
250 void ScreenLocker::UnlockOnLoginSuccess() {
251 DCHECK(base::MessageLoopForUI::IsCurrent());
252 if (!authentication_capture_.get()) {
253 LOG(WARNING) << "Call to UnlockOnLoginSuccess without previous " <<
254 "authentication success.";
258 if (login_status_consumer_) {
259 login_status_consumer_->OnLoginSuccess(
260 UserContext(authentication_capture_->user_context.username,
261 authentication_capture_->user_context.password,
262 authentication_capture_->user_context.auth_code,
263 authentication_capture_->user_context.username_hash,
264 authentication_capture_->user_context.using_oauth,
265 authentication_capture_->user_context.auth_flow));
267 authentication_capture_.reset();
268 weak_factory_.InvalidateWeakPtrs();
270 VLOG(1) << "Hiding the lock screen.";
271 chromeos::ScreenLocker::Hide();
274 void ScreenLocker::Authenticate(const UserContext& user_context) {
275 LOG_ASSERT(IsUserLoggedIn(user_context.username))
276 << "Invalid user trying to unlock.";
277 authentication_start_time_ = base::Time::Now();
278 delegate_->SetInputEnabled(false);
279 delegate_->OnAuthenticate();
281 BrowserThread::PostTask(
282 BrowserThread::UI, FROM_HERE,
283 base::Bind(&Authenticator::AuthenticateToUnlock,
284 authenticator_.get(),
288 void ScreenLocker::AuthenticateByPassword(const std::string& password) {
289 LOG_ASSERT(users_.size() == 1);
290 Authenticate(UserContext(users_[0]->email(), password, ""));
293 void ScreenLocker::ClearErrors() {
294 delegate_->ClearErrors();
297 void ScreenLocker::EnableInput() {
298 delegate_->SetInputEnabled(true);
301 void ScreenLocker::Signout() {
302 delegate_->ClearErrors();
303 content::RecordAction(UserMetricsAction("ScreenLocker_Signout"));
304 // We expect that this call will not wait for any user input.
305 // If it changes at some point, we will need to force exit.
306 chrome::AttemptUserExit();
308 // Don't hide yet the locker because the chrome screen may become visible
312 void ScreenLocker::ShowBannerMessage(const std::string& message) {
313 delegate_->ShowBannerMessage(message);
316 void ScreenLocker::ShowUserPodButton(const std::string& username,
317 const gfx::Image& icon,
318 const base::Closure& click_callback) {
322 screenlock_icon_provider_->AddIcon(username, icon);
324 // Append the current time to the URL so the image will not be cached.
325 std::string icon_url = ScreenlockIconSource::GetIconURLForUser(username)
326 + "?" + base::Int64ToString(base::Time::Now().ToInternalValue());
327 delegate_->ShowUserPodButton(username, icon_url, click_callback);
330 void ScreenLocker::ShowErrorMessage(int error_msg_id,
331 HelpAppLauncher::HelpTopic help_topic_id,
332 bool sign_out_only) {
333 delegate_->SetInputEnabled(!sign_out_only);
334 delegate_->ShowErrorMessage(error_msg_id, help_topic_id);
337 void ScreenLocker::SetLoginStatusConsumer(
338 chromeos::LoginStatusConsumer* consumer) {
339 login_status_consumer_ = consumer;
343 void ScreenLocker::Show() {
344 content::RecordAction(UserMetricsAction("ScreenLocker_Show"));
345 DCHECK(base::MessageLoopForUI::IsCurrent());
347 // Check whether the currently logged in user is a guest account and if so,
348 // refuse to lock the screen (crosbug.com/23764).
349 // For a demo user, we should never show the lock screen (crosbug.com/27647).
350 if (UserManager::Get()->IsLoggedInAsGuest() ||
351 UserManager::Get()->IsLoggedInAsDemoUser()) {
352 VLOG(1) << "Refusing to lock screen for guest/demo account";
356 // If the active window is fullscreen, exit fullscreen to avoid the web page
357 // or app mimicking the lock screen. Do not exit fullscreen if the shelf is
358 // visible while in fullscreen because the shelf makes it harder for a web
359 // page or app to mimick the lock screen.
360 ash::wm::WindowState* active_window_state = ash::wm::GetActiveWindowState();
361 if (active_window_state &&
362 active_window_state->IsFullscreen() &&
363 active_window_state->hide_shelf_when_fullscreen()) {
364 active_window_state->ToggleFullscreen();
367 if (!screen_locker_) {
368 ScreenLocker* locker =
369 new ScreenLocker(UserManager::Get()->GetUnlockUsers());
370 VLOG(1) << "Created ScreenLocker " << locker;
373 VLOG(1) << "ScreenLocker " << screen_locker_ << " already exists; "
374 << " calling session manager's HandleLockScreenShown D-Bus method";
375 DBusThreadManager::Get()->GetSessionManagerClient()->
376 NotifyLockScreenShown();
381 void ScreenLocker::Hide() {
382 DCHECK(base::MessageLoopForUI::IsCurrent());
383 // For a guest/demo user, screen_locker_ would have never been initialized.
384 if (UserManager::Get()->IsLoggedInAsGuest() ||
385 UserManager::Get()->IsLoggedInAsDemoUser()) {
386 VLOG(1) << "Refusing to hide lock screen for guest/demo account";
390 DCHECK(screen_locker_);
391 base::Callback<void(void)> callback =
392 base::Bind(&ScreenLocker::ScheduleDeletion);
393 ash::Shell::GetInstance()->lock_state_controller()->
394 OnLockScreenHide(callback);
397 void ScreenLocker::ScheduleDeletion() {
398 // Avoid possible multiple calls.
399 if (screen_locker_ == NULL)
401 VLOG(1) << "Deleting ScreenLocker " << screen_locker_;
403 ash::PlaySystemSound(SOUND_UNLOCK, true /* honor_spoken_feedback */);
405 delete screen_locker_;
406 screen_locker_ = NULL;
410 void ScreenLocker::InitClass() {
411 g_screen_lock_observer.Get();
414 ////////////////////////////////////////////////////////////////////////////////
415 // ScreenLocker, private:
417 ScreenLocker::~ScreenLocker() {
418 VLOG(1) << "Destroying ScreenLocker " << this;
419 DCHECK(base::MessageLoopForUI::IsCurrent());
421 if (authenticator_.get())
422 authenticator_->SetConsumer(NULL);
425 VLOG(1) << "Moving desktop background to unlocked container";
426 ash::Shell::GetInstance()->
427 desktop_background_controller()->MoveDesktopToUnlockedContainer();
429 screen_locker_ = NULL;
431 VLOG(1) << "Emitting SCREEN_LOCK_STATE_CHANGED with state=" << state;
432 content::NotificationService::current()->Notify(
433 chrome::NOTIFICATION_SCREEN_LOCK_STATE_CHANGED,
434 content::Source<ScreenLocker>(this),
435 content::Details<bool>(&state));
436 VLOG(1) << "Calling session manager's HandleLockScreenDismissed D-Bus method";
437 DBusThreadManager::Get()->GetSessionManagerClient()->
438 NotifyLockScreenDismissed();
441 void ScreenLocker::SetAuthenticator(Authenticator* authenticator) {
442 authenticator_ = authenticator;
445 void ScreenLocker::ScreenLockReady() {
447 base::TimeDelta delta = base::Time::Now() - start_time_;
448 VLOG(1) << "ScreenLocker " << this << " is ready after "
449 << delta.InSecondsF() << " second(s)";
450 UMA_HISTOGRAM_TIMES("ScreenLocker.ScreenLockTime", delta);
452 VLOG(1) << "Moving desktop background to locked container";
453 ash::Shell::GetInstance()->
454 desktop_background_controller()->MoveDesktopToLockedContainer();
457 VLOG(1) << "Emitting SCREEN_LOCK_STATE_CHANGED with state=" << state;
458 content::NotificationService::current()->Notify(
459 chrome::NOTIFICATION_SCREEN_LOCK_STATE_CHANGED,
460 content::Source<ScreenLocker>(this),
461 content::Details<bool>(&state));
462 VLOG(1) << "Calling session manager's HandleLockScreenShown D-Bus method";
463 DBusThreadManager::Get()->GetSessionManagerClient()->NotifyLockScreenShown();
466 content::WebUI* ScreenLocker::GetAssociatedWebUI() {
467 return delegate_->GetAssociatedWebUI();
470 bool ScreenLocker::IsUserLoggedIn(const std::string& username) {
471 for (UserList::const_iterator it = users_.begin(); it != users_.end(); ++it) {
472 if ((*it)->email() == username)
478 } // namespace chromeos