File indexing completed on 2024-12-01 04:48:03

0001 /*
0002     This file is part of oxaccess.
0003 
0004     SPDX-FileCopyrightText: 2009 Tobias Koenig <tokoe@kde.org>
0005 
0006     SPDX-License-Identifier: LGPL-2.0-or-later
0007 */
0008 
0009 #include "connectiontestjob.h"
0010 
0011 #include <KIO/Job>
0012 #include <KIO/StoredTransferJob>
0013 
0014 #include <QJsonDocument>
0015 #include <QJsonObject>
0016 #include <QUrl>
0017 
0018 using namespace OXA;
0019 
0020 ConnectionTestJob::ConnectionTestJob(const QString &url, const QString &user, const QString &password, QObject *parent)
0021     : KJob(parent)
0022     , mUrl(url)
0023     , mUser(user)
0024     , mPassword(password)
0025 {
0026 }
0027 
0028 void ConnectionTestJob::start()
0029 {
0030     if (!mUrl.startsWith(QLatin1StringView("https://"))) {
0031         mUrl = QLatin1StringView("https://") + mUrl;
0032     }
0033     const QUrl url(mUrl + QStringLiteral("/ajax/login?action=login&name=%1&password=%2").arg(mUser, mPassword));
0034 
0035     KJob *job = KIO::storedGet(url, KIO::Reload, KIO::HideProgressInfo);
0036     connect(job, &KJob::result, this, &ConnectionTestJob::httpJobFinished);
0037 }
0038 
0039 void ConnectionTestJob::httpJobFinished(KJob *job)
0040 {
0041     if (job->error()) {
0042         setError(job->error());
0043         setErrorText(job->errorText());
0044         emitResult();
0045         return;
0046     }
0047 
0048     auto transferJob = qobject_cast<KIO::StoredTransferJob *>(job);
0049     Q_ASSERT(transferJob);
0050 
0051     const QJsonObject data = QJsonDocument::fromJson(transferJob->data()).object();
0052 
0053     // on success data contains something like: {"session":"e530578bca504aa89738fadde9e44b3d","random":"ac9090d2cc284fed926fa3c7e316c43b"}
0054     // on failure data contains something like: {"category":1,"error_params":[],"error":"Invalid credentials.","error_id":"-1529642166-37","code":"LGI-0006"}
0055     if (data.contains(QLatin1StringView("error"))) {
0056         const QString errorText = data[QStringLiteral("error")].toString();
0057 
0058         setError(UserDefinedError);
0059         setErrorText(errorText);
0060         emitResult();
0061         return;
0062     } else { // success case
0063         const QString sessionId = data[QStringLiteral("session")].toString();
0064 
0065         // logout correctly...
0066         const QUrl url(mUrl + QStringLiteral("/ajax/login?action=logout&session=%1").arg(sessionId));
0067         KIO::storedGet(url, KIO::Reload, KIO::HideProgressInfo);
0068     }
0069 
0070     emitResult();
0071 }
0072 
0073 #include "moc_connectiontestjob.cpp"