accountmodel.cpp 17.1 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/*************************************************************************************
 *  Copyright (C) 2012 by Alejandro Fiestas Olivares <afiestas@kde.org>              *
 *                                                                                   *
 *  This program is free software; you can redistribute it and/or                    *
 *  modify it under the terms of the GNU General Public License                      *
 *  as published by the Free Software Foundation; either version 2                   *
 *  of the License, or (at your option) any later version.                           *
 *                                                                                   *
 *  This program is distributed in the hope that it will be useful,                  *
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of                   *
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the                    *
 *  GNU General Public License for more details.                                     *
 *                                                                                   *
 *  You should have received a copy of the GNU General Public License                *
 *  along with this program; if not, write to the Free Software                      *
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA   *
 *************************************************************************************/


#include "accountmodel.h"
21
22
#include "usersessions.h"

23
24
25
#include "accounts_interface.h"
#include "user_interface.h"

Vishesh Handa's avatar
Vishesh Handa committed
26
#include <QIcon>
27

Laurent Montel's avatar
Laurent Montel committed
28
#include "user_manager_debug.h"
29
#include <KLocalizedString>
30
#include <kiconloader.h>
31

32
33
34
#include <KAuth/KAuthActionReply>
#include <KAuth/KAuthExecuteJob>

35
36
37
#include <sys/types.h>
#include <unistd.h>

38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include <KConfig>
#include <KConfigGroup>

#define SDDM_CONFIG_FILE    "/etc/sddm.conf"

AutomaticLoginSettings::AutomaticLoginSettings()
{
    KConfig config(QStringLiteral(SDDM_CONFIG_FILE));
    m_autoLoginUser = config.group("Autologin").readEntry("User", QString());
}

QString AutomaticLoginSettings::autoLoginUser() const
{
    return m_autoLoginUser;
}

bool AutomaticLoginSettings::setAutoLoginUser(const QString& username)
{
56
57
    KAuth::Action saveAction(QStringLiteral("org.kde.kcontrol.kcmsddm.save"));
    saveAction.setHelperId(QStringLiteral("org.kde.kcontrol.kcmsddm"));
58
59
    QVariantMap args;

60
61
    args[QStringLiteral("sddm.conf")] = QStringLiteral(SDDM_CONFIG_FILE);
    args[QStringLiteral("sddm.conf/Autologin/User")] = username;
62

63
    saveAction.setHelperId(QStringLiteral("org.kde.kcontrol.kcmsddm"));
64
65
66
67
    saveAction.setArguments(args);

    auto job = saveAction.execute();
    if (!job->exec()) {
Laurent Montel's avatar
Laurent Montel committed
68
        qCWarning(USER_MANAGER_LOG) << "fail" << job->errorText();
69
70
71
72
73
74
75
        return false;
    }

    m_autoLoginUser = username;
    return true;
}

76
77
typedef OrgFreedesktopAccountsInterface AccountsManager;
typedef OrgFreedesktopAccountsUserInterface Account;
78
79
80
AccountModel::AccountModel(QObject* parent)
 : QAbstractListModel(parent)
 , m_sessions(new UserSession(this))
81
{
82
    m_dbus = new AccountsManager(QStringLiteral("org.freedesktop.Accounts"), QStringLiteral("/org/freedesktop/Accounts"), QDBusConnection::systemBus(), this);
83
84
85
86
    QDBusPendingReply <QList <QDBusObjectPath > > reply = m_dbus->ListCachedUsers();
    reply.waitForFinished();

    if (reply.isError()) {
Laurent Montel's avatar
Laurent Montel committed
87
        qCDebug(USER_MANAGER_LOG) << reply.error().message();
88
89
90
        return;
    }

91
92
    const QList<QDBusObjectPath> users = reply.value();
    for (const QDBusObjectPath& path : users) {
93
        addAccount(path.path());
94
    }
95

96
    // Adding fake "new user" directly into cache
97
    addAccountToCache(QStringLiteral("new-user"), nullptr);
98

David Edmundson's avatar
David Edmundson committed
99
    m_kEmailSettings.setProfile(m_kEmailSettings.defaultProfileName());
100

Laurent Montel's avatar
Laurent Montel committed
101
102
    connect(m_dbus, &OrgFreedesktopAccountsInterface::UserAdded, this, &AccountModel::UserAdded);
    connect(m_dbus, &OrgFreedesktopAccountsInterface::UserDeleted, this, &AccountModel::UserDeleted);
103

Laurent Montel's avatar
Laurent Montel committed
104
    connect(m_sessions, &UserSession::userLogged, this, &AccountModel::userLogged);
105
106
107
108
}

AccountModel::~AccountModel()
{
Àlex Fiestas's avatar
Àlex Fiestas committed
109
110
    delete m_dbus;
    qDeleteAll(m_users);
111
112
113
114
115
116
117
118
}

int AccountModel::rowCount(const QModelIndex& parent) const
{
    if (parent.isValid()) {
        return 0;
    }

119
    return m_userPath.count();
120
121
122
123
124
125
126
127
128
129
130
131
}

QVariant AccountModel::data(const QModelIndex& index, int role) const
{
    if(!index.isValid()) {
        return QVariant();
    }

    if (index.row() >= m_users.count()) {
        return QVariant();
    }

132
133
    QString path = m_userPath.at(index.row());
    Account* acc = m_users.value(path);
134
    if (!acc) {
135
136
        //new user
        return newUserData(role);
137
138
    }

139
140
141
142
143
144
    switch(role) {
        case Qt::DisplayRole || AccountModel::FriendlyName:
            if (!acc->realName().isEmpty()) {
                return acc->realName();
            }
            return acc->userName();
145
        case Qt::DecorationRole || AccountModel::Face:
146
        {
147
            QFile file(acc->iconFile());
148
            int size = IconSize(KIconLoader::Dialog);
149
            if (!file.exists()) {
150
                return QIcon::fromTheme(QStringLiteral("user-identity")).pixmap(size, size);
151
            }
152
153
154
            auto pixMap = QPixmap(file.fileName()).scaled(static_cast<int>(size * m_dpr), static_cast<int>(size * m_dpr), Qt::KeepAspectRatio, Qt::SmoothTransformation);
            pixMap.setDevicePixelRatio(m_dpr);
            return pixMap;
155
        }
156
157
158
159
160
161
162
163
        case AccountModel::RealName:
            return acc->realName();
        case AccountModel::Username:
            return acc->userName();
        case AccountModel::Email:
            return acc->email();
        case AccountModel::Administrator:
            return acc->accountType() == 1;
164
165
166
167
        case AccountModel::AutomaticLogin: {
            const QString username = index.data(AccountModel::Username).toString();
            return m_autoLoginSettings.autoLoginUser() == username;
        }
168
        case AccountModel::Logged:
169
170
171
172
            if (m_loggedAccounts.contains(path)) {
                return m_loggedAccounts[path];
            }
            return QVariant();
173
174
        case AccountModel::Created:
            return true;
175
176
    }

177
178
179
    return QVariant();
}

Àlex Fiestas's avatar
Àlex Fiestas committed
180
181
182
183
184
185
186
187
188
189
bool AccountModel::setData(const QModelIndex& index, const QVariant& value, int role)
{
    if(!index.isValid()) {
        return false;
    }

    if (index.row() >= m_users.count()) {
        return false;
    }

190
191
    QString path = m_userPath.at(index.row());
    Account* acc = m_users.value(path);
Àlex Fiestas's avatar
Àlex Fiestas committed
192
    if (!acc) {
193
        return newUserSetData(index, value, role);
Àlex Fiestas's avatar
Àlex Fiestas committed
194
195
    }

Àlex Fiestas's avatar
Àlex Fiestas committed
196
    switch(role) {
197
198
        //The modification of the face file should be done outside
        case AccountModel::Face:
199
200
201
            if (checkForErrors(acc->SetIconFile(value.toString()))) {
                return false;
            }
202
203
            emit dataChanged(index, index);
            return true;
Àlex Fiestas's avatar
Àlex Fiestas committed
204
        case AccountModel::RealName:
205
            if (checkForErrors(acc->SetRealName(value.toString()))) {
Àlex Fiestas's avatar
Àlex Fiestas committed
206
207
                return false;
            }
David Edmundson's avatar
David Edmundson committed
208
            m_kEmailSettings.setSetting(KEMailSettings::RealName, value.toString());
Àlex Fiestas's avatar
Àlex Fiestas committed
209

Àlex Fiestas's avatar
Àlex Fiestas committed
210
211
212
            emit dataChanged(index, index);
            return true;
        case AccountModel::Username:
213
            if (checkForErrors(acc->SetUserName(value.toString()))) {
Àlex Fiestas's avatar
Àlex Fiestas committed
214
215
                return false;
            }
Àlex Fiestas's avatar
Àlex Fiestas committed
216

217
218
219
220
221
222
223
            emit dataChanged(index, index);
            return true;
        case AccountModel::Password:
            if (checkForErrors(acc->SetPassword(cryptPassword(value.toString()), QString()))) {
                return false;
            }

Àlex Fiestas's avatar
Àlex Fiestas committed
224
225
226
            emit dataChanged(index, index);
            return true;
        case AccountModel::Email:
227
            if (checkForErrors(acc->SetEmail(value.toString()))) {
Àlex Fiestas's avatar
Àlex Fiestas committed
228
229
                return false;
            }
David Edmundson's avatar
David Edmundson committed
230
            m_kEmailSettings.setSetting(KEMailSettings::EmailAddress, value.toString());
Àlex Fiestas's avatar
Àlex Fiestas committed
231

Àlex Fiestas's avatar
Àlex Fiestas committed
232
233
234
            emit dataChanged(index, index);
            return true;
        case AccountModel::Administrator:
235
            if (checkForErrors(acc->SetAccountType(value.toBool() ? 1 : 0))) {
Àlex Fiestas's avatar
Àlex Fiestas committed
236
237
                return false;
            }
Àlex Fiestas's avatar
Àlex Fiestas committed
238

Àlex Fiestas's avatar
Àlex Fiestas committed
239
240
241
            emit dataChanged(index, index);
            return true;
        case AccountModel::AutomaticLogin:
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
        {
            const bool autoLoginSet = value.toBool();
            const QString username = index.data(AccountModel::Username).toString();

            //if the checkbox is set and the SDDM config is not already us, set it to us
            //all rows need updating as we may have unset it from someone else.
            if (autoLoginSet && m_autoLoginSettings.autoLoginUser() != username) {
                if (m_autoLoginSettings.setAutoLoginUser(username)) {
                    emit dataChanged(createIndex(0, 0), createIndex(rowCount(), 0));
                    return true;
                }
                return false;
            }
            //if the checkbox is not set and the SDDM config is set to us, then clear it
            else if (!autoLoginSet && m_autoLoginSettings.autoLoginUser() == username) {
                if (m_autoLoginSettings.setAutoLoginUser(QString())) {
                    emit dataChanged(index, index);
                    return true;
                }
Àlex Fiestas's avatar
Àlex Fiestas committed
261
262
263
                return false;
            }
            return true;
264
        }
265
266
        case AccountModel::Logged:
            m_loggedAccounts[path] = value.toBool();
267
            emit dataChanged(index, index);
268
            return true;
269
        case AccountModel::Created:
270
271
272
            qFatal("AccountModel NewAccount should never be set");
            return false;

Àlex Fiestas's avatar
Àlex Fiestas committed
273
274
275
276
277
    }

    return QAbstractItemModel::setData(index, value, role);
}

Àlex Fiestas's avatar
Àlex Fiestas committed
278
bool AccountModel::removeRows(int row, int count, const QModelIndex& parent)
279
{
Àlex Fiestas's avatar
Àlex Fiestas committed
280
281
    Q_UNUSED(count);
    Q_UNUSED(parent);
282
283
284
285
    return removeAccountKeepingFiles(row, true);
}

bool AccountModel::removeAccountKeepingFiles(int row, bool keepFile)
Àlex Fiestas's avatar
Àlex Fiestas committed
286
287
{
    Account* acc = m_users.value(m_userPath.at(row));
288
    QDBusPendingReply <void > rep = m_dbus->DeleteUser(acc->uid(), keepFile);
Àlex Fiestas's avatar
Àlex Fiestas committed
289
290
291
292
293
    rep.waitForFinished();

    return !rep.isError();
}

294
295
296
297
298
299
QVariant AccountModel::newUserData(int role) const
{
    switch(role) {
        case Qt::DisplayRole || AccountModel::FriendlyName:
            return i18n("New User");
        case Qt::DecorationRole || AccountModel::Face:
300
            return QIcon::fromTheme(QStringLiteral("list-add-user")).pixmap(IconSize(KIconLoader::Dialog), IconSize(KIconLoader::Dialog));
301
302
        case AccountModel::Created:
            return false;
303
304
305
306
    }
    return QVariant();
}

307
bool AccountModel::newUserSetData(const QModelIndex &index, const QVariant& value, int roleInt)
Àlex Fiestas's avatar
Àlex Fiestas committed
308
{
Laurent Montel's avatar
Laurent Montel committed
309
    AccountModel::Role role = static_cast<AccountModel::Role>(roleInt);
Àlex Fiestas's avatar
Àlex Fiestas committed
310
    m_newUserData[role] = value;
311
312
    QList<AccountModel::Role> roles = m_newUserData.keys();
    if (!roles.contains(Username) || !roles.contains(RealName) || !roles.contains(Administrator)) {
Àlex Fiestas's avatar
Àlex Fiestas committed
313
314
315
        return true;
    }

316
317

    int userType = m_newUserData[Administrator].toBool() ? 1 : 0;
Àlex Fiestas's avatar
Àlex Fiestas committed
318
319
320
321
    QDBusPendingReply <QDBusObjectPath > reply = m_dbus->CreateUser(m_newUserData[Username].toString(), m_newUserData[RealName].toString(), userType);
    reply.waitForFinished();

    if (reply.isError()) {
Laurent Montel's avatar
Laurent Montel committed
322
323
        qCDebug(USER_MANAGER_LOG) << reply.error().name();
        qCDebug(USER_MANAGER_LOG) << reply.error().message();
324
        m_newUserData.clear();
Àlex Fiestas's avatar
Àlex Fiestas committed
325
326
327
        return false;
    }

328
329
330
331
332
333
334
335
336
337
338
339
340
    m_newUserData.remove(Username);
    m_newUserData.remove(RealName);
    m_newUserData.remove(Administrator);

    //If we don't have anything else to set just return
    if (m_newUserData.isEmpty()) {
        return true;
    }

    UserAdded(reply.value());

    QHash<AccountModel::Role, QVariant>::const_iterator i = m_newUserData.constBegin();
    while (i != m_newUserData.constEnd()) {
Laurent Montel's avatar
Laurent Montel committed
341
        qCDebug(USER_MANAGER_LOG) << "Setting extra:" << i.key() << "with value:" << i.value();
342
343
344
        setData(index, i.value(), i.key());
        ++i;
    }
Àlex Fiestas's avatar
Àlex Fiestas committed
345
346
347
348
349
350

    m_newUserData.clear();

    return true;
}

351
352
void AccountModel::addAccount(const QString& path)
{
353
    Account *acc = new Account(QStringLiteral("org.freedesktop.Accounts"), path, QDBusConnection::systemBus(), this);
Àlex Fiestas's avatar
Àlex Fiestas committed
354
    qulonglong uid = acc->uid();
355
356
357
358
    if (!acc->isValid() || acc->lastError().isValid() || acc->systemAccount()) {
        return;
    }

Laurent Montel's avatar
Laurent Montel committed
359
    connect(acc, &OrgFreedesktopAccountsUserInterface::Changed, this, &AccountModel::Changed);
360
361
362
363
364
365
366
367
    if (uid == getuid()) {
        addAccountToCache(path, acc, 0);
        return;
    }

    addAccountToCache(path, acc);
}

368
void AccountModel::addAccountToCache(const QString& path, Account* acc, int pos)
369
370
{
    if (pos > -1) {
371
        m_userPath.insert(pos, path);
372
373
374
375
376
    } else {
        m_userPath.append(path);
    }

    m_users.insert(path, acc);
377
    m_loggedAccounts[path] = false;
378
379
}

380
381
382
383
384
385
386
387
388
389
void AccountModel::replaceAccount(const QString &path, OrgFreedesktopAccountsUserInterface *acc, int pos)
{
    if (pos >= m_userPath.size() || pos < 0) {
        return;
    }
    m_userPath.replace(pos, path);

    m_users.insert(path, acc);
    m_loggedAccounts[path] = false;
}
390

391
392
393
394
void AccountModel::removeAccount(const QString& path)
{
    m_userPath.removeAll(path);
    delete m_users.take(path);
395
    m_loggedAccounts.remove(path);
396
397
}

398
399
400
401
bool AccountModel::checkForErrors(QDBusPendingReply<void> reply) const
{
    reply.waitForFinished();
    if (reply.isError()) {
Laurent Montel's avatar
Laurent Montel committed
402
403
        qCDebug(USER_MANAGER_LOG) << reply.error().name();
        qCDebug(USER_MANAGER_LOG) << reply.error().message();
404
405
406
407
408
        return true;
    }

    return false;
}
Àlex Fiestas's avatar
Àlex Fiestas committed
409

410
411
QVariant AccountModel::headerData(int section, Qt::Orientation orientation, int role) const
{
Àlex Fiestas's avatar
Àlex Fiestas committed
412
    Q_UNUSED(section);
413
414
415
416
417
418
419
420
421
422
423
    if (role != Qt::DisplayRole) {
        return QVariant();
    }

    if (orientation == Qt::Vertical) {
        return QVariant();
    }

    return i18n("Users");
}

424
void AccountModel::UserAdded(const QDBusObjectPath& dbusPath)
425
{
426
    QString path = dbusPath.path();
427
    if (m_userPath.contains(path)) {
Laurent Montel's avatar
Laurent Montel committed
428
        qCDebug(USER_MANAGER_LOG) << "We already have:" << path;
429
430
431
        return;
    }

432
    Account* acc = new Account(QStringLiteral("org.freedesktop.Accounts"), path, QDBusConnection::systemBus(), this);
433
434
435
    if (acc->systemAccount()) {
        return;
    }
Laurent Montel's avatar
Laurent Montel committed
436
    connect(acc, &OrgFreedesktopAccountsUserInterface::Changed, this, &AccountModel::Changed);
437

438
    // First, we modify "new-user" to become the new created user
439
    int row = rowCount();
440
    replaceAccount(path, acc, row - 1);
441
442
    QModelIndex changedIndex = index(row - 1, 0);
    emit dataChanged(changedIndex, changedIndex);
443

444
    // Then we add new-user again.
445
    beginInsertRows(QModelIndex(), row, row);
446
    addAccountToCache(QStringLiteral("new-user"), nullptr);
447
    endInsertRows();
448
449
450
451
}

void AccountModel::UserDeleted(const QDBusObjectPath& path)
{
452
    if (!m_userPath.contains(path.path())) {
Laurent Montel's avatar
Laurent Montel committed
453
        qCDebug(USER_MANAGER_LOG) << "User Deleted but not found: " << path.path();
454
455
456
        return;
    }

457
    beginRemoveRows(QModelIndex(), m_userPath.indexOf(path.path()), m_userPath.indexOf(path.path()));
458
    removeAccount(path.path());
459
    endRemoveRows();
460
461
462
463
}

void AccountModel::Changed()
{
464
    Account* acc = qobject_cast<Account*>(sender());
465
466
467
468
    acc->path();

    QModelIndex accountIndex = index(m_userPath.indexOf(acc->path()), 0);
    Q_EMIT dataChanged(accountIndex, accountIndex);
469
470
}

471
void AccountModel::userLogged(uint uid, bool logged)
472
473
{
    QString path = accountPathForUid(uid);
474
475
476
    int row = m_userPath.indexOf(path);

    setData(index(row), logged, Logged);
477
478
479
480
481
482
483
484
485
486
487
488
}

const QString AccountModel::accountPathForUid(uint uid) const
{
    QHash<QString, Account*>::ConstIterator i;
    for (i = m_users.constBegin(); i != m_users.constEnd(); ++i) {
        if (i.value() && i.value()->uid() == uid) {
            return i.key();
        }
    }

    return QString();
489
490
491
492
493
494
495
496
497
498
499
500
501
}

QString AccountModel::cryptPassword(const QString& password) const
{
    QString cryptedPassword;
    QByteArray alpha = "0123456789ABCDEFGHIJKLMNOPQRSTUVXYZ"
                       "abcdefghijklmnopqrstuvxyz./";
    QByteArray salt("$6$");//sha512
    int len = alpha.count();
    for(int i = 0; i < 16; i++){
        salt.append(alpha.at((qrand() % len)));
    }

502
    return QString::fromUtf8(crypt(password.toUtf8().constData(), salt.constData()));
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
}

QDebug operator<<(QDebug debug, AccountModel::Role role)
{
    switch(role) {
        case AccountModel::FriendlyName:
            debug << "AccountModel::FriendlyName";
            break;
        case AccountModel::Face:
            debug << "AccountModel::Face";
            break;
        case AccountModel::RealName:
            debug << "AccountModel::RealName";
            break;
        case AccountModel::Username:
            debug << "AccountModel::Username";
            break;
        case AccountModel::Password:
            debug << "AccountModel::Password";
            break;
        case AccountModel::Email:
            debug << "AccountModel::Email";
            break;
        case AccountModel::Administrator:
            debug << "AccountModel::Administrator";
            break;
        case AccountModel::AutomaticLogin:
            debug << "AccountModel::AutomaticLogin";
            break;
        case AccountModel::Logged:
            debug << "AccountModel::Logged";
            break;
        case AccountModel::Created:
Mario Fux's avatar
Mario Fux committed
536
            debug << "AccountModel::Created";
537
538
539
            break;
    }
    return debug;
Vishesh Handa's avatar
Vishesh Handa committed
540
}
541

542
543
544
545
void AccountModel::setDpr(qreal dpr) {
    m_dpr = dpr;
}

546