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;
65 // Timeout for unlock animation guard - some animations may be required to run
66 // on successful authentication before unlocking, but we want to be sure that
67 // unlock happens even if animations are broken.
68 const int kUnlockGuardTimeoutMs = 400;
70 // Observer to start ScreenLocker when the screen lock
71 class ScreenLockObserver : public SessionManagerClient::Observer,
72 public content::NotificationObserver,
73 public UserAddingScreen::Observer {
75 ScreenLockObserver() : session_started_(false) {
77 chrome::NOTIFICATION_LOGIN_USER_CHANGED,
78 content::NotificationService::AllSources());
80 chrome::NOTIFICATION_SESSION_STARTED,
81 content::NotificationService::AllSources());
84 bool session_started() const { return session_started_; }
86 // NotificationObserver overrides:
87 virtual void Observe(int type,
88 const content::NotificationSource& source,
89 const content::NotificationDetails& details) OVERRIDE {
91 case chrome::NOTIFICATION_LOGIN_USER_CHANGED: {
92 // Register Screen Lock only after a user has logged in.
93 SessionManagerClient* session_manager =
94 DBusThreadManager::Get()->GetSessionManagerClient();
95 if (!session_manager->HasObserver(this))
96 session_manager->AddObserver(this);
100 case chrome::NOTIFICATION_SESSION_STARTED: {
101 session_started_ = true;
110 // TODO(derat): Remove this once the session manager is calling the LockScreen
111 // method instead of emitting a signal.
112 virtual void LockScreen() OVERRIDE {
113 VLOG(1) << "Received LockScreen D-Bus signal from session manager";
114 ScreenLocker::HandleLockScreenRequest();
117 virtual void OnUserAddingFinished() OVERRIDE {
118 UserAddingScreen::Get()->RemoveObserver(this);
123 bool session_started_;
124 content::NotificationRegistrar registrar_;
126 DISALLOW_COPY_AND_ASSIGN(ScreenLockObserver);
129 static base::LazyInstance<ScreenLockObserver> g_screen_lock_observer =
130 LAZY_INSTANCE_INITIALIZER;
135 ScreenLocker* ScreenLocker::screen_locker_ = NULL;
137 //////////////////////////////////////////////////////////////////////////////
138 // ScreenLocker, public:
140 ScreenLocker::ScreenLocker(const UserList& users)
143 start_time_(base::Time::Now()),
144 login_status_consumer_(NULL),
145 incorrect_passwords_count_(0),
146 weak_factory_(this) {
147 DCHECK(!screen_locker_);
148 screen_locker_ = this;
150 ui::ResourceBundle& bundle = ui::ResourceBundle::GetSharedInstance();
151 media::SoundsManager* manager = media::SoundsManager::Get();
152 manager->Initialize(SOUND_LOCK,
153 bundle.GetRawDataResource(IDR_SOUND_LOCK_WAV));
154 manager->Initialize(SOUND_UNLOCK,
155 bundle.GetRawDataResource(IDR_SOUND_UNLOCK_WAV));
157 ash::Shell::GetInstance()->
158 lock_state_controller()->SetLockScreenDisplayedCallback(
159 base::Bind(base::IgnoreResult(&ash::PlaySystemSound),
160 static_cast<media::SoundsManager::SoundKey>(
161 chromeos::SOUND_LOCK),
162 true /* honor_spoken_feedback */));
165 void ScreenLocker::Init() {
166 authenticator_ = LoginUtils::Get()->CreateAuthenticator(this);
167 delegate_.reset(new WebUIScreenLocker(this));
168 delegate_->LockScreen();
170 // Ownership of |icon_image_source| is passed.
171 screenlock_icon_provider_.reset(new ScreenlockIconProvider);
172 ScreenlockIconSource* screenlock_icon_source =
173 new ScreenlockIconSource(screenlock_icon_provider_->AsWeakPtr());
174 content::URLDataSource::Add(
175 Profile::FromWebUI(GetAssociatedWebUI()),
176 screenlock_icon_source);
179 void ScreenLocker::OnLoginFailure(const LoginFailure& error) {
180 content::RecordAction(UserMetricsAction("ScreenLocker_OnLoginFailure"));
181 if (authentication_start_time_.is_null()) {
182 LOG(ERROR) << "Start time is not set at authentication failure";
184 base::TimeDelta delta = base::Time::Now() - authentication_start_time_;
185 VLOG(1) << "Authentication failure: " << delta.InSecondsF() << " second(s)";
186 UMA_HISTOGRAM_TIMES("ScreenLocker.AuthenticationFailureTime", delta);
190 // Don't enable signout button here as we're showing
193 delegate_->ShowErrorMessage(incorrect_passwords_count_++ ?
194 IDS_LOGIN_ERROR_AUTHENTICATING_2ND_TIME :
195 IDS_LOGIN_ERROR_AUTHENTICATING,
196 HelpAppLauncher::HELP_CANT_ACCESS_ACCOUNT);
198 if (login_status_consumer_)
199 login_status_consumer_->OnLoginFailure(error);
202 void ScreenLocker::OnLoginSuccess(const UserContext& user_context) {
203 incorrect_passwords_count_ = 0;
204 if (authentication_start_time_.is_null()) {
205 if (!user_context.username.empty())
206 LOG(ERROR) << "Start time is not set at authentication success";
208 base::TimeDelta delta = base::Time::Now() - authentication_start_time_;
209 VLOG(1) << "Authentication success: " << delta.InSecondsF() << " second(s)";
210 UMA_HISTOGRAM_TIMES("ScreenLocker.AuthenticationSuccessTime", delta);
213 if (const User* user = UserManager::Get()->FindUser(user_context.username)) {
214 if (!user->is_active())
215 UserManager::Get()->SwitchActiveUser(user_context.username);
217 NOTREACHED() << "Logged in user not found.";
220 authentication_capture_.reset(new AuthenticationParametersCapture());
221 authentication_capture_->user_context = user_context;
223 // Add guard for case when something get broken in call chain to unlock
225 base::MessageLoop::current()->PostDelayedTask(
227 base::Bind(&ScreenLocker::UnlockOnLoginSuccess,
228 weak_factory_.GetWeakPtr()),
229 base::TimeDelta::FromMilliseconds(kUnlockGuardTimeoutMs));
230 delegate_->AnimateAuthenticationSuccess();
233 void ScreenLocker::UnlockOnLoginSuccess() {
234 DCHECK(base::MessageLoopForUI::IsCurrent());
235 if (!authentication_capture_.get()) {
236 LOG(WARNING) << "Call to UnlockOnLoginSuccess without previous " <<
237 "authentication success.";
241 if (login_status_consumer_) {
242 login_status_consumer_->OnLoginSuccess(
243 UserContext(authentication_capture_->user_context.username,
244 authentication_capture_->user_context.password,
245 authentication_capture_->user_context.auth_code,
246 authentication_capture_->user_context.username_hash,
247 authentication_capture_->user_context.using_oauth,
248 authentication_capture_->user_context.auth_flow));
250 authentication_capture_.reset();
251 weak_factory_.InvalidateWeakPtrs();
253 VLOG(1) << "Hiding the lock screen.";
254 chromeos::ScreenLocker::Hide();
257 void ScreenLocker::Authenticate(const UserContext& user_context) {
258 LOG_ASSERT(IsUserLoggedIn(user_context.username))
259 << "Invalid user trying to unlock.";
260 authentication_start_time_ = base::Time::Now();
261 delegate_->SetInputEnabled(false);
262 delegate_->OnAuthenticate();
264 BrowserThread::PostTask(
265 BrowserThread::UI, FROM_HERE,
266 base::Bind(&Authenticator::AuthenticateToUnlock,
267 authenticator_.get(),
271 void ScreenLocker::AuthenticateByPassword(const std::string& password) {
272 LOG_ASSERT(users_.size() == 1);
273 Authenticate(UserContext(users_[0]->email(), password, ""));
276 void ScreenLocker::ClearErrors() {
277 delegate_->ClearErrors();
280 void ScreenLocker::EnableInput() {
281 delegate_->SetInputEnabled(true);
284 void ScreenLocker::Signout() {
285 delegate_->ClearErrors();
286 content::RecordAction(UserMetricsAction("ScreenLocker_Signout"));
287 // We expect that this call will not wait for any user input.
288 // If it changes at some point, we will need to force exit.
289 chrome::AttemptUserExit();
291 // Don't hide yet the locker because the chrome screen may become visible
295 void ScreenLocker::ShowBannerMessage(const std::string& message) {
296 delegate_->ShowBannerMessage(message);
299 void ScreenLocker::ShowUserPodButton(const std::string& username,
300 const gfx::Image& icon,
301 const base::Closure& click_callback) {
305 screenlock_icon_provider_->AddIcon(username, icon);
307 // Append the current time to the URL so the image will not be cached.
308 std::string icon_url = ScreenlockIconSource::GetIconURLForUser(username)
309 + "?" + base::Int64ToString(base::Time::Now().ToInternalValue());
310 delegate_->ShowUserPodButton(username, icon_url, click_callback);
313 void ScreenLocker::ShowErrorMessage(int error_msg_id,
314 HelpAppLauncher::HelpTopic help_topic_id,
315 bool sign_out_only) {
316 delegate_->SetInputEnabled(!sign_out_only);
317 delegate_->ShowErrorMessage(error_msg_id, help_topic_id);
320 void ScreenLocker::SetLoginStatusConsumer(
321 chromeos::LoginStatusConsumer* consumer) {
322 login_status_consumer_ = consumer;
326 void ScreenLocker::InitClass() {
327 g_screen_lock_observer.Get();
331 void ScreenLocker::HandleLockScreenRequest() {
332 VLOG(1) << "Received LockScreen request from session manager";
333 if (UserAddingScreen::Get()->IsRunning()) {
334 VLOG(1) << "Waiting for user adding screen to stop";
335 UserAddingScreen::Get()->AddObserver(g_screen_lock_observer.Pointer());
336 UserAddingScreen::Get()->Cancel();
339 if (g_screen_lock_observer.Get().session_started() &&
340 UserManager::Get()->CanCurrentUserLock()) {
341 ScreenLocker::Show();
343 // If the current user's session cannot be locked or the user has not
344 // completed all sign-in steps yet, log out instead. The latter is done to
345 // avoid complications with displaying the lock screen over the login
346 // screen while remaining secure in the case the user walks away during
347 // the sign-in steps. See crbug.com/112225 and crbug.com/110933.
348 VLOG(1) << "Calling session manager's StopSession D-Bus method";
349 DBusThreadManager::Get()->GetSessionManagerClient()->StopSession();
354 void ScreenLocker::Show() {
355 content::RecordAction(UserMetricsAction("ScreenLocker_Show"));
356 DCHECK(base::MessageLoopForUI::IsCurrent());
358 // Check whether the currently logged in user is a guest account and if so,
359 // refuse to lock the screen (crosbug.com/23764).
360 // For a demo user, we should never show the lock screen (crosbug.com/27647).
361 if (UserManager::Get()->IsLoggedInAsGuest() ||
362 UserManager::Get()->IsLoggedInAsDemoUser()) {
363 VLOG(1) << "Refusing to lock screen for guest/demo account";
367 // If the active window is fullscreen, exit fullscreen to avoid the web page
368 // or app mimicking the lock screen. Do not exit fullscreen if the shelf is
369 // visible while in fullscreen because the shelf makes it harder for a web
370 // page or app to mimick the lock screen.
371 ash::wm::WindowState* active_window_state = ash::wm::GetActiveWindowState();
372 if (active_window_state &&
373 active_window_state->IsFullscreen() &&
374 active_window_state->hide_shelf_when_fullscreen()) {
375 active_window_state->ToggleFullscreen();
378 if (!screen_locker_) {
379 ScreenLocker* locker =
380 new ScreenLocker(UserManager::Get()->GetUnlockUsers());
381 VLOG(1) << "Created ScreenLocker " << locker;
384 VLOG(1) << "ScreenLocker " << screen_locker_ << " already exists; "
385 << " calling session manager's HandleLockScreenShown D-Bus method";
386 DBusThreadManager::Get()->GetSessionManagerClient()->
387 NotifyLockScreenShown();
392 void ScreenLocker::Hide() {
393 DCHECK(base::MessageLoopForUI::IsCurrent());
394 // For a guest/demo user, screen_locker_ would have never been initialized.
395 if (UserManager::Get()->IsLoggedInAsGuest() ||
396 UserManager::Get()->IsLoggedInAsDemoUser()) {
397 VLOG(1) << "Refusing to hide lock screen for guest/demo account";
401 DCHECK(screen_locker_);
402 base::Callback<void(void)> callback =
403 base::Bind(&ScreenLocker::ScheduleDeletion);
404 ash::Shell::GetInstance()->lock_state_controller()->
405 OnLockScreenHide(callback);
408 void ScreenLocker::ScheduleDeletion() {
409 // Avoid possible multiple calls.
410 if (screen_locker_ == NULL)
412 VLOG(1) << "Deleting ScreenLocker " << screen_locker_;
414 ash::PlaySystemSound(SOUND_UNLOCK, true /* honor_spoken_feedback */);
416 delete screen_locker_;
417 screen_locker_ = NULL;
420 ////////////////////////////////////////////////////////////////////////////////
421 // ScreenLocker, private:
423 ScreenLocker::~ScreenLocker() {
424 VLOG(1) << "Destroying ScreenLocker " << this;
425 DCHECK(base::MessageLoopForUI::IsCurrent());
427 if (authenticator_.get())
428 authenticator_->SetConsumer(NULL);
431 VLOG(1) << "Moving desktop background to unlocked container";
432 ash::Shell::GetInstance()->
433 desktop_background_controller()->MoveDesktopToUnlockedContainer();
435 screen_locker_ = NULL;
437 VLOG(1) << "Emitting SCREEN_LOCK_STATE_CHANGED with state=" << state;
438 content::NotificationService::current()->Notify(
439 chrome::NOTIFICATION_SCREEN_LOCK_STATE_CHANGED,
440 content::Source<ScreenLocker>(this),
441 content::Details<bool>(&state));
442 VLOG(1) << "Calling session manager's HandleLockScreenDismissed D-Bus method";
443 DBusThreadManager::Get()->GetSessionManagerClient()->
444 NotifyLockScreenDismissed();
447 void ScreenLocker::SetAuthenticator(Authenticator* authenticator) {
448 authenticator_ = authenticator;
451 void ScreenLocker::ScreenLockReady() {
453 base::TimeDelta delta = base::Time::Now() - start_time_;
454 VLOG(1) << "ScreenLocker " << this << " is ready after "
455 << delta.InSecondsF() << " second(s)";
456 UMA_HISTOGRAM_TIMES("ScreenLocker.ScreenLockTime", delta);
458 VLOG(1) << "Moving desktop background to locked container";
459 ash::Shell::GetInstance()->
460 desktop_background_controller()->MoveDesktopToLockedContainer();
463 VLOG(1) << "Emitting SCREEN_LOCK_STATE_CHANGED with state=" << state;
464 content::NotificationService::current()->Notify(
465 chrome::NOTIFICATION_SCREEN_LOCK_STATE_CHANGED,
466 content::Source<ScreenLocker>(this),
467 content::Details<bool>(&state));
468 VLOG(1) << "Calling session manager's HandleLockScreenShown D-Bus method";
469 DBusThreadManager::Get()->GetSessionManagerClient()->NotifyLockScreenShown();
472 content::WebUI* ScreenLocker::GetAssociatedWebUI() {
473 return delegate_->GetAssociatedWebUI();
476 bool ScreenLocker::IsUserLoggedIn(const std::string& username) {
477 for (UserList::const_iterator it = users_.begin(); it != users_.end(); ++it) {
478 if ((*it)->email() == username)
484 } // namespace chromeos