summaryrefslogtreecommitdiffstats
path: root/src/oauth/qabstractoauth.cpp
blob: 53262928acd484f576a0ab02dfd8a612368da0fb (plain)
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
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
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
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
/****************************************************************************
**
** Copyright (C) 2017 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the Qt Network Auth module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:GPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 or (at your option) any later version
** approved by the KDE Free Qt Foundation. The licenses are as published by
** the Free Software Foundation and appearing in the file LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/

#ifndef QT_NO_HTTP

#include <qabstractoauth.h>
#include <qabstractoauthreplyhandler.h>

#include <private/qabstractoauth_p.h>

#include <QtCore/qurl.h>
#include <QtCore/qpair.h>
#include <QtCore/qstring.h>
#include <QtCore/qdatetime.h>
#include <QtCore/qurlquery.h>
#include <QtCore/qjsondocument.h>
#include <QtCore/qmessageauthenticationcode.h>

#include <QtNetwork/qnetworkrequest.h>
#include <QtNetwork/qnetworkaccessmanager.h>

#include <random>

Q_DECLARE_METATYPE(QAbstractOAuth::Error)

QT_BEGIN_NAMESPACE

/*!
    \class QAbstractOAuth
    \inmodule QtNetworkAuth
    \ingroup oauth
    \brief The QAbstractOAuth class is the base of all
    implementations of OAuth authentication methods.
    \since 5.8

    The class defines the basic interface of the OAuth
    authentication classes. By inheriting this class, you
    can create custom authentication methods for different web
    services.

    It also contains some functions to ease the process of
    implementing different authentication flows.
*/

/*!
    \enum QAbstractOAuth::Status

    Indicates the current authentication status.

    \value NotAuthenticated                 No token has been
    retrieved.

    \value TemporaryCredentialsReceived     Temporary credentials
    have been received, this status is used in some OAuth
    authetication methods.

    \value Granted                          Token credentials have
    been received and authenticated calls are allowed.

    \value RefreshingToken                  New token credentials
    have been requested.
*/

/*!
    \enum QAbstractOAuth::Stage

    Identifies an authentication stage.  It's passed to a
    ModifyParametersFunction so that it can make different changes to
    parameters at each call to it during the process of
    authentication.

    \value RequestingTemporaryCredentials   Preparing the temporary
    credentials request.

    \value RequestingAuthorization          Preparing the
    authorization grant URL.

    \value RequestingAccessToken            Preparing the token
    request.

    \value RefreshingAccessToken            Preparing the access
    token refresh.
*/

/*!
    \enum QAbstractOAuth::Error

    Indicates the latest received error.

    \value NoError                          No error has ocurred.

    \value NetworkError                     Failed to connect to the server.

    \value ServerError                      The server answered the
    request with an error.

    \value OAuthTokenNotFoundError          The server's response to
    a token request provided no token identifier.

    \value OAuthTokenSecretNotFoundError    The server's response to
    a token request provided no token secret.

    \value OAuthCallbackNotVerified         The authorization server
    has not verified the supplied callback URI in the request. This
    usually happens when the provided callback does not match with
    the callback supplied during client registration.
*/

/*!
    \enum QAbstractOAuth::ContentType

    Indicates the MIME Content-Type of the POST methods in
    authenticated calls.

    \value WwwFormUrlEncoded                Uses
    application/x-www-form-urlencoded format.

    \value Json                             Uses
    application/json format.
*/

/*!
    \property QAbstractOAuth::status
    \brief This property holds the current authentication status.
*/

/*!
    \property QAbstractOAuth::extraTokens
    \brief This property holds the extra tokens received from the
    server.
*/

/*!
    \property QAbstractOAuth::authorizationUrl
    \brief This property holds the URL used to request the Resource
    Owner Authorization as described in:
    \l{https://tools.ietf.org/html/rfc5849#section-2.2}{The OAuth
    1.0 Protocol: Resource Owner Authorization}
*/

/*!
    \property QAbstractOAuth::contentType
    \brief The Content-Type to use when sending authorization
    parameters.

    This property controls how parameters are formatted when sent
    with a POST request.  A suitable header is also added.
*/

/*!
    \fn void QAbstractOAuth::authorizeWithBrowser(const QUrl &url)

    This signal is emitted when the \a url generated by
    resourceOwnerAuthorization() is ready to be used in the web
    browser to allow the application to impersonate the user.
    \sa resourceOwnerAuthorization()
*/

/*!
    \fn void QAbstractOAuth::granted()

    This signal is emitted when the authorization flow finishes
    successfully.
*/

/*!
    \fn QNetworkReply *QAbstractOAuth::head(const QUrl &url, const QVariantMap &parameters)

    Sends an authenticated HEAD request and returns a new
    QNetworkReply. The \a url and \a parameters are used to create
    the request.

    \b {See also}: \l {https://tools.ietf.org/html/rfc2616#section-9.4}
    {Hypertext Transfer Protocol -- HTTP/1.1: HEAD}
*/

/*!
    \fn QNetworkReply *QAbstractOAuth::get(const QUrl &url, const QVariantMap &parameters)

    Sends an authenticated GET request and returns a new
    QNetworkReply. The \a url and \a parameters are used to create
    the request.

    \b {See also}: \l {https://tools.ietf.org/html/rfc2616#section-9.3}
    {Hypertext Transfer Protocol -- HTTP/1.1: GET}
*/

/*!
    \fn QNetworkReply *QAbstractOAuth::post(const QUrl &url, const QVariantMap &parameters)

    Sends an authenticated POST request and returns a new
    QNetworkReply. The \a url and \a parameters are used to create
    the request.

    \b {See also}: \l {https://tools.ietf.org/html/rfc2616#section-9.5}
    {Hypertext Transfer Protocol -- HTTP/1.1: POST}
*/

/*!
    \fn QNetworkReply *QAbstractOAuth::put(const QUrl &url, const QVariantMap &parameters)

    Sends an authenticated PUT request and returns a new
    QNetworkReply. The \a url and \a parameters are used to create
    the request.

    \b {See also}: \l {https://tools.ietf.org/html/rfc2616#section-9.6}
    {Hypertext Transfer Protocol -- HTTP/1.1: PUT}
*/

/*!
    \fn QNetworkReply *QAbstractOAuth::deleteResource(const QUrl &url, const QVariantMap &parameters)

    Sends an authenticated DELETE request and returns a new
    QNetworkReply. The \a url and \a parameters are used to create
    the request.

    \b {See also}: \l {https://tools.ietf.org/html/rfc2616#section-9.7}
    {Hypertext Transfer Protocol -- HTTP/1.1: DELETE}
*/

/*!
    \fn void QAbstractOAuth::grant()

    Override this function to implement the corresponding
    authentication flow in the subclasses. Client code calls this
    function to start the authentication workflow. This may require
    user interaction: for example, asking the user's authorization
    via a web browser. When the authentication succeeds, it should
    emit granted(); this gives notice that credentials are ready to
    be used in authenticated calls.
*/

QAbstractOAuthPrivate::QAbstractOAuthPrivate(const char *loggingCategory,
                                             const QUrl &authorizationUrl,
                                             const QString &clientIdentifier,
                                             QNetworkAccessManager *manager) :
    loggingCategory(loggingCategory),
    clientIdentifier(clientIdentifier),
    authorizationUrl(authorizationUrl),
    defaultReplyHandler(new QOAuthOobReplyHandler),
    networkAccessManagerPointer(manager)
{}

QAbstractOAuthPrivate::~QAbstractOAuthPrivate()
{}

QNetworkAccessManager *QAbstractOAuthPrivate::networkAccessManager()
{
    Q_Q(QAbstractOAuth);
    if (!networkAccessManagerPointer)
        networkAccessManagerPointer = new QNetworkAccessManager(q);
    return networkAccessManagerPointer.data();
}

void QAbstractOAuthPrivate::setStatus(QAbstractOAuth::Status newStatus)
{
    Q_Q(QAbstractOAuth);
    if (status != newStatus) {
        status = newStatus;
        Q_EMIT q->statusChanged(status);
        if (status == QAbstractOAuth::Status::Granted)
            Q_EMIT q->granted();
    }
}

QByteArray QAbstractOAuthPrivate::generateRandomString(quint8 length)
{
    const char characters[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    static std::mt19937 randomEngine(QDateTime::currentDateTime().toMSecsSinceEpoch());
    std::uniform_int_distribution<int> distribution(0, sizeof(characters) - 2);
    QByteArray data;
    data.reserve(length);
    for (quint8 i = 0; i < length; ++i)
        data.append(characters[distribution(randomEngine)]);
    return data;
}

QByteArray QAbstractOAuthPrivate::convertParameters(const QVariantMap &parameters)
{
    QByteArray data;
    switch (contentType) {
    case QAbstractOAuth::ContentType::Json:
        data = QJsonDocument::fromVariant(QVariant(parameters)).toJson();
        break;
    case QAbstractOAuth::ContentType::WwwFormUrlEncoded: {
        QUrlQuery query;
        for (auto it = parameters.begin(), end = parameters.end(); it != end; ++it)
            query.addQueryItem(it.key(), it->toString());
        data = query.toString(QUrl::FullyEncoded).toUtf8();
        break;
    }
    }
    return data;
}

void QAbstractOAuthPrivate::addContentTypeHeaders(QNetworkRequest *request)
{
    Q_ASSERT(request);

    switch (contentType) {
    case QAbstractOAuth::ContentType::WwwFormUrlEncoded:
        request->setHeader(QNetworkRequest::ContentTypeHeader,
                           QStringLiteral("application/x-www-form-urlencoded"));
        break;
    case QAbstractOAuth::ContentType::Json:
        request->setHeader(QNetworkRequest::ContentTypeHeader,
                           QStringLiteral("application/json"));
        break;
    }
}

QUrlQuery QAbstractOAuthPrivate::createQuery(const QVariantMap &parameters)
{
    QUrlQuery query;
    for (auto it = parameters.begin(), end = parameters.end(); it != end; ++it)
        query.addQueryItem(it.key(), it.value().toString());
    return query;
}

QAbstractOAuth::QAbstractOAuth(QAbstractOAuthPrivate &dd, QObject *parent)
    : QObject(dd, parent)
{
    qRegisterMetaType<QAbstractOAuth::Error>();
}

/*!
    Destroys the abstract OAuth.
*/
QAbstractOAuth::~QAbstractOAuth()
{}

/*!
    Returns the current client identifier used in the authentication
    process.

    \sa setClientIdentifier()
*/
QString QAbstractOAuth::clientIdentifier() const
{
    Q_D(const QAbstractOAuth);
    return d->clientIdentifier;
}

/*!
    Sets the current client identifier to \a clientIdentifier.

    \sa clientIdentifier()
*/
void QAbstractOAuth::setClientIdentifier(const QString &clientIdentifier)
{
    Q_D(QAbstractOAuth);
    if (d->clientIdentifier != clientIdentifier) {
        d->clientIdentifier = clientIdentifier;
        Q_EMIT clientIdentifierChanged(clientIdentifier);
    }
}

/*!
    Returns the token used to sign the authenticated requests.

    \sa setToken()
*/
QString QAbstractOAuth::token() const
{
    Q_D(const QAbstractOAuth);
    return d->token;
}

/*!
    Sets the token used to sign authenticated requests to \a token.

    \sa token()
*/
void QAbstractOAuth::setToken(const QString &token)
{
    Q_D(QAbstractOAuth);
    if (d->token != token) {
        d->token = token;
        Q_EMIT tokenChanged(token);
    }
}

/*!
    Returns the current network access manager used to send the
    requests to the server during authentication flows or to make
    authentication calls.

    \sa setNetworkAccessManager(), QNetworkAccessManager
*/
QNetworkAccessManager *QAbstractOAuth::networkAccessManager() const
{
    Q_D(const QAbstractOAuth);
    return d->networkAccessManagerPointer.data();
}

/*!
    Sets the network manager to \a networkAccessManager.
    QAbstractOAuth does not take ownership of
    \a networkAccessManager. If no custom network access manager is
    set, an internal network access manager is used.
    This network access manager will be used
    to make the request to the authentication server and the
    authenticated request to the web service.

    \sa networkAccessManager(), QNetworkAccessManager
*/
void QAbstractOAuth::setNetworkAccessManager(QNetworkAccessManager *networkAccessManager)
{
    Q_D(QAbstractOAuth);
    if (networkAccessManager != d->networkAccessManagerPointer) {
        if (d->networkAccessManagerPointer && d->networkAccessManagerPointer->parent() == this)
            delete d->networkAccessManagerPointer.data();
        d->networkAccessManagerPointer = networkAccessManager;
    }
}

/*!
    Returns the current authentication status.
    \sa Status
*/
QAbstractOAuth::Status QAbstractOAuth::status() const
{
    Q_D(const QAbstractOAuth);
    return d->status;
}

/*!
    Returns the authorization request URL.
    \sa setAuthorizationUrl()
*/
QUrl QAbstractOAuth::authorizationUrl() const
{
    Q_D(const QAbstractOAuth);
    return d->authorizationUrl;
}

/*!
    Sets the authorization request URL to \a url. This address
    will be used to allow the user to grant the application the
    ability to make authenticated calls on behalf of the user.
    \sa authorizationUrl()
*/
void QAbstractOAuth::setAuthorizationUrl(const QUrl &url)
{
    Q_D(QAbstractOAuth);
    if (d->authorizationUrl != url) {
        d->authorizationUrl = url;
        Q_EMIT authorizationUrlChanged(url);
    }
}

/*!
    Sets the current status to \a status. This method is for use
    by classes based on QAbstractOAuth.
    \sa status()
*/
void QAbstractOAuth::setStatus(QAbstractOAuth::Status status)
{
    Q_D(QAbstractOAuth);
    if (status != d->status) {
        d->status = status;
        Q_EMIT statusChanged(status);
    }
}

/*!
    Returns the reply handler currently in use.
    \sa setReplyHandler(), QAbstractOAuthReplyHandler
*/
QAbstractOAuthReplyHandler *QAbstractOAuth::replyHandler() const
{
    Q_D(const QAbstractOAuth);
    return d->replyHandler ? d->replyHandler.data() : d->defaultReplyHandler.data();
}

/*!
    Sets the current reply handler to \a handler.
    \note Does not take ownership of \a handler.
*/
void QAbstractOAuth::setReplyHandler(QAbstractOAuthReplyHandler *handler)
{
    Q_D(QAbstractOAuth);
    d->replyHandler = handler;
}

/*!
    Returns the current parameter-modification function.
    \sa ModifyParametersFunction, setModifyParametersFunction(), Stage
*/
QAbstractOAuth::ModifyParametersFunction QAbstractOAuth::modifyParametersFunction() const
{
    Q_D(const QAbstractOAuth);
    return d->modifyParametersFunction;
}

/*!
    Sets the parameter-modification function \a modifyParametersFunction.
    This function is used to customize the parameters sent to the server
    during a specified authorization stage. The number of calls to this
    function depends on the flow used during the authentication.
    \sa modifyParametersFunction(), ModifyParametersFunction, Stage
*/
void QAbstractOAuth::setModifyParametersFunction(
        const QAbstractOAuth::ModifyParametersFunction &modifyParametersFunction)
{
    Q_D(QAbstractOAuth);
    d->modifyParametersFunction = modifyParametersFunction;
}

/*!
    Returns the current Content-Type used in authenticated calls.
    \sa setContentType(), post()
*/
QAbstractOAuth::ContentType QAbstractOAuth::contentType() const
{
    Q_D(const QAbstractOAuth);
    return d->contentType;
}

/*!
    Sets the current Content-Type to \a contentType.
*/
void QAbstractOAuth::setContentType(QAbstractOAuth::ContentType contentType)
{
    Q_D(QAbstractOAuth);
    if (d->contentType != contentType) {
        d->contentType = contentType;
        Q_EMIT contentTypeChanged(contentType);
    }
}

/*!
    Returns the extra tokens received from the server during
    authentication.
    \sa extraTokensChanged()
*/
QVariantMap QAbstractOAuth::extraTokens() const
{
    Q_D(const QAbstractOAuth);
    return d->extraTokens;
}

/*!
    Returns the current callback string corresponding to the
    current reply handler. The returned string is the string
    sent to the server to specify the callback URI, or the word
    identifying the alternative method in headless devices.
    \sa replyHandler(), setReplyHandler()
*/
QString QAbstractOAuth::callback() const
{
    Q_D(const QAbstractOAuth);
    return d->replyHandler ? d->replyHandler->callback()
                           : d->defaultReplyHandler->callback();
}

/*!
    Builds the resource owner authorization URL to be used in the web
    browser: \a url is used as the base URL and the query is created
    using \a parameters. When the URL is ready, the
    authorizeWithBrowser() signal will be emitted with the generated
    URL.
    \sa authorizeWithBrowser()
*/
void QAbstractOAuth::resourceOwnerAuthorization(const QUrl &url, const QVariantMap &parameters)
{
    QUrl u = url;
    u.setQuery(QAbstractOAuthPrivate::createQuery(parameters));
    Q_EMIT authorizeWithBrowser(u);
}

/*!
    Generates a random string which could be used as state or nonce.
    The parameter \a length determines the size of the generated
    string.

    \b {See also}: \l {https://tools.ietf.org/html/rfc5849#section-3.3}{The
    OAuth 1.0 Protocol: Nonce and Timestamp}.
*/
QByteArray QAbstractOAuth::generateRandomString(quint8 length)
{
    return QAbstractOAuthPrivate::generateRandomString(length);
}

QT_END_NAMESPACE

#endif // QT_NO_HTTP