e72152ac1da5b642146bf3eb2b47a6155e1390f8
[platform/framework/web/crosswalk.git] / src / chrome / browser / ui / webui / options / managed_user_import_handler.cc
1 // Copyright 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 #include "chrome/browser/ui/webui/options/managed_user_import_handler.h"
6
7 #include <set>
8
9 #include "base/bind.h"
10 #include "base/prefs/pref_service.h"
11 #include "base/values.h"
12 #include "chrome/browser/browser_process.h"
13 #include "chrome/browser/chrome_notification_types.h"
14 #include "chrome/browser/managed_mode/managed_user_constants.h"
15 #include "chrome/browser/managed_mode/managed_user_shared_settings_service.h"
16 #include "chrome/browser/managed_mode/managed_user_shared_settings_service_factory.h"
17 #include "chrome/browser/managed_mode/managed_user_sync_service.h"
18 #include "chrome/browser/managed_mode/managed_user_sync_service_factory.h"
19 #include "chrome/browser/profiles/profile.h"
20 #include "chrome/browser/profiles/profile_info_cache.h"
21 #include "chrome/browser/profiles/profile_manager.h"
22 #include "chrome/browser/signin/signin_global_error.h"
23 #include "chrome/browser/signin/signin_manager.h"
24 #include "chrome/browser/signin/signin_manager_factory.h"
25 #include "chrome/common/pref_names.h"
26 #include "chrome/common/url_constants.h"
27 #include "content/public/browser/notification_details.h"
28 #include "content/public/browser/notification_source.h"
29 #include "content/public/browser/web_ui.h"
30 #include "grit/generated_resources.h"
31 #include "grit/theme_resources.h"
32 #include "ui/base/l10n/l10n_util.h"
33
34 namespace {
35
36 scoped_ptr<base::ListValue> GetAvatarIcons() {
37   scoped_ptr<base::ListValue> avatar_icons(new base::ListValue);
38   for (size_t i = 0; i < ProfileInfoCache::GetDefaultAvatarIconCount(); ++i) {
39     std::string avatar_url = ProfileInfoCache::GetDefaultAvatarIconUrl(i);
40     avatar_icons->Append(new base::StringValue(avatar_url));
41   }
42
43   return avatar_icons.Pass();
44 }
45
46 }  // namespace
47
48 namespace options {
49
50 ManagedUserImportHandler::ManagedUserImportHandler()
51     : weak_ptr_factory_(this) {}
52
53 ManagedUserImportHandler::~ManagedUserImportHandler() {
54   Profile* profile = Profile::FromWebUI(web_ui());
55   if (!profile->IsManaged()) {
56     ManagedUserSyncService* service =
57         ManagedUserSyncServiceFactory::GetForProfile(profile);
58     if (service)
59       service->RemoveObserver(this);
60     subscription_.reset();
61   }
62 }
63
64 void ManagedUserImportHandler::GetLocalizedValues(
65     base::DictionaryValue* localized_strings) {
66   DCHECK(localized_strings);
67
68   static OptionsStringResource resources[] = {
69       { "managedUserImportTitle", IDS_IMPORT_EXISTING_MANAGED_USER_TITLE },
70       { "managedUserImportText", IDS_IMPORT_EXISTING_MANAGED_USER_TEXT },
71       { "createNewUserLink", IDS_CREATE_NEW_USER_LINK },
72       { "managedUserImportOk", IDS_IMPORT_EXISTING_MANAGED_USER_OK },
73       { "managedUserImportSigninError", IDS_MANAGED_USER_IMPORT_SIGN_IN_ERROR },
74       { "managedUserAlreadyOnThisDevice",
75           IDS_MANAGED_USER_ALREADY_ON_THIS_DEVICE },
76       { "noExistingManagedUsers", IDS_MANAGED_USER_NO_EXISTING_ERROR },
77       { "managedUserSelectAvatarTitle", IDS_MANAGED_USER_SELECT_AVATAR_TITLE },
78       { "managedUserSelectAvatarText", IDS_MANAGED_USER_SELECT_AVATAR_TEXT },
79       { "managedUserSelectAvatarOk", IDS_MANAGED_USER_SELECT_AVATAR_OK },
80   };
81
82   RegisterStrings(localized_strings, resources, arraysize(resources));
83   localized_strings->Set("avatarIcons", GetAvatarIcons().release());
84 }
85
86 void ManagedUserImportHandler::InitializeHandler() {
87   Profile* profile = Profile::FromWebUI(web_ui());
88   registrar_.Add(this, chrome::NOTIFICATION_GLOBAL_ERRORS_CHANGED,
89                  content::Source<Profile>(profile));
90   if (!profile->IsManaged()) {
91     ManagedUserSyncService* sync_service =
92         ManagedUserSyncServiceFactory::GetForProfile(profile);
93     if (sync_service) {
94       sync_service->AddObserver(this);
95       ManagedUserSharedSettingsService* settings_service =
96           ManagedUserSharedSettingsServiceFactory::GetForBrowserContext(
97               profile);
98       subscription_ = settings_service->Subscribe(
99           base::Bind(&ManagedUserImportHandler::OnSharedSettingChanged,
100                      weak_ptr_factory_.GetWeakPtr()));
101     } else {
102       DCHECK(!ManagedUserSharedSettingsServiceFactory::GetForBrowserContext(
103                  profile));
104     }
105   }
106 }
107
108 void ManagedUserImportHandler::RegisterMessages() {
109   web_ui()->RegisterMessageCallback("requestManagedUserImportUpdate",
110       base::Bind(&ManagedUserImportHandler::RequestManagedUserImportUpdate,
111                  base::Unretained(this)));
112 }
113
114 void ManagedUserImportHandler::Observe(
115     int type,
116     const content::NotificationSource& source,
117     const content::NotificationDetails& details) {
118   if (type == chrome::NOTIFICATION_GLOBAL_ERRORS_CHANGED) {
119     SigninGlobalError* error =
120         SigninGlobalError::GetForProfile(Profile::FromWebUI(web_ui()));
121     if (content::Details<SigninGlobalError>(details).ptr() == error)
122       FetchManagedUsers();
123   }
124 }
125
126 void ManagedUserImportHandler::OnManagedUsersChanged() {
127   FetchManagedUsers();
128 }
129
130 void ManagedUserImportHandler::FetchManagedUsers() {
131   web_ui()->CallJavascriptFunction("options.ManagedUserListData.resetPromise");
132   RequestManagedUserImportUpdate(NULL);
133 }
134
135 void ManagedUserImportHandler::RequestManagedUserImportUpdate(
136     const base::ListValue* /* args */) {
137   if (Profile::FromWebUI(web_ui())->IsManaged())
138     return;
139
140   if (!IsAccountConnected() || HasAuthError()) {
141     ClearManagedUsersAndShowError();
142   } else {
143     ManagedUserSyncService* managed_user_sync_service =
144         ManagedUserSyncServiceFactory::GetForProfile(
145             Profile::FromWebUI(web_ui()));
146     managed_user_sync_service->GetManagedUsersAsync(
147         base::Bind(&ManagedUserImportHandler::SendExistingManagedUsers,
148                    weak_ptr_factory_.GetWeakPtr()));
149   }
150 }
151
152 void ManagedUserImportHandler::SendExistingManagedUsers(
153     const base::DictionaryValue* dict) {
154   DCHECK(dict);
155   const ProfileInfoCache& cache =
156       g_browser_process->profile_manager()->GetProfileInfoCache();
157
158   // Collect the ids of local supervised user profiles.
159   std::set<std::string> managed_user_ids;
160   for (size_t i = 0; i < cache.GetNumberOfProfiles(); ++i) {
161     if (cache.ProfileIsManagedAtIndex(i))
162       managed_user_ids.insert(cache.GetManagedUserIdOfProfileAtIndex(i));
163   }
164
165   base::ListValue managed_users;
166   Profile* profile = Profile::FromWebUI(web_ui());
167   ManagedUserSharedSettingsService* service =
168       ManagedUserSharedSettingsServiceFactory::GetForBrowserContext(profile);
169   for (base::DictionaryValue::Iterator it(*dict); !it.IsAtEnd(); it.Advance()) {
170     const base::DictionaryValue* value = NULL;
171     bool success = it.value().GetAsDictionary(&value);
172     DCHECK(success);
173     std::string name;
174     value->GetString(ManagedUserSyncService::kName, &name);
175
176     base::DictionaryValue* managed_user = new base::DictionaryValue;
177     managed_user->SetString("id", it.key());
178     managed_user->SetString("name", name);
179
180     int avatar_index = ManagedUserSyncService::kNoAvatar;
181     const base::Value* avatar_index_value =
182         service->GetValue(it.key(), managed_users::kChromeAvatarIndex);
183     if (avatar_index_value) {
184       success = avatar_index_value->GetAsInteger(&avatar_index);
185     } else {
186       // Check if there is a legacy avatar index stored.
187       std::string avatar_str;
188       value->GetString(ManagedUserSyncService::kChromeAvatar, &avatar_str);
189       success =
190           ManagedUserSyncService::GetAvatarIndex(avatar_str, &avatar_index);
191     }
192     DCHECK(success);
193     managed_user->SetBoolean("needAvatar",
194                              avatar_index == ManagedUserSyncService::kNoAvatar);
195
196     std::string supervised_user_icon =
197         std::string(chrome::kChromeUIThemeURL) +
198         "IDR_SUPERVISED_USER_PLACEHOLDER";
199     std::string avatar_url =
200         avatar_index == ManagedUserSyncService::kNoAvatar ?
201             supervised_user_icon :
202             ProfileInfoCache::GetDefaultAvatarIconUrl(avatar_index);
203     managed_user->SetString("iconURL", avatar_url);
204     bool on_current_device =
205         managed_user_ids.find(it.key()) != managed_user_ids.end();
206     managed_user->SetBoolean("onCurrentDevice", on_current_device);
207
208     managed_users.Append(managed_user);
209   }
210
211   web_ui()->CallJavascriptFunction(
212       "options.ManagedUserListData.receiveExistingManagedUsers",
213       managed_users);
214 }
215
216 void ManagedUserImportHandler::ClearManagedUsersAndShowError() {
217   web_ui()->CallJavascriptFunction("options.ManagedUserListData.onSigninError");
218 }
219
220 bool ManagedUserImportHandler::IsAccountConnected() const {
221   Profile* profile = Profile::FromWebUI(web_ui());
222   SigninManagerBase* signin_manager =
223       SigninManagerFactory::GetForProfile(profile);
224   return !signin_manager->GetAuthenticatedUsername().empty();
225 }
226
227 bool ManagedUserImportHandler::HasAuthError() const {
228   Profile* profile = Profile::FromWebUI(web_ui());
229   SigninGlobalError* signin_global_error =
230       SigninGlobalError::GetForProfile(profile);
231   GoogleServiceAuthError::State state =
232       signin_global_error->GetLastAuthError().state();
233
234   return state == GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS ||
235       state == GoogleServiceAuthError::USER_NOT_SIGNED_UP ||
236       state == GoogleServiceAuthError::ACCOUNT_DELETED ||
237       state == GoogleServiceAuthError::ACCOUNT_DISABLED;
238 }
239
240 void ManagedUserImportHandler::OnSharedSettingChanged(
241     const std::string& managed_user_id,
242     const std::string& key) {
243   if (key == managed_users::kChromeAvatarIndex)
244     FetchManagedUsers();
245 }
246
247 }  // namespace options