keepassxc

Форк
0
/
Add.cpp 
134 строки · 5.3 Кб
1
/*
2
 *  Copyright (C) 2019 KeePassXC Team <team@keepassxc.org>
3
 *
4
 *  This program is free software: you can redistribute it and/or modify
5
 *  it under the terms of the GNU General Public License as published by
6
 *  the Free Software Foundation, either version 2 or (at your option)
7
 *  version 3 of the License.
8
 *
9
 *  This program is distributed in the hope that it will be useful,
10
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
11
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
 *  GNU General Public License for more details.
13
 *
14
 *  You should have received a copy of the GNU General Public License
15
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
16
 */
17

18
#include "Add.h"
19

20
#include "Generate.h"
21
#include "Utils.h"
22
#include "core/Group.h"
23
#include "core/PasswordGenerator.h"
24

25
#include <QCommandLineParser>
26

27
const QCommandLineOption Add::UsernameOption = QCommandLineOption(QStringList() << "u"
28
                                                                                << "username",
29
                                                                  QObject::tr("Username for the entry."),
30
                                                                  QObject::tr("username"));
31

32
const QCommandLineOption Add::UrlOption =
33
    QCommandLineOption(QStringList() << "url", QObject::tr("URL for the entry."), QObject::tr("URL"));
34

35
const QCommandLineOption Add::NotesOption =
36
    QCommandLineOption(QStringList() << "notes", QObject::tr("Notes for the entry."), QObject::tr("Notes"));
37

38
const QCommandLineOption Add::PasswordPromptOption =
39
    QCommandLineOption(QStringList() << "p"
40
                                     << "password-prompt",
41
                       QObject::tr("Prompt for the entry's password."));
42

43
const QCommandLineOption Add::GenerateOption = QCommandLineOption(QStringList() << "g"
44
                                                                                << "generate",
45
                                                                  QObject::tr("Generate a password for the entry."));
46

47
Add::Add()
48
{
49
    name = QString("add");
50
    description = QObject::tr("Add a new entry to a database.");
51
    options.append(Add::UsernameOption);
52
    options.append(Add::UrlOption);
53
    options.append(Add::NotesOption);
54
    options.append(Add::PasswordPromptOption);
55
    positionalArguments.append({QString("entry"), QObject::tr("Path of the entry to add."), QString("")});
56

57
    // Password generation options.
58
    options.append(Add::GenerateOption);
59
    options.append(Generate::PasswordLengthOption);
60
    options.append(Generate::LowerCaseOption);
61
    options.append(Generate::UpperCaseOption);
62
    options.append(Generate::NumbersOption);
63
    options.append(Generate::SpecialCharsOption);
64
    options.append(Generate::ExtendedAsciiOption);
65
    options.append(Generate::ExcludeCharsOption);
66
    options.append(Generate::ExcludeSimilarCharsOption);
67
    options.append(Generate::IncludeEveryGroupOption);
68
    options.append(Generate::CustomCharacterSetOption);
69
}
70

71
int Add::executeWithDatabase(QSharedPointer<Database> database, QSharedPointer<QCommandLineParser> parser)
72
{
73
    auto& out = Utils::STDOUT;
74
    auto& err = Utils::STDERR;
75

76
    const QStringList args = parser->positionalArguments();
77
    auto& entryPath = args.at(1);
78

79
    // Cannot use those 2 options at the same time!
80
    if (parser->isSet(Add::GenerateOption) && parser->isSet(Add::PasswordPromptOption)) {
81
        err << QObject::tr("Cannot generate a password and prompt at the same time.") << endl;
82
        return EXIT_FAILURE;
83
    }
84

85
    // Validating the password generator here, before we actually create
86
    // the entry.
87
    QSharedPointer<PasswordGenerator> passwordGenerator;
88
    if (parser->isSet(Add::GenerateOption)) {
89
        passwordGenerator = Generate::createGenerator(parser);
90
        if (passwordGenerator.isNull()) {
91
            return EXIT_FAILURE;
92
        }
93
    }
94

95
    Entry* entry = database->rootGroup()->addEntryWithPath(entryPath);
96
    if (!entry) {
97
        err << QObject::tr("Could not create entry with path %1.").arg(entryPath) << endl;
98
        return EXIT_FAILURE;
99
    }
100

101
    if (!parser->value(Add::UsernameOption).isEmpty()) {
102
        entry->setUsername(parser->value(Add::UsernameOption));
103
    }
104

105
    if (!parser->value(Add::UrlOption).isEmpty()) {
106
        entry->setUrl(parser->value(Add::UrlOption));
107
    }
108

109
    if (!parser->value(Add::NotesOption).isEmpty()) {
110
        entry->setNotes(parser->value(Add::NotesOption).replace("\\n", "\n"));
111
    }
112

113
    if (parser->isSet(Add::PasswordPromptOption)) {
114
        if (!parser->isSet(Command::QuietOption)) {
115
            out << QObject::tr("Enter password for new entry: ") << flush;
116
        }
117
        QString password = Utils::getPassword(parser->isSet(Command::QuietOption));
118
        entry->setPassword(password);
119
    } else if (parser->isSet(Add::GenerateOption)) {
120
        QString password = passwordGenerator->generatePassword();
121
        entry->setPassword(password);
122
    }
123

124
    QString errorMessage;
125
    if (!database->save(Database::Atomic, {}, &errorMessage)) {
126
        err << QObject::tr("Writing the database failed %1.").arg(errorMessage) << endl;
127
        return EXIT_FAILURE;
128
    }
129

130
    if (!parser->isSet(Command::QuietOption)) {
131
        out << QObject::tr("Successfully added entry %1.").arg(entry->title()) << endl;
132
    }
133
    return EXIT_SUCCESS;
134
}
135

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.