-
Notifications
You must be signed in to change notification settings - Fork 40
Expand file tree
/
Copy pathAuthDialog.cpp
More file actions
456 lines (391 loc) · 14.6 KB
/
Copy pathAuthDialog.cpp
File metadata and controls
456 lines (391 loc) · 14.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
// SPDX-FileCopyrightText: 2017 - 2026 UnionTech Software Technology Co., Ltd.
//
// SPDX-License-Identifier: GPL-3.0-or-later
#include "AuthDialog.h"
#include "usersmanager.h"
#include <QPainter>
#include <QDesktopServices>
#include <QVBoxLayout>
#include <QUrl>
#include <QAbstractButton>
#include <QButtonGroup>
#include <QDateTime>
#include <QSettings>
#include <DIcon>
#include <DGuiApplicationHelper>
#include <libintl.h>
#include <dde-shell/dlayershellwindow.h>
DWIDGET_USE_NAMESPACE
AuthDialog::AuthDialog(const QString &message,
const QString &iconName)
: DDialog(message, QString(), nullptr)
, m_message(message)
, m_iconName(iconName)
, m_adminsCombo(new QComboBox(this))
, m_passwordInput(new DPasswordEdit(this))
, m_numTries(0)
, m_lockLimitTryNum(getLockLimitTryNum())
, m_unlockTimer(new QTimer(this))
, m_authStatus(AuthStatus::None)
{
initUI();
m_unlockTimer->setSingleShot(true);
connect(m_unlockTimer, &QTimer::timeout, this, &AuthDialog::onUnlockTimeout);
setlocale(LC_ALL, "");
qDebug() << "lock limit: " << m_lockLimitTryNum;
// 始终显示用户名 (bug:9145,降低用户理解成本)
connect(m_adminsCombo, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, &AuthDialog::on_userCB_currentIndexChanged);
}
AuthDialog::~AuthDialog()
{
}
void AuthDialog::setError(const QString &error, bool alertImmediately)
{
//由于无法获取到dgetText的临时方案
QString dgetText = "";
if ("Finger moved too fast, please do not lift until prompted" == error) {
dgetText = tr("Finger moved too fast, please do not lift until prompted");
} else if ("Verification failed, 2 chances left" == error) {
dgetText = tr("Verification failed, two chances left");
} else {
dgetText = QString(dgettext("deepin-authentication", error.toUtf8()));
}
m_errorMsg = dgetText;
if (alertImmediately)
m_passwordInput->showAlertMessage(dgetText);
}
void AuthDialog::setAuthInfo(const QString &info)
{
if ("Password" == info)
m_passwordInput->lineEdit()->setFocus();
m_passwordInput->lineEdit()->setPlaceholderText(QString(dgettext("deepin-authentication", info.toStdString().c_str())));
setButtonText(1, tr("Confirm", "button"));
getButton(1)->setAccessibleName("Confirm");
update();
}
void AuthDialog::addOptions(QButtonGroup *bg)
{
QList<QAbstractButton *> btns = bg->buttons();
if (btns.length() > 0) {
addSpacing(10);
}
for (QAbstractButton *btn : btns) {
addContent(btn);
}
}
bool AuthDialog::hasSecurityHighLever(QString userName)
{
bool re = false;
QDBusInterface securityEnhance("com.deepin.daemon.SecurityEnhance",
"/com/deepin/daemon/SecurityEnhance",
"com.deepin.daemon.SecurityEnhance",
QDBusConnection::systemBus());
QDBusReply<QString> reply = securityEnhance.call("GetSEUserByName", userName);
if(reply.isValid()){
QString value = reply.value();
re = (value == "sysadm_u");
}
return re;
}
bool AuthDialog::hasOpenSecurity()
{
bool hasOpen = false;
QDBusInterface securityEnhance("com.deepin.daemon.SecurityEnhance",
"/com/deepin/daemon/SecurityEnhance",
"com.deepin.daemon.SecurityEnhance",
QDBusConnection::systemBus());
QDBusReply<QString> reply = securityEnhance.call("Status");
if(reply.isValid()){
QString value = reply.value();
hasOpen = (value == "open");
}
return hasOpen;
}
void AuthDialog::createUserCB(const PolkitQt1::Identity::List &identities)
{
// Clears the combobox in the case some user be added
m_adminsCombo->clear();
bool isOpen = hasOpenSecurity();
// For each user
foreach (const PolkitQt1::Identity &identity, identities) {
if (!identity.isValid()) {
continue;
}
// appends the user item
QString username = identity.toString().remove("unix-user:");
QString fullname = UsersManager::instance()->getFullName(username);
QString displayName = fullname.isEmpty() ? username : fullname;
if (passwordIsExpired(identity))
displayName += QString("(%1)").arg(tr("Expired"));
if (isOpen) {
if (hasSecurityHighLever(username) && identities.count() > 1) {
m_adminsCombo->clear();
if (username == qgetenv("USER"))
m_adminsCombo->insertItem(0, displayName, identity.toString());
else
m_adminsCombo->addItem(displayName, identity.toString());
break;
}
}
if (username == qgetenv("USER"))
m_adminsCombo->insertItem(0, displayName, identity.toString());
else
m_adminsCombo->addItem(displayName, identity.toString());
}
if (m_adminsCombo->count() > 0) {
m_adminsCombo->setCurrentIndex(0); // select the current user.
} else {
qWarning() << "ERROR, no valid user";
}
m_adminsCombo->show();
}
// 判断用户密码是否在有效期内
bool AuthDialog::passwordIsExpired(PolkitQt1::Identity identity)
{
QDBusInterface accounts("org.deepin.dde.Accounts1", "/org/deepin/dde/Accounts1", "org.deepin.dde.Accounts1", QDBusConnection::systemBus());
QDBusReply<QString> reply = accounts.call("FindUserById", QString::number(identity.toUnixUserIdentity().uid()));
if (reply.isValid()) {
const QString path = reply.value();
if (!path.isEmpty()) {
QDBusInterface accounts_user("org.deepin.dde.Accounts1", path, "org.deepin.dde.Accounts1.User", QDBusConnection::systemBus());
QDBusReply<bool> expiredReply = accounts_user.call("IsPasswordExpired");
if (expiredReply.isValid())
return expiredReply.value();
}
}
return false;
}
PolkitQt1::Identity AuthDialog::selectedAdminUser() const
{
if (m_adminsCombo->currentIndex() == -1)
return PolkitQt1::Identity();
const QString &id = m_adminsCombo->currentData().toString();
if (id.isEmpty())
return PolkitQt1::Identity();
return PolkitQt1::Identity::fromString(id);
}
int AuthDialog::getLockLimitTryNum()
{
const QString path = "/var/lib/dde-session-shell/dde-session-shell.conf";
int count = 5;
QFile file(path);
if (!file.exists()) {
return count;
}
QSettings settings(path, QSettings::IniFormat);
settings.beginGroup("LockTime");
count = settings.value("lockLimitTryNum").toInt();
settings.endGroup();
return count;
}
void AuthDialog::on_userCB_currentIndexChanged(int /*index*/)
{
PolkitQt1::Identity identity = selectedAdminUser();
// 清除上一个用户已经输入的密码
m_passwordInput->clear();
m_passwordInput->setAlert(false);
m_passwordInput->lineEdit()->setPlaceholderText("");
m_errorMsg = "";
m_numTries = 0;
m_unlockTimer->stop();
// itemData is Null when "Select user" is selected
if (!identity.isValid()) {
// 清理警告信息
m_passwordInput->setEnabled(false);
} else {
// 如果密码已过期
if (passwordIsExpired(identity)) {
m_passwordInput->setEnabled(false);
m_passwordInput->lineEdit()->setPlaceholderText(tr("Unavailable"));
// 密码过期不会执行到验证失败的逻辑,需要立即弹出提醒
setError(tr("The password of this user has expired. Please authenticate using another user account or change the password and try again."), true);
} else {
// 清理警告信息
m_passwordInput->setEnabled(true);
m_passwordInput->hideAlertMessage();
// We need this to restart the auth with the new user
emit adminUserSelected(identity);
// git password label focus
m_passwordInput->lineEdit()->setFocus();
}
}
}
QString AuthDialog::password() const
{
return m_passwordInput->text();
}
void AuthDialog::lock()
{
m_passwordInput->setEnabled(false);
getButton(1)->setEnabled(false);
}
void AuthDialog::unlock()
{
m_unlockTimer->stop();
m_passwordInput->setEnabled(true);
m_passwordInput->setAlert(false);
m_passwordInput->hideAlertMessage();
m_passwordInput->lineEdit()->setPlaceholderText("");
m_errorMsg = "";
m_passwordInput->lineEdit()->setFocus();
const bool enable = (m_authStatus != Authenticating
&& m_authStatus != None
&& !m_passwordInput->text().isEmpty());
getButton(1)->setEnabled(enable);
}
void AuthDialog::setLockedState(const QString &unlockTime)
{
lock();
// 清空已输入的密码,清除残留提示
m_passwordInput->clear();
m_passwordInput->setAlert(false);
m_passwordInput->hideAlertMessage();
// 保留 DA 已下发的错误文本,仅在没有时使用 fallback
if (m_errorMsg.isEmpty()) {
setError(tr("Locked, please try again later"));
}
// alert 弹窗使用 m_errorMsg(与 master 一致,可能含 DA 下发的分钟数)
m_passwordInput->showAlertMessage(m_errorMsg);
m_passwordInput->setAlert(true);
// placeholder 使用固定通用文案,不显示分钟数
m_passwordInput->lineEdit()->setPlaceholderText(tr("Locked, please try again later"));
if (unlockTime.isEmpty()) {
return;
}
const QDateTime unlockDt = QDateTime::fromString(unlockTime, Qt::ISODateWithMs);
if (!unlockDt.isValid()) {
return;
}
// 单次定时器:剩余锁定时长到期后触发一次,由 listener 重新查询 DA 确认是否真正解锁;
// 若仍锁定,listener 会再次调用 setLockedState 重新计算剩余时间并重启定时器
qint64 remainingMs = QDateTime::currentDateTime().msecsTo(unlockDt);
if (remainingMs < 1000) {
// 已到期或即将到期,尽快触发重新查询
remainingMs = 1000;
}
m_unlockTimer->start(static_cast<int>(remainingMs));
}
void AuthDialog::onUnlockTimeout()
{
emit unlockTimeout();
}
void AuthDialog::authenticationFailure(bool &isLock, const QString &unlockTime)
{
m_numTries++;
if (!isLock) {
// 不存在DA的情况,由次数来判定是否锁定
if (m_lockLimitTryNum <= m_numTries) {
isLock = true;
}
}
if (isLock) {
// 锁定场景:unlockTime 由 DA 的 GetLimits 提供(DA 自身已读取 lockWaitTime 配置换算)
setLockedState(unlockTime);
activateWindow();
return;
}
// 非锁定场景:显示错误提示并允许继续输入
if (m_errorMsg.isEmpty()) {
// 专业版错误信息现在由DA提供,考虑没有DA的版本,保留以前由agent提供错误的方案
qDebug() << "authentication failed, error message is empty, set error message by agent.";
setError(tr("Wrong password"));
}
m_passwordInput->setEnabled(true);
m_passwordInput->showAlertMessage(m_errorMsg);
m_passwordInput->setAlert(true);
m_passwordInput->lineEdit()->setFocus();
m_passwordInput->lineEdit()->selectAll();
const bool enable = (m_authStatus != Authenticating
&& m_authStatus != None
&& !m_passwordInput->text().isEmpty());
getButton(1)->setEnabled(enable);
activateWindow();
}
bool AuthDialog::event(QEvent *event)
{
if (event->type() == QEvent::Enter) {
activateWindow();
m_passwordInput->setFocus();
}
return DDialog::event(event);
}
void AuthDialog::initUI()
{
if (Dtk::Gui::DGuiApplicationHelper::testAttribute(Dtk::Gui::DGuiApplicationHelper::IsWaylandPlatform)) {
// create window
winId();
auto wnd = windowHandle();
if (wnd) {
auto layerShellWnd = ds::DLayerShellWindow::get(wnd);
layerShellWnd->setLayer(ds::DLayerShellWindow::LayerOverlay);
layerShellWnd->setKeyboardInteractivity(ds::DLayerShellWindow::KeyboardInteractivityOnDemand);
layerShellWnd->setScreenConfiguration(ds::DLayerShellWindow::ScreenFromCompositor);
} else {
qWarning() << "WindowHandle is null!";
}
} else {
setWindowFlags(windowFlags() | Qt::WindowStaysOnTopHint | Qt::Tool);
setWindowFlag(Qt::BypassWindowManagerHint, true);
}
setMinimumWidth(380);
setOnButtonClickedClose(false);
// 设置图标
QPixmap icon;
const qreal dpr = devicePixelRatioF();
if (!m_iconName.isEmpty() && QIcon::hasThemeIcon(m_iconName)) {
icon = QIcon::fromTheme(m_iconName).pixmap(static_cast<int>(48 * dpr), static_cast<int>(48 * dpr));
} else {
icon = Dtk::Gui::DIcon::loadNxPixmap(":/images/default.svg");
}
icon.setDevicePixelRatio(dpr);
setIcon(icon);
// 禁用剪切、复制
m_passwordInput->setCopyEnabled(false);
m_passwordInput->setCutEnabled(false);
int cancelId = addButton(tr("Cancel", "button"));
int confirmId = addButton(tr("Confirm", "button"), true, ButtonType::ButtonRecommend);
setDefaultButton(1);
getButton(confirmId)->setEnabled(false);
getButton(cancelId)->setAccessibleName("Cancel");
getButton(confirmId)->setAccessibleName("Confirm");
m_passwordInput->setAccessibleName("PasswordInput");
m_adminsCombo->setAccessibleName("AdminUsers");
m_adminsCombo->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
m_adminsCombo->hide();
m_passwordInput->setEchoMode(QLineEdit::Password);
addSpacing(10);
addContent(m_adminsCombo);
addSpacing(6);
addContent(m_passwordInput);
connect(this, &AuthDialog::buttonClicked, [this](int index, QString) {
switch (index) {
case 0:
emit rejected();
break;
case 1: {
emit accepted();
break;
}
default:;
}
});
connect(m_passwordInput, &DPasswordEdit::textChanged, [ = ](const QString & text) {
getButton(confirmId)->setEnabled(Authenticating != m_authStatus && None != m_authStatus && text.length() > 0);
if (text.length() > 0) {
m_passwordInput->setAlert(false);
m_errorMsg = "";
}
});
}
void AuthDialog::setInAuth(AuthStatus authStatus)
{
m_authStatus = authStatus;
// 锁定期间不恢复按钮可用状态,由 unlock() 负责恢复
if (m_unlockTimer->isActive()) {
return;
}
const bool enable = (authStatus != Authenticating
&& authStatus != None
&& !m_passwordInput->text().isEmpty());
getButton(1)->setEnabled(enable);
}