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#include "components/password_manager/core/browser/password_generation_manager.h"
6
7#include "components/autofill/core/browser/autofill_field.h"
8#include "components/autofill/core/browser/field_types.h"
9#include "components/autofill/core/browser/form_structure.h"
10#include "components/autofill/core/common/form_data.h"
11#include "components/password_manager/core/browser/password_manager.h"
12#include "components/password_manager/core/browser/password_manager_client.h"
13#include "components/password_manager/core/browser/password_manager_driver.h"
14
15namespace password_manager {
16
17PasswordGenerationManager::PasswordGenerationManager(
18    PasswordManagerClient* client)
19    : client_(client),
20      driver_(client->GetDriver()) {}
21
22PasswordGenerationManager::~PasswordGenerationManager() {}
23
24void PasswordGenerationManager::DetectAccountCreationForms(
25    const std::vector<autofill::FormStructure*>& forms) {
26  std::vector<autofill::FormData> account_creation_forms;
27  for (std::vector<autofill::FormStructure*>::const_iterator form_it =
28           forms.begin(); form_it != forms.end(); ++form_it) {
29    autofill::FormStructure* form = *form_it;
30    for (std::vector<autofill::AutofillField*>::const_iterator field_it =
31             form->begin(); field_it != form->end(); ++field_it) {
32      autofill::AutofillField* field = *field_it;
33      if (field->server_type() == autofill::ACCOUNT_CREATION_PASSWORD) {
34        account_creation_forms.push_back(form->ToFormData());
35        break;
36      }
37    }
38  }
39  if (!account_creation_forms.empty() && IsGenerationEnabled())
40    driver_->AccountCreationFormsFound(account_creation_forms);
41}
42
43// In order for password generation to be enabled, we need to make sure:
44// (1) Password sync is enabled, and
45// (2) Password saving is enabled.
46bool PasswordGenerationManager::IsGenerationEnabled() const {
47  if (!driver_->GetPasswordManager()->IsSavingEnabledForCurrentPage()) {
48    DVLOG(2) << "Generation disabled because password saving is disabled";
49    return false;
50  }
51
52  if (!client_->IsPasswordSyncEnabled()) {
53    DVLOG(2) << "Generation disabled because passwords are not being synced";
54    return false;
55  }
56
57  return true;
58}
59
60}  // namespace password_manager
61