| 1 | // For license of this file, see <project-root-folder>/LICENSE.md. |
| 2 | |
| 3 | //////////////////////////////////////////////////////////////////////////////// |
| 4 | |
| 5 | // // |
| 6 | // This file is part of QOAuth2. // |
| 7 | // Copyright (c) 2014 Jacob Dawid <[email protected]> // |
| 8 | // // |
| 9 | // QOAuth2 is free software: you can redistribute it and/or modify // |
| 10 | // it under the terms of the GNU Affero General Public License as // |
| 11 | // published by the Free Software Foundation, either version 3 of the // |
| 12 | // License, or (at your option) any later version. // |
| 13 | // // |
| 14 | // QOAuth2 is distributed in the hope that it will be useful, // |
| 15 | // but WITHOUT ANY WARRANTY; without even the implied warranty of // |
| 16 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // |
| 17 | // GNU Affero General Public License for more details. // |
| 18 | // // |
| 19 | // You should have received a copy of the GNU Affero General Public // |
| 20 | // License along with QOAuth2. // |
| 21 | // If not, see <http://www.gnu.org/licenses/>. // |
| 22 | // // |
| 23 | //////////////////////////////////////////////////////////////////////////////// |
| 24 | |
| 25 | #include "network-web/oauth2service.h" |
| 26 | |
| 27 | #include "definitions/definitions.h" |
| 28 | #include "miscellaneous/application.h" |
| 29 | #include "network-web/networkfactory.h" |
| 30 | #include "network-web/oauthhttphandler.h" |
| 31 | #include "network-web/webfactory.h" |
| 32 | |
| 33 | #include <cstdlib> |
| 34 | #include <utility> |
| 35 | |
| 36 | #include <QDebug> |
| 37 | #include <QJsonDocument> |
| 38 | #include <QJsonObject> |
| 39 | #include <QNetworkReply> |
| 40 | #include <QNetworkRequest> |
| 41 | #include <QRandomGenerator> |
| 42 | |
| 43 | OAuth2Service::OAuth2Service(const QString& auth_url, |
| 44 | const QString& token_url, |
| 45 | const QString& client_id, |
| 46 | const QString& client_secret, |
| 47 | const QString& scope, |
| 48 | QObject* parent) |
| 49 | : QObject(parent), m_id(QString::number(QRandomGenerator::global()->generate())), m_timerId(-1), |
| 50 | m_redirectionHandler(new OAuthHttpHandler(tr("You can close this window now. Go back to %1.").arg(QSL(APP_NAME)), |
| 51 | this)), |
| 52 | m_functorOnLogin(std::function<void()>()) { |
| 53 | m_tokenGrantType = QSL("authorization_code"); |
| 54 | m_tokenUrl = QUrl(token_url); |
| 55 | m_authUrl = auth_url; |
| 56 | |
| 57 | m_clientId = client_id; |
| 58 | m_clientSecret = client_secret; |
| 59 | m_clientSecretId = m_clientSecretSecret = QString(); |
| 60 | m_scope = scope; |
| 61 | m_useHttpBasicAuthWithClientData = false; |
| 62 | |
| 63 | connect(&m_networkManager, &QNetworkAccessManager::finished, this, &OAuth2Service::tokenRequestFinished); |
| 64 | connect(m_redirectionHandler, &OAuthHttpHandler::authGranted, [this](const QString& auth_code, const QString& id) { |
| 65 | if (id.isEmpty() || id == m_id) { |
| 66 | // We process this further only if handler (static singleton) responded to our original request. |
| 67 | retrieveAccessToken(auth_code); |
| 68 | } |
| 69 | }); |
| 70 | connect(m_redirectionHandler, |
| 71 | &OAuthHttpHandler::authRejected, |
| 72 | [this](const QString& error_description, const QString& id) { |
| 73 | Q_UNUSED(error_description) |
| 74 | |
| 75 | if (id.isEmpty() || id == m_id) { |
| 76 | // We process this further only if handler (static singleton) responded to our original request. |
| 77 | emit authFailed(); |
| 78 | } |
| 79 | }); |
| 80 | } |
| 81 | |
| 82 | OAuth2Service::~OAuth2Service() { |
| 83 | qDebugNN << LOGSEC_OAUTH << "Destroying OAuth2Service instance."; |
| 84 | } |
| 85 | |
| 86 | QString OAuth2Service::bearer() { |
| 87 | if (!isFullyLoggedIn()) { |
| 88 | qApp->showGuiMessage(Notification::Event::LoginFailure, |
| 89 | {tr("You have to login first"), |
| 90 | tr("Click here to login."), |
| 91 | QSystemTrayIcon::MessageIcon::Critical}, |
| 92 | {}, |
| 93 | {tr("Login"), [this]() { |
| 94 | login(); |
| 95 | }}); |
| 96 | return {}; |
| 97 | } |
| 98 | else { |
| 99 | return QSL("Bearer %1").arg(accessToken()); |
| 100 | } |
| 101 | } |
| 102 | |
| 103 | bool OAuth2Service::isFullyLoggedIn() const { |
| 104 | bool is_expiration_valid = tokensExpireIn() > QDateTime::currentDateTime(); |
| 105 | bool do_tokens_exist = !refreshToken().isEmpty() && !accessToken().isEmpty(); |
| 106 | |
| 107 | return is_expiration_valid && do_tokens_exist; |
| 108 | } |
| 109 | |
| 110 | void OAuth2Service::setOAuthTokenGrantType(QString grant_type) { |
| 111 | m_tokenGrantType = std::move(grant_type); |
| 112 | } |
| 113 | |
| 114 | QString OAuth2Service::oAuthTokenGrantType() { |
| 115 | return m_tokenGrantType; |
| 116 | } |
| 117 | |
| 118 | void OAuth2Service::timerEvent(QTimerEvent* event) { |
| 119 | if (m_timerId >= 0 && event->timerId() == m_timerId) { |
| 120 | event->accept(); |
| 121 | |
| 122 | QDateTime window_about_expire = tokensExpireIn().addSecs(-60 * 15); |
| 123 | |
| 124 | if (window_about_expire < QDateTime::currentDateTime()) { |
| 125 | // We try to refresh access token, because it probably expires soon. |
| 126 | qDebugNN << LOGSEC_OAUTH << "Refreshing automatically access token."; |
| 127 | refreshAccessToken(); |
| 128 | } |
| 129 | else { |
| 130 | qDebugNN << LOGSEC_OAUTH << "Access token is not expired yet."; |
| 131 | } |
| 132 | } |
| 133 | |
| 134 | QObject::timerEvent(event); |
| 135 | } |
| 136 | |
| 137 | bool OAuth2Service::useHttpBasicAuthWithClientData() const { |
| 138 | return m_useHttpBasicAuthWithClientData; |
| 139 | } |
| 140 | |
| 141 | void OAuth2Service::setUseHttpBasicAuthWithClientData(bool use_auth) { |
| 142 | m_useHttpBasicAuthWithClientData = use_auth; |
| 143 | } |
| 144 | |
| 145 | QString OAuth2Service::clientSecretSecret() const { |
| 146 | return m_clientSecretSecret; |
| 147 | } |
| 148 | |
| 149 | void OAuth2Service::setClientSecretSecret(const QString& client_secret_secret) { |
| 150 | m_clientSecretSecret = client_secret_secret; |
| 151 | } |
| 152 | |
| 153 | QString OAuth2Service::clientSecretId() const { |
| 154 | return m_clientSecretId; |
| 155 | } |
| 156 | |
| 157 | void OAuth2Service::setClientSecretId(const QString& client_secret_id) { |
| 158 | m_clientSecretId = client_secret_id; |
| 159 | } |
| 160 | |
| 161 | QString OAuth2Service::id() const { |
| 162 | return m_id; |
| 163 | } |
| 164 | |
| 165 | void OAuth2Service::setId(const QString& id) { |
| 166 | m_id = id; |
| 167 | } |
| 168 | |
| 169 | void OAuth2Service::retrieveAccessToken(const QString& auth_code) { |
| 170 | QNetworkRequest network_request; |
| 171 | |
| 172 | network_request.setUrl(m_tokenUrl); |
| 173 | network_request.setHeader(QNetworkRequest::KnownHeaders::ContentTypeHeader, "application/x-www-form-urlencoded"); |
| 174 | |
| 175 | if (m_useHttpBasicAuthWithClientData) { |
| 176 | auto basic_auth = NetworkFactory::generateBasicAuthHeader(NetworkFactory::NetworkAuthentication::Basic, |
| 177 | properClientId(), |
| 178 | properClientSecret()); |
| 179 | |
| 180 | network_request.setRawHeader(basic_auth.first, basic_auth.second); |
| 181 | } |
| 182 | |
| 183 | QString content = QString("client_id=%1&" |
| 184 | "client_secret=%2&" |
| 185 | "code=%3&" |
| 186 | "redirect_uri=%5&" |
| 187 | "grant_type=%4") |
| 188 | .arg(properClientId(), |
| 189 | properClientSecret(), |
| 190 | auth_code, |
| 191 | m_tokenGrantType, |
| 192 | m_redirectionHandler->listenAddressPort()); |
| 193 | |
| 194 | qDebugNN << LOGSEC_OAUTH << "Posting data for access token retrieval:" << QUOTE_W_SPACE_DOT(content); |
| 195 | m_networkManager.post(network_request, content.toUtf8()); |
| 196 | } |
| 197 | |
| 198 | void OAuth2Service::refreshAccessToken(const QString& refresh_token) { |
| 199 | auto real_refresh_token = refresh_token.isEmpty() ? refreshToken() : refresh_token; |
| 200 | QNetworkRequest network_request; |
| 201 | |
| 202 | network_request.setUrl(m_tokenUrl); |
| 203 | network_request.setHeader(QNetworkRequest::KnownHeaders::ContentTypeHeader, "application/x-www-form-urlencoded"); |
| 204 | |
| 205 | if (m_useHttpBasicAuthWithClientData) { |
| 206 | auto basic_auth = NetworkFactory::generateBasicAuthHeader(NetworkFactory::NetworkAuthentication::Basic, |
| 207 | properClientId(), |
| 208 | properClientSecret()); |
| 209 | |
| 210 | network_request.setRawHeader(basic_auth.first, basic_auth.second); |
| 211 | } |
| 212 | |
| 213 | QString content = QString("client_id=%1&" |
| 214 | "client_secret=%2&" |
| 215 | "refresh_token=%3&" |
| 216 | "grant_type=%4") |
| 217 | .arg(properClientId(), properClientSecret(), real_refresh_token, QSL("refresh_token")); |
| 218 | |
| 219 | qApp->showGuiMessage(Notification::Event::LoginDataRefreshed, |
| 220 | {tr("Logging in via OAuth 2.0..."), |
| 221 | tr("Refreshing login tokens for '%1'...").arg(m_tokenUrl.toString()), |
| 222 | QSystemTrayIcon::MessageIcon::Information}, |
| 223 | {true, false, true}); |
| 224 | |
| 225 | qDebugNN << LOGSEC_OAUTH << "Posting data for access token refreshing:" << QUOTE_W_SPACE_DOT(content); |
| 226 | m_networkManager.post(network_request, content.toUtf8()); |
| 227 | } |
| 228 | |
| 229 | void OAuth2Service::tokenRequestFinished(QNetworkReply* network_reply) { |
| 230 | QByteArray repl = network_reply->readAll(); |
| 231 | QJsonDocument json_document = QJsonDocument::fromJson(repl); |
| 232 | QJsonObject root_obj = json_document.object(); |
| 233 | |
| 234 | qDebugNN << LOGSEC_OAUTH << "Token response:" << QUOTE_W_SPACE_DOT(QString::fromUtf8(json_document.toJson())); |
| 235 | |
| 236 | if (network_reply->error() != QNetworkReply::NetworkError::NoError) { |
| 237 | qWarningNN << LOGSEC_OAUTH |
| 238 | << "Network error when obtaining token response:" << QUOTE_W_SPACE_DOT(network_reply->error()); |
| 239 | |
| 240 | emit tokensRetrieveError(QString(), NetworkFactory::networkErrorText(network_reply->error())); |
| 241 | } |
| 242 | else if (root_obj.keys().contains(QSL("error"))) { |
| 243 | QString error = root_obj.value(QSL("error")).toString(); |
| 244 | QString error_description = root_obj.value(QSL("error_description")).toString(); |
| 245 | |
| 246 | qWarningNN << LOGSEC_OAUTH << "JSON error when obtaining token response:" << QUOTE_W_SPACE(error) |
| 247 | << QUOTE_W_SPACE_DOT(error_description); |
| 248 | |
| 249 | logout(); |
| 250 | |
| 251 | emit tokensRetrieveError(error, error_description); |
| 252 | } |
| 253 | else { |
| 254 | int expires = root_obj.value(QL1S("expires_in")).toInt(); |
| 255 | |
| 256 | setTokensExpireIn(QDateTime::currentDateTime().addSecs(expires)); |
| 257 | setAccessToken(root_obj.value(QL1S("access_token")).toString()); |
| 258 | |
| 259 | const QString refresh_token = root_obj.value(QL1S("refresh_token")).toString(); |
| 260 | |
| 261 | if (!refresh_token.isEmpty()) { |
| 262 | setRefreshToken(refresh_token); |
| 263 | } |
| 264 | |
| 265 | qDebugNN << LOGSEC_OAUTH << "Obtained refresh token" << QUOTE_W_SPACE(refreshToken()) << "- expires on date/time" |
| 266 | << QUOTE_W_SPACE_DOT(tokensExpireIn()); |
| 267 | |
| 268 | if (m_functorOnLogin != nullptr) { |
| 269 | qDebugNN << LOGSEC_OAUTH << "Running custom after-login code."; |
| 270 | |
| 271 | m_functorOnLogin(); |
| 272 | } |
| 273 | |
| 274 | emit tokensRetrieved(accessToken(), refreshToken(), expires); |
| 275 | } |
| 276 | |
| 277 | network_reply->deleteLater(); |
| 278 | } |
| 279 | |
| 280 | QString OAuth2Service::properClientId() const { |
| 281 | return m_clientId.simplified().isEmpty() ? m_clientSecretId : m_clientId; |
| 282 | } |
| 283 | |
| 284 | QString OAuth2Service::properClientSecret() const { |
| 285 | return m_clientSecret.simplified().isEmpty() ? m_clientSecretSecret : m_clientSecret; |
| 286 | } |
| 287 | |
| 288 | QString OAuth2Service::accessToken() const { |
| 289 | return m_accessToken; |
| 290 | } |
| 291 | |
| 292 | void OAuth2Service::setAccessToken(const QString& access_token) { |
| 293 | m_accessToken = access_token; |
| 294 | } |
| 295 | |
| 296 | QDateTime OAuth2Service::tokensExpireIn() const { |
| 297 | return m_tokensExpireIn; |
| 298 | } |
| 299 | |
| 300 | void OAuth2Service::setTokensExpireIn(const QDateTime& tokens_expire_in) { |
| 301 | m_tokensExpireIn = tokens_expire_in; |
| 302 | } |
| 303 | |
| 304 | QString OAuth2Service::clientSecret() const { |
| 305 | return m_clientSecret; |
| 306 | } |
| 307 | |
| 308 | void OAuth2Service::setClientSecret(const QString& client_secret) { |
| 309 | m_clientSecret = client_secret; |
| 310 | } |
| 311 | |
| 312 | QString OAuth2Service::clientId() const { |
| 313 | return m_clientId; |
| 314 | } |
| 315 | |
| 316 | void OAuth2Service::setClientId(const QString& client_id) { |
| 317 | m_clientId = client_id; |
| 318 | } |
| 319 | |
| 320 | QString OAuth2Service::redirectUrl() const { |
| 321 | return m_redirectionHandler->listenAddressPort(); |
| 322 | } |
| 323 | |
| 324 | void OAuth2Service::setRedirectUrl(const QString& redirect_url, bool start_handler) { |
| 325 | m_redirectionHandler->setListenAddressPort(redirect_url, start_handler); |
| 326 | } |
| 327 | |
| 328 | QString OAuth2Service::refreshToken() const { |
| 329 | return m_refreshToken; |
| 330 | } |
| 331 | |
| 332 | void OAuth2Service::setRefreshToken(const QString& refresh_token) { |
| 333 | killRefreshTimer(); |
| 334 | m_refreshToken = refresh_token; |
| 335 | startRefreshTimer(); |
| 336 | } |
| 337 | |
| 338 | bool OAuth2Service::login(const std::function<void()>& functor_when_logged_in) { |
| 339 | m_functorOnLogin = functor_when_logged_in; |
| 340 | |
| 341 | if (!m_redirectionHandler->isListening()) { |
| 342 | qCriticalNN << LOGSEC_OAUTH << "Cannot log-in because OAuth redirection handler is not listening."; |
| 343 | |
| 344 | emit tokensRetrieveError(QString(), |
| 345 | tr("Failed to start OAuth " |
| 346 | "redirection listener. Maybe your " |
| 347 | "rights are not high enough.")); |
| 348 | |
| 349 | return false; |
| 350 | } |
| 351 | |
| 352 | bool did_token_expire = tokensExpireIn().isNull() || tokensExpireIn() < QDateTime::currentDateTime().addSecs(-120); |
| 353 | bool does_token_exist = !refreshToken().isEmpty(); |
| 354 | |
| 355 | // We refresh current tokens only if: |
| 356 | // 1. We have some existing refresh token. |
| 357 | // AND |
| 358 | // 2. We do not know its expiration date or it passed. |
| 359 | if (does_token_exist && did_token_expire) { |
| 360 | refreshAccessToken(); |
| 361 | return false; |
| 362 | } |
| 363 | else if (!does_token_exist) { |
| 364 | retrieveAuthCode(); |
| 365 | return false; |
| 366 | } |
| 367 | else { |
| 368 | functor_when_logged_in(); |
| 369 | return true; |
| 370 | } |
| 371 | } |
| 372 | |
| 373 | void OAuth2Service::logout(bool stop_redirection_handler) { |
| 374 | setTokensExpireIn(QDateTime()); |
| 375 | setAccessToken(QString()); |
| 376 | setRefreshToken(QString()); |
| 377 | |
| 378 | qDebugNN << LOGSEC_OAUTH << "Clearing tokens."; |
| 379 | |
| 380 | if (stop_redirection_handler) { |
| 381 | m_redirectionHandler->stop(); |
| 382 | } |
| 383 | } |
| 384 | |
| 385 | void OAuth2Service::startRefreshTimer() { |
| 386 | if (!refreshToken().isEmpty()) { |
| 387 | m_timerId = startTimer(1000 * 60 * 15, Qt::TimerType::VeryCoarseTimer); |
| 388 | } |
| 389 | } |
| 390 | |
| 391 | void OAuth2Service::killRefreshTimer() { |
| 392 | if (m_timerId > 0) { |
| 393 | killTimer(m_timerId); |
| 394 | } |
| 395 | } |
| 396 | |
| 397 | void OAuth2Service::retrieveAuthCode() { |
| 398 | QString auth_url = m_authUrl + QString("?client_id=%1&" |
| 399 | "scope=%2&" |
| 400 | "redirect_uri=%3&" |
| 401 | "response_type=code&" |
| 402 | "state=%4&" |
| 403 | "prompt=consent&" |
| 404 | "duration=permanent&" |
| 405 | "access_type=offline") |
| 406 | .arg(properClientId(), m_scope, m_redirectionHandler->listenAddressPort(), m_id); |
| 407 | |
| 408 | // We run login URL in external browser, response is caught by light HTTP server. |
| 409 | qApp->web()->openUrlInExternalBrowser(auth_url); |
| 410 | } |