Remove kQOAuth from MuseScore dependencies

This commit is contained in:
Dmitri Ovodok 2019-11-07 15:37:47 +02:00
parent 85f3641835
commit ebce1c3c61
23 changed files with 1 additions and 3535 deletions

View file

@ -740,7 +740,7 @@ endif (NOT MSVC)
subdirs(
awl bww2mxml share midi audiofile fluid libmscore synthesizer
effects thirdparty/rtf2html thirdparty/beatroot
thirdparty/qzip thirdparty/kQOAuth
thirdparty/qzip
)
if (BUILD_CRASH_REPORTER)

View file

@ -523,7 +523,6 @@ target_link_libraries(mscore
libmscore
qzip
beatroot
kqoauth
)
if (BUILD_CRASH_REPORTER)

View file

@ -13,7 +13,6 @@
#include "musescore.h"
#include "logindialog.h"
#include "network/loginmanager.h"
#include "kQOAuth/kqoauthrequest_xauth.h"
namespace Ms {

View file

@ -15,8 +15,6 @@
#include "musescore.h"
#include "libmscore/score.h"
#include "preferences.h"
#include "kQOAuth/kqoauthrequest.h"
#include "kQOAuth/kqoauthrequest_xauth.h"
#ifdef USE_WEBENGINE
#include <QWebEngineCookieStore>
@ -295,28 +293,6 @@ QString LoginManager::getErrorString(QNetworkReply* reply, const QJsonObject& ob
return QString("%1 (%2)").arg(err).arg(msg);
}
//---------------------------------------------------------
// onAuthorizedRequestDone
//---------------------------------------------------------
#if 0
void LoginManager::onAuthorizedRequestDone()
{
if (_oauthManager->lastError() == KQOAuthManager::NetworkError)
QMessageBox::critical(0, tr("Network error"), tr("Please check your Internet connection"));
else if (_oauthManager->lastError() == KQOAuthManager::ContentOperationNotPermittedError)
QMessageBox::critical(0, tr("Please upgrade"), tr("Your MuseScore version is too old to use this feature.\n"
"%1Please upgrade first%2.")
.arg("<a href=\"https://musescore.org\">")
.arg("</a>")
.replace("\n", "<br/>"));
// don't do that, it will logout user if score is private and already known
//else if (_oauthManager->lastError() == KQOAuthManager::RequestUnauthorized){
// logout();
// mscore->showLoginDialog();
// }
}
#endif
/*------- TRY LOGIN ROUTINES ----------------------------*/
/* Try to get user information, if error, */
/* display login form until quit or successful login */
@ -498,71 +474,6 @@ void LoginManager::onLoginRefreshReply(QNetworkReply* reply, int code, const QJs
save();
}
//---------------------------------------------------------
// onAccessTokenReceived
//---------------------------------------------------------
#if 0
void LoginManager::onAccessTokenReceived(QString token, QString tokenSecret)
{
//qDebug() << "Access token received: " << token << tokenSecret;
_accessToken = token;
_accessTokenSecret = tokenSecret;
disconnect(_oauthManager, SIGNAL(requestReady(QByteArray)), this, SLOT(onAccessTokenRequestReady(QByteArray)));
emit loginSuccess();
}
#endif
//---------------------------------------------------------
// onAccessTokenRequestReady
//---------------------------------------------------------
#if 0
void LoginManager::onAccessTokenRequestReady(QByteArray ba)
{
//qDebug() << "onAccessTokenRequestReady" << ba;
if (_oauthManager->lastError() == KQOAuthManager::RequestUnauthorized) { // 401/406
QJsonDocument jsonResponse = QJsonDocument::fromJson(ba);
QJsonArray array = jsonResponse.array();
QString message = tr("Unsuccessful login. Please try again.");
if (array.size() > 0) {
QJsonObject o = array.at(0).toObject();
if (o.value("code") != QJsonValue::Undefined) {
QString code = o["code"].toString();
if (code == "USER_AUTHENTICATION_FAILED") {
message = tr("Sorry, wrong email address, username or password. Please check again. %1Have you forgotten your password%2?")
.arg("<a href=\"https://musescore.com/user/password\">")
.arg("</a>");
}
else if (code == "USER_DENIED") {
message = tr("This account has been blocked.");
}
else if (code == "USER_NOT_ACTIVATED") {
message = tr("Your account has not been activated yet. Please check your mailbox to activate your account or %1request a new activation email%2.")
.arg("<a href=\"https://musescore.com/user/resendregistrationpassword\">")
.arg("</a>");
}
else if (code == "USER_TIMESTAMP_EXPIRED") {
message = tr("The local time on your device is not set right. Please check it and adjust. It's advised to set the time/timezone to automatic. If you still can't log in, %1contact us%2.")
.arg("<a href=\"https://musescore.com/contact?category=Login%20problems\">")
.arg("</a>");
}
}
}
emit loginError(message);
}
else if (_oauthManager->lastError() == KQOAuthManager::NetworkError) {
QMessageBox::critical(0, tr("Network error"), tr("Please check your Internet connection"));
}
else if (_oauthManager->lastError() == KQOAuthManager::ContentOperationNotPermittedError) {
QMessageBox::critical(0, tr("Please upgrade"), tr("Your MuseScore version is too old to use this feature.\n"
"%1Please upgrade first%2.")
.arg("<a href=\"https://musescore.org\">")
.arg("</a>")
.replace("\n", "<br/>"));
}
}
#endif
//---------------------------------------------------------
// getUser
//---------------------------------------------------------
@ -709,70 +620,8 @@ void LoginManager::onGetMediaUrlReply(QNetworkReply* reply, int code, const QJso
}
else // TODO: handle request error properly
qWarning("%s", getErrorString(reply, response).toUtf8().constData());
#if 0
disconnect(_oauthManager, SIGNAL(requestReady(QByteArray)),
this, SLOT(onGetMediaUrlRequestReady(QByteArray)));
QJsonDocument jsonResponse = QJsonDocument::fromJson(ba);
QJsonObject response = jsonResponse.object();
QJsonValue urlValue = response.value("url");
if (urlValue.isString()) {
_mediaUrl = response.value("url").toString();
QString mp3Path = QDir::tempPath() + QString("/temp_%1.mp3").arg(qrand() % 100000);
_mp3File = new QFile(mp3Path);
Score* score = mscore->currentScore()->masterScore();
int br = preferences.getInt(PREF_EXPORT_MP3_BITRATE);
preferences.setPreference(PREF_EXPORT_MP3_BITRATE, 128);
if (mscore->saveMp3(score, mp3Path)) { // no else, error handling is done in saveMp3
_uploadTryCount = 0;
uploadMedia();
}
preferences.setPreference(PREF_EXPORT_MP3_BITRATE, br);
}
#endif
}
//---------------------------------------------------------
// onGetUserRequestReady
//---------------------------------------------------------
#if 0
void LoginManager::onGetScoreRequestReady(QByteArray ba)
{
//qDebug() << "onGetScoreRequestReady" << ba;
//qDebug() << _oauthManager->lastError();
disconnect(_oauthManager, SIGNAL(requestReady(QByteArray)),
this, SLOT(onGetScoreRequestReady(QByteArray)));
if (_oauthManager->lastError() == KQOAuthManager::NoError) {
QJsonDocument jsonResponse = QJsonDocument::fromJson(ba);
QJsonObject score = jsonResponse.object();
if (score.value("user") != QJsonValue::Undefined) {
QJsonObject user = score.value("user").toObject();
QString title = score.value("title").toString();
QString description = score.value("description").toString();
QString sharing = score.value("sharing").toString();
QString license = score.value("license").toString();
QString tags = score.value("tags").toString();
QString url = score.value("custom_url").toString();
if (user.value("uid") != QJsonValue::Undefined) {
int uid = user.value("uid").toString().toInt();
if (uid == _uid)
emit getScoreSuccess(title, description, (sharing == "private"), license, tags, url);
else
emit getScoreError("");
}
else {
emit getScoreError("");
}
}
else {
emit getScoreError("");
}
}
else {
emit getScoreError("");
}
}
#endif
//---------------------------------------------------------
// uploadMedia
//---------------------------------------------------------
@ -855,10 +704,6 @@ void LoginManager::mediaUploadProgress(qint64 progress, qint64 total)
void LoginManager::upload(const QString& path, int nid, const QString& title)
{
qDebug() << "file upload" << nid;
// KQOAuthRequest *oauthRequest = new KQOAuthRequest(this);
// QUrl url(QString("https://%1/services/rest/score.json").arg(MUSESCORE_HOST));
// if (nid > 0)
// url = QUrl(QString("https://%1/services/rest/score/%2/update.json").arg(MUSESCORE_HOST).arg(nid));
ApiRequest* r = new ApiRequest(this);
r->setPath("/score/upload-light")

View file

@ -1,69 +0,0 @@
#=============================================================================
# MusE
# Linux Music Editor
#
# Copyright (C) 2010 by Werner Schweer and others
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2.
#
# 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., 675 Mass Ave, Cambridge, MA 02139, USA.
#=============================================================================
include (${PROJECT_SOURCE_DIR}/build/gch.cmake)
if (APPLE)
file(GLOB_RECURSE INCS "*.h")
else (APPLE)
set(INCS "")
endif (APPLE)
if (NOT MSVC)
set(_all_h_file "${PROJECT_BINARY_DIR}/all.h")
else (NOT MSVC)
set(_all_h_file "${PROJECT_SOURCE_DIR}/all.h")
endif (NOT MSVC)
add_library(kqoauth STATIC
kqoauthauthreplyserver.cpp
kqoauthrequest.cpp
kqoauthrequest_xauth.cpp
kqoauthmanager.cpp
kqoauthutils.cpp
${_all_h_file}
${PCH}
${INCS}
)
if (NOT MSVC)
set_target_properties (
kqoauth
PROPERTIES
COMPILE_FLAGS "${PCH_INCLUDE} -I ${PROJECT_SOURCE_DIR}/thirdparty/openssl/include -g -Wall -Wextra -Winvalid-pch"
)
else (NOT MSVC)
set_target_properties (
kqoauth
PROPERTIES
COMPILE_FLAGS "${PCH_INCLUDE} /I${PROJECT_SOURCE_DIR}/thirdparty/openssl/include"
)
endif (NOT MSVC)
xcode_pch(kqoauth all)
# Use MSVC pre-compiled headers
vstudio_pch( kqoauth )
# MSVC does not depend on mops1 & mops2 for PCH
if (NOT MSVC)
ADD_DEPENDENCIES(kqoauth mops1)
ADD_DEPENDENCIES(kqoauth mops2)
endif (NOT MSVC)

View file

@ -1,502 +0,0 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 2.1, February 1999
Copyright (C) 1991, 1999 Free Software Foundation, Inc.
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
[This is the first released version of the Lesser GPL. It also counts
as the successor of the GNU Library Public License, version 2, hence
the version number 2.1.]
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
Licenses are intended to guarantee your freedom to share and change
free software--to make sure the software is free for all its users.
This license, the Lesser General Public License, applies to some
specially designated software packages--typically libraries--of the
Free Software Foundation and other authors who decide to use it. You
can use it too, but we suggest you first think carefully about whether
this license or the ordinary General Public License is the better
strategy to use in any particular case, based on the explanations below.
When we speak of free software, we are referring to freedom of use,
not price. Our General Public Licenses are designed to make sure that
you have the freedom to distribute copies of free software (and charge
for this service if you wish); that you receive source code or can get
it if you want it; that you can change the software and use pieces of
it in new free programs; and that you are informed that you can do
these things.
To protect your rights, we need to make restrictions that forbid
distributors to deny you these rights or to ask you to surrender these
rights. These restrictions translate to certain responsibilities for
you if you distribute copies of the library or if you modify it.
For example, if you distribute copies of the library, whether gratis
or for a fee, you must give the recipients all the rights that we gave
you. You must make sure that they, too, receive or can get the source
code. If you link other code with the library, you must provide
complete object files to the recipients, so that they can relink them
with the library after making changes to the library and recompiling
it. And you must show them these terms so they know their rights.
We protect your rights with a two-step method: (1) we copyright the
library, and (2) we offer you this license, which gives you legal
permission to copy, distribute and/or modify the library.
To protect each distributor, we want to make it very clear that
there is no warranty for the free library. Also, if the library is
modified by someone else and passed on, the recipients should know
that what they have is not the original version, so that the original
author's reputation will not be affected by problems that might be
introduced by others.
Finally, software patents pose a constant threat to the existence of
any free program. We wish to make sure that a company cannot
effectively restrict the users of a free program by obtaining a
restrictive license from a patent holder. Therefore, we insist that
any patent license obtained for a version of the library must be
consistent with the full freedom of use specified in this license.
Most GNU software, including some libraries, is covered by the
ordinary GNU General Public License. This license, the GNU Lesser
General Public License, applies to certain designated libraries, and
is quite different from the ordinary General Public License. We use
this license for certain libraries in order to permit linking those
libraries into non-free programs.
When a program is linked with a library, whether statically or using
a shared library, the combination of the two is legally speaking a
combined work, a derivative of the original library. The ordinary
General Public License therefore permits such linking only if the
entire combination fits its criteria of freedom. The Lesser General
Public License permits more lax criteria for linking other code with
the library.
We call this license the "Lesser" General Public License because it
does Less to protect the user's freedom than the ordinary General
Public License. It also provides other free software developers Less
of an advantage over competing non-free programs. These disadvantages
are the reason we use the ordinary General Public License for many
libraries. However, the Lesser license provides advantages in certain
special circumstances.
For example, on rare occasions, there may be a special need to
encourage the widest possible use of a certain library, so that it becomes
a de-facto standard. To achieve this, non-free programs must be
allowed to use the library. A more frequent case is that a free
library does the same job as widely used non-free libraries. In this
case, there is little to gain by limiting the free library to free
software only, so we use the Lesser General Public License.
In other cases, permission to use a particular library in non-free
programs enables a greater number of people to use a large body of
free software. For example, permission to use the GNU C Library in
non-free programs enables many more people to use the whole GNU
operating system, as well as its variant, the GNU/Linux operating
system.
Although the Lesser General Public License is Less protective of the
users' freedom, it does ensure that the user of a program that is
linked with the Library has the freedom and the wherewithal to run
that program using a modified version of the Library.
The precise terms and conditions for copying, distribution and
modification follow. Pay close attention to the difference between a
"work based on the library" and a "work that uses the library". The
former contains code derived from the library, whereas the latter must
be combined with the library in order to run.
GNU LESSER GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License Agreement applies to any software library or other
program which contains a notice placed by the copyright holder or
other authorized party saying it may be distributed under the terms of
this Lesser General Public License (also called "this License").
Each licensee is addressed as "you".
A "library" means a collection of software functions and/or data
prepared so as to be conveniently linked with application programs
(which use some of those functions and data) to form executables.
The "Library", below, refers to any such software library or work
which has been distributed under these terms. A "work based on the
Library" means either the Library or any derivative work under
copyright law: that is to say, a work containing the Library or a
portion of it, either verbatim or with modifications and/or translated
straightforwardly into another language. (Hereinafter, translation is
included without limitation in the term "modification".)
"Source code" for a work means the preferred form of the work for
making modifications to it. For a library, complete source code means
all the source code for all modules it contains, plus any associated
interface definition files, plus the scripts used to control compilation
and installation of the library.
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running a program using the Library is not restricted, and output from
such a program is covered only if its contents constitute a work based
on the Library (independent of the use of the Library in a tool for
writing it). Whether that is true depends on what the Library does
and what the program that uses the Library does.
1. You may copy and distribute verbatim copies of the Library's
complete source code as you receive it, in any medium, provided that
you conspicuously and appropriately publish on each copy an
appropriate copyright notice and disclaimer of warranty; keep intact
all the notices that refer to this License and to the absence of any
warranty; and distribute a copy of this License along with the
Library.
You may charge a fee for the physical act of transferring a copy,
and you may at your option offer warranty protection in exchange for a
fee.
2. You may modify your copy or copies of the Library or any portion
of it, thus forming a work based on the Library, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) The modified work must itself be a software library.
b) You must cause the files modified to carry prominent notices
stating that you changed the files and the date of any change.
c) You must cause the whole of the work to be licensed at no
charge to all third parties under the terms of this License.
d) If a facility in the modified Library refers to a function or a
table of data to be supplied by an application program that uses
the facility, other than as an argument passed when the facility
is invoked, then you must make a good faith effort to ensure that,
in the event an application does not supply such function or
table, the facility still operates, and performs whatever part of
its purpose remains meaningful.
(For example, a function in a library to compute square roots has
a purpose that is entirely well-defined independent of the
application. Therefore, Subsection 2d requires that any
application-supplied function or table used by this function must
be optional: if the application does not supply it, the square
root function must still compute square roots.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Library,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Library, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote
it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Library.
In addition, mere aggregation of another work not based on the Library
with the Library (or with a work based on the Library) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may opt to apply the terms of the ordinary GNU General Public
License instead of this License to a given copy of the Library. To do
this, you must alter all the notices that refer to this License, so
that they refer to the ordinary GNU General Public License, version 2,
instead of to this License. (If a newer version than version 2 of the
ordinary GNU General Public License has appeared, then you can specify
that version instead if you wish.) Do not make any other change in
these notices.
Once this change is made in a given copy, it is irreversible for
that copy, so the ordinary GNU General Public License applies to all
subsequent copies and derivative works made from that copy.
This option is useful when you wish to copy part of the code of
the Library into a program that is not a library.
4. You may copy and distribute the Library (or a portion or
derivative of it, under Section 2) in object code or executable form
under the terms of Sections 1 and 2 above provided that you accompany
it with the complete corresponding machine-readable source code, which
must be distributed under the terms of Sections 1 and 2 above on a
medium customarily used for software interchange.
If distribution of object code is made by offering access to copy
from a designated place, then offering equivalent access to copy the
source code from the same place satisfies the requirement to
distribute the source code, even though third parties are not
compelled to copy the source along with the object code.
5. A program that contains no derivative of any portion of the
Library, but is designed to work with the Library by being compiled or
linked with it, is called a "work that uses the Library". Such a
work, in isolation, is not a derivative work of the Library, and
therefore falls outside the scope of this License.
However, linking a "work that uses the Library" with the Library
creates an executable that is a derivative of the Library (because it
contains portions of the Library), rather than a "work that uses the
library". The executable is therefore covered by this License.
Section 6 states terms for distribution of such executables.
When a "work that uses the Library" uses material from a header file
that is part of the Library, the object code for the work may be a
derivative work of the Library even though the source code is not.
Whether this is true is especially significant if the work can be
linked without the Library, or if the work is itself a library. The
threshold for this to be true is not precisely defined by law.
If such an object file uses only numerical parameters, data
structure layouts and accessors, and small macros and small inline
functions (ten lines or less in length), then the use of the object
file is unrestricted, regardless of whether it is legally a derivative
work. (Executables containing this object code plus portions of the
Library will still fall under Section 6.)
Otherwise, if the work is a derivative of the Library, you may
distribute the object code for the work under the terms of Section 6.
Any executables containing that work also fall under Section 6,
whether or not they are linked directly with the Library itself.
6. As an exception to the Sections above, you may also combine or
link a "work that uses the Library" with the Library to produce a
work containing portions of the Library, and distribute that work
under terms of your choice, provided that the terms permit
modification of the work for the customer's own use and reverse
engineering for debugging such modifications.
You must give prominent notice with each copy of the work that the
Library is used in it and that the Library and its use are covered by
this License. You must supply a copy of this License. If the work
during execution displays copyright notices, you must include the
copyright notice for the Library among them, as well as a reference
directing the user to the copy of this License. Also, you must do one
of these things:
a) Accompany the work with the complete corresponding
machine-readable source code for the Library including whatever
changes were used in the work (which must be distributed under
Sections 1 and 2 above); and, if the work is an executable linked
with the Library, with the complete machine-readable "work that
uses the Library", as object code and/or source code, so that the
user can modify the Library and then relink to produce a modified
executable containing the modified Library. (It is understood
that the user who changes the contents of definitions files in the
Library will not necessarily be able to recompile the application
to use the modified definitions.)
b) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (1) uses at run time a
copy of the library already present on the user's computer system,
rather than copying library functions into the executable, and (2)
will operate properly with a modified version of the library, if
the user installs one, as long as the modified version is
interface-compatible with the version that the work was made with.
c) Accompany the work with a written offer, valid for at
least three years, to give the same user the materials
specified in Subsection 6a, above, for a charge no more
than the cost of performing this distribution.
d) If distribution of the work is made by offering access to copy
from a designated place, offer equivalent access to copy the above
specified materials from the same place.
e) Verify that the user has already received a copy of these
materials or that you have already sent this user a copy.
For an executable, the required form of the "work that uses the
Library" must include any data and utility programs needed for
reproducing the executable from it. However, as a special exception,
the materials to be distributed need not include anything that is
normally distributed (in either source or binary form) with the major
components (compiler, kernel, and so on) of the operating system on
which the executable runs, unless that component itself accompanies
the executable.
It may happen that this requirement contradicts the license
restrictions of other proprietary libraries that do not normally
accompany the operating system. Such a contradiction means you cannot
use both them and the Library together in an executable that you
distribute.
7. You may place library facilities that are a work based on the
Library side-by-side in a single library together with other library
facilities not covered by this License, and distribute such a combined
library, provided that the separate distribution of the work based on
the Library and of the other library facilities is otherwise
permitted, and provided that you do these two things:
a) Accompany the combined library with a copy of the same work
based on the Library, uncombined with any other library
facilities. This must be distributed under the terms of the
Sections above.
b) Give prominent notice with the combined library of the fact
that part of it is a work based on the Library, and explaining
where to find the accompanying uncombined form of the same work.
8. You may not copy, modify, sublicense, link with, or distribute
the Library except as expressly provided under this License. Any
attempt otherwise to copy, modify, sublicense, link with, or
distribute the Library is void, and will automatically terminate your
rights under this License. However, parties who have received copies,
or rights, from you under this License will not have their licenses
terminated so long as such parties remain in full compliance.
9. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Library or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Library (or any work based on the
Library), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Library or works based on it.
10. Each time you redistribute the Library (or any work based on the
Library), the recipient automatically receives a license from the
original licensor to copy, distribute, link with or modify the Library
subject to these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties with
this License.
11. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Library at all. For example, if a patent
license would not permit royalty-free redistribution of the Library by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Library.
If any portion of this section is held invalid or unenforceable under any
particular circumstance, the balance of the section is intended to apply,
and the section as a whole is intended to apply in other circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
12. If the distribution and/or use of the Library is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Library under this License may add
an explicit geographical distribution limitation excluding those countries,
so that distribution is permitted only in or among countries not thus
excluded. In such case, this License incorporates the limitation as if
written in the body of this License.
13. The Free Software Foundation may publish revised and/or new
versions of the Lesser General Public License from time to time.
Such new versions will be similar in spirit to the present version,
but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Library
specifies a version number of this License which applies to it and
"any later version", you have the option of following the terms and
conditions either of that version or of any later version published by
the Free Software Foundation. If the Library does not specify a
license version number, you may choose any version ever published by
the Free Software Foundation.
14. If you wish to incorporate parts of the Library into other free
programs whose distribution conditions are incompatible with these,
write to the author to ask for permission. For software which is
copyrighted by the Free Software Foundation, write to the Free
Software Foundation; we sometimes make exceptions for this. Our
decision will be guided by the two goals of preserving the free status
of all derivatives of our free software and of promoting the sharing
and reuse of software generally.
NO WARRANTY
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Libraries
If you develop a new library, and you want it to be of the greatest
possible use to the public, we recommend making it free software that
everyone can redistribute and change. You can do so by permitting
redistribution under these terms (or, alternatively, under the terms of the
ordinary General Public License).
To apply these terms, attach the following notices to the library. It is
safest to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least the
"copyright" line and a pointer to where the full notice is found.
<one line to give the library's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Also add information on how to contact you by electronic and paper mail.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the library, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the
library `Frob' (a library for tweaking knobs) written by James Random Hacker.
<signature of Ty Coon>, 1 April 1990
Ty Coon, President of Vice
That's all there is to it!

View file

@ -1,343 +0,0 @@
kQOAuth is a OAuth 1.0 library written for Qt in C++. The goals for the
library have been to provide easy integration to existing Qt applications
utilizing Qt signals describing the OAuth process, and to provide a
convenient approach to OAuth authentication.
kQOAuth has support for retrieving the user authorization from the service
provider's website. kQOAuth will open the user's web browser to the
authorization page, give a local URL as the callback URL and setup a HTTP
server on this address to listen for the reply from the service and then
process it.
BUILDING kQOAuth
===============================
- Make sure that you have Qt 4.7 or greater installed
For OS X and Linux:
- run "qmake"
- run "make" to build
- Run "sudo make install" to install
- To run unit tests you need to set platform specific variable to point
correct directory in order to make unit tests to find the library. Note
that it doesn't require kQOAuth to be installed in order to run unit tests.
* for Linux: export LD_LIBRARY_PATH=/path/to/kQOAuth/lib/dir
* for OS X: export DYLD_LIBRARY_PATH=/path/to/kQOAuth/lib/dir
For Windows with the Visual Studio or Windows SDK Compiler
- run "qmake CONFIG+=release"
- run "nmake" to build
- run "nmake install" to install
COMPONENTS
===============================
Below I will present the two fundamental components necessary when using
kQOAuth; KQOAuthManager and KQOAuthRequest.
KQOAuthManager
===============================
Executes OAuth requests (KQOAuthRequest), parses the replies and emits Qt
signals describing the process of the OAuth authentication.
KQOAuthManager will keep track of the state of the authorization process.
This means that the provided convenience methods can be used to achieve the
necessary steps in OAuth authentication without explicitly constructing
each request.
Methods
-------------------------------
* void executeRequest(KQOAuthRequest *request)
- request: The KQOAuthRequest to process.
Takes as parameter a pointer to a KQOAuthRequest describing the request
that will be executed. The call will return as soon as the HTTP
request has been sent.
When the service responded to this request the signal
requestReady(QByteArray) is emitted. This will contain the raw data
that the service sent back as a response to the request.
If an error in the request was detected, this method will set the
error code and emit the requestReady(QByteArray) signal with
an empty QByteArray. The error code can be retrieved by calling lastError().
* void executeAuthorizedRequest(KQOAuthRequest *request, int id)
- request: The KQOAuthRequest to process.
- id: An id that is unique to the request.
This method is useful for situations where the reponses from a server
have different processing requirements.
The arguments and behavior of this method is similar to executeRequest()
with the addition of an id that is mapped to the request. When the service
has responded, the signal authorizedRequestReady(QByteArray, int) is emitted
where the int is the mapped id.
* void setHandleUserAuthorization(bool set)
- set: A boolean value telling KQOAuthManager to process the user's
authorization to protected resources.
If KQOAuth is to handle user authorization this method must be called
with argument set as 'true' before a request for the temporary token has
been executed.
* void getUserAuthorization(QUrl authorizationEndpoint);
- authorizationEndpoint: The URL to the service provider's authorization
web page.
A convenience method to retrieve the user authorization to access the
protected resources. This method will open user's web browser to the
service providers authorization page given as argument and setup a
a local HTTP server to process the response.
This method must be called after temporaryTokenReceived(...) signal
is emitted.
When the user's authentication is processed, the signal
authorizationReceived(...) is emitted.
* void getUserAccessTokens(QUrl accessTokenEndpoint);
- accessTokenEndpoint: The URL to the service provider which is used for
retrieving the access token.
A convenience method to retrieve the access token, which is used for
accessing the protected resources.
This method must be called after the signal authorizationReceived(...)
is received.
When the access token request is processed, the signal accessTokenReceived(...)
is emitted. After this signal the protected resources can be accessed.
* void sendAuthorizedRequest(QUrl requestEndpoint,
const KQOAuthParameters &requestParameters);
- requestEndpoint: The URL to the service provider which can be used for
accessing protected resources.
- requestParameters: The parameters for this request which are service
specific. KQOAuthParameters is a typecasted
QMultiMap<QString, QString> for parameter name and value.
A convenience method for accessing the protected resources. The
parameters are given as KQOAuthParameters, which is a typecasted
QMultiMap<QString parameterName, QString parameterValue>. Please
consult your service provider for which parameters to use.
* bool hasTemporaryToken()
Returns true if the temporary token has been received. Otherwise returns
false
* bool isVerified()
Returns true if the user has successfully verified us to access the protected
resources. Otherwise returns false.
* bool isAuthorized()
Returns true if we have access tokens to access the protected resources.
Otherwise returns false.
* KQOAuthError lastError()
Returns the most recent error code in the authentication process.
Signals
-------------------------------
* void requestReady(QByteArray networkReply)
- networkReply: The response as sent from the service the each request.
This signal is emitted after each request has been processed. It will
return all the request response parameters in the QMultiMap, where
the first parameter is the name and the second parameter is the value.
* void authorizedRequestReady(QByteArray networkReply, int id);
- networkReply: The response as sent from the service the each request.
- id: The id that is mapped to the original request
This signal is emitted after each authorizedRequest has been processed.
* void receivedToken(QString oauth_token, QString oauth_token_secret)
- oauth_oken: Token value
- oauth_token_secret: Token secret value
This signal is emitted after a successful request for temporary tokens or
access tokens. The requested tokens are sent as parameters in this
signal.
* void temporaryTokenReceived(QString oauth_token, QString oauth_token_secret)
- oauth_token: Temporary token value
- oauth_token_secret: Temporary token secret value
This signal is emitted after a successful request for temporary tokens.
The tokens are sent as parameters to this signal.
* void authorizationReceived(QString oauth_token, QString oauth_verifier)
- oauth_token: The temporary token that was used when requesting access.
- oauth_verifier: The oauth_verifier token received as a reply to the
request. This value is necessary when requesting access token.
This signal is emitted after the user has concluded the authorization request
step in the service provider's website.
Note that setHandleUserAuthorization(true) must be called when requesting for
the temporary token.
* void accessTokenReceived(QString oauth_token, QString oauth_token_secret)
- oauth_token: The access token value.
- oauth_token_secret: The access token secret value.
This signal is emitted after a successful request for access tokens. The
requested tokens are sent as parameters in this signal. These tokens
are necessary when requesting for protected resources.
KQOAuthRequest
====================================
KQOAuthRequest is given to KQOAuthManager to execute the requested OAuth
request. It will also take care of parameter normalization, generating
the needed authorization header, and most importantly, generate a
OAuth signature.
Methods
------------------------------------
* void initRequest(KQOAuthRequest::RequestType type, const QUrl &requestEndpoint)
- type: Initializes this request to be of type 'KQOAuthRequest::RequestType'.
- requestEndpoint: The URL to the service provider that can handle the
requests of type 'KQOAuthRequest::RequestType'.
Initializes the request to be of a certain type that will be sent to
service provider's HTTP location. The request can be of type:
- TemporaryCredentials: Requesting the temporary credentials.
- AccessToken: Request the access tokens.
- AuthorizedRequest: When OAuth process is complete, we can access the
protected resources with this request.
* void setConsumerKey(const QString &consumerKey)
Set the consumer key to 'consumerKey'. This is given by the service provider.
* void setConsumerSecretKey(const QString &consumerSecretKey)
Set the consumer key secret to 'consumerSecretKey'. This is given by the
service provider.
* void setCallbackUrl(const QUrl &callbackUrl)
If the request type is 'KQOAuthRequest::TemporaryCredentials', then this
is the callback URL for the request. This is needed when asking user
authorization.
* void setTokenSecret(const QString &tokenSecret)
If the request type is 'KQOAuthRequest::AccessToken' then this is the
temporary token secret from the earlier request returned by the service
provider.
* void setToken(const QString &token)
If the request type is 'KQOAuthRequest::AccessToken' then this is the
temporary token from the earlier request returned by the service provider.
* void setSignatureMethod(KQOAuthRequest::RequestSignatureMethod)
Sets the signature method to be used when signing the requests.
NOTE: Currently only KQOAuthRequest::::HMAC_SHA1 is supported!
* void setHttpMethod(KQOAuthRequest::RequestHttpMethod)
Sets the HTTP method to be used for this request.
* void setAdditionalParameters(const KQOAuthParameters &additionalParams);
Sets any additional request specific parameters as specified by the
service provider.
* void setRequestBody(const KQOAuthParameters &requestParams);
Sets the request body for HTTP POST request as specified by the service
provider.
* bool isValid() const;
Returns true if this request is valid (has all the necessary parameters
required by the given request type).
* QByteArray requestBody() const;
Returns the raw request body as sent to the service provider.
* KQOAuthRequest::RequestType requestType() const;
Returns the current request type.
* QUrl requestEndpoint() const;
Returns the current request endpoint (URL location).
* void setContentType(const QString &contentType)
By default the POST requests are sent as "application/x-www-form-urlencoded".
With this method, however, the content type of the POST request can be changed.
If you want to override the content type, please look at setRawData().
* QString contentType()
Returns the current content type.
* void setRawData(const QByteArray &data);
If you send the POST request as anything else but "application/x-www-form-urlencoded"
it is assumed that you want to send some manually crafted data that kQOAuth
is not responsible of.
Set that data here.
* QByteArray rawData()
Returns the raw data you want to se send to the endpoint.
* QList<QByteArray> requestParameters();
Returns the request parameters of this request as a list of elements
sent to the service.
* void clearRequest();
Deletes all cached data from this request object.
* void setTimeout(int timeoutMilliseconds);
Sets the timeout for this request. If the timeout expires, the request will be aborted.
SOURCE CODE
============================
The source code is available on Gitorious at:
http://www.gitorious.org/kqoauth
git clone git://gitorious.org/kqoauth/kqoauth.git
EXAMPLE APPLICATION
============================
kQOAuth provides as an example application a command line Twitter client.
Currently it only supports requesting the authorization and sending status
updates, but this should be enough to show the basic usage of kQOAuth with
the convenience APIs.
See example/twittercli/ for source code.
LICENSE AND AUTHOR
============================
The library and the source code is licensed under the GNU Lesser General Public
License (LGPL). For more information, visit http://www.gnu.org/licenses/lgpl.html
This library is written by Johan Paul (johan.paul@gmail.com)
CONTRIBUTORS
============================
Keith Obenschain (obenschaink@gmail.com)
ACKNOWLEDGEMENT
============================
Thank you to Dominik Kapusta for the original Qt OAuth library, QOAuth. I wanted
to improve on this library to better suit my needs.
Visit his project at http://files.ayoy.net/qoauth/doc/
SO, WHAT'S WITH THE NAME?
============================
The library is called kQOAuth. I wanted the library to reflect the fact that it
is a Qt based library and since QOAuth was already taken, I added a 'k' in
front of it. k is for Kypeli, not KDE.

View file

@ -1,4 +0,0 @@
kQOAuth
=======
kQOAuth is a library written in C++ for Qt that implements the OAuth 1.0 authentication specification RFC 5849 (http://tools.ietf.org/html/rfc5849). Greetings go to Dominik Kapusta for writing the original OAuth library using Qt, QOAuth (http://blog.ayoy.net/2009/6/24/oauth). However, I wanted to improve on the QOAuths approach in some ways. kQOAuth main features: Easy integrated solution for retrieving user authentication and access token. No external dependency to QCA. Convenient signals that can be used for easy OAuth authorization process handling. Access to request objects that will wrap request signing and network access, but still gives possibility for detailed control of the authentication process for easier integration to existing application logic.

View file

@ -1,111 +0,0 @@
/**
* KQOAuth - An OAuth authentication library for Qt.
*
* Author: Johan Paul (johan.paul@gmail.com)
* http://www.johanpaul.com
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* KQOAuth 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with KQOAuth. If not, see <http://www.gnu.org/licenses/>.
*/
#include <QTcpSocket>
#include <QStringList>
#include <QUrl>
#if QT_VERSION >= 0x050000
#include <QUrlQuery>
#endif
#include "kqoauthauthreplyserver.h"
#include "kqoauthauthreplyserver_p.h"
KQOAuthAuthReplyServerPrivate::KQOAuthAuthReplyServerPrivate(KQOAuthAuthReplyServer *parent):
q_ptr(parent)
{
}
KQOAuthAuthReplyServerPrivate::~KQOAuthAuthReplyServerPrivate()
{
}
void KQOAuthAuthReplyServerPrivate::onIncomingConnection() {
Q_Q(KQOAuthAuthReplyServer);
socket = q->nextPendingConnection();
connect(socket, SIGNAL(readyRead()),
this, SLOT(onBytesReady()), Qt::UniqueConnection);
}
void KQOAuthAuthReplyServerPrivate::onBytesReady() {
Q_Q(KQOAuthAuthReplyServer);
QByteArray reply;
QByteArray content;
content.append("<HTML></HTML>");
reply.append("HTTP/1.0 200 OK \r\n");
reply.append("Content-Type: text/html; charset=\"utf-8\"\r\n");
reply.append(QString("Content-Length: %1\r\n").arg(content.size()));
reply.append("\r\n");
reply.append(content);
socket->write(reply);
QByteArray data = socket->readAll();
QMultiMap<QString, QString> queryParams = parseQueryParams(&data);
socket->disconnectFromHost();
q->close();
emit q->verificationReceived(queryParams);
}
QMultiMap<QString, QString> KQOAuthAuthReplyServerPrivate::parseQueryParams(QByteArray *data) {
QString splitGetLine = QString(*data).split("\r\n").first(); // Retrieve the first line with query params.
splitGetLine.remove("GET "); // Clean the line from GET
splitGetLine.remove("HTTP/1.1"); // From HTTP
splitGetLine.remove("\r\n"); // And from rest.
splitGetLine.prepend("http://localhost"); // Now, make it a URL
QUrl getTokenUrl(splitGetLine);
#if QT_VERSION < 0x050000
QList< QPair<QString, QString> > tokens = getTokenUrl.queryItems(); // Ask QUrl to do our work.
#else
QList< QPair<QString, QString> > tokens = QUrlQuery(getTokenUrl.query()).queryItems(); // Ask QUrl to do our work.
#endif
QMultiMap<QString, QString> queryParams;
QPair<QString, QString> tokenPair;
foreach (tokenPair, tokens) {
queryParams.insert(tokenPair.first.trimmed(), tokenPair.second.trimmed());
}
return queryParams;
}
KQOAuthAuthReplyServer::KQOAuthAuthReplyServer(QObject *parent) :
QTcpServer(parent),
d_ptr( new KQOAuthAuthReplyServerPrivate(this) )
{
Q_D(KQOAuthAuthReplyServer);
connect(this, SIGNAL(newConnection()),
d, SLOT(onIncomingConnection()));
}
KQOAuthAuthReplyServer::~KQOAuthAuthReplyServer()
{
delete d_ptr;
}

View file

@ -1,47 +0,0 @@
/**
* KQOAuth - An OAuth authentication library for Qt.
*
* Author: Johan Paul (johan.paul@gmail.com)
* http://www.johanpaul.com
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* KQOAuth 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with KQOAuth. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef KQOAUTHAUTHREPLYSERVER_H
#define KQOAUTHAUTHREPLYSERVER_H
#include <QTcpServer>
#include "kqoauthglobals.h"
class KQOAuthAuthReplyServerPrivate;
class KQOAuthAuthReplyServer : public QTcpServer
{
Q_OBJECT
public:
explicit KQOAuthAuthReplyServer(QObject *parent);
~KQOAuthAuthReplyServer();
Q_SIGNALS:
void verificationReceived(QMultiMap<QString, QString>);
private:
KQOAuthAuthReplyServerPrivate * const d_ptr;
Q_DECLARE_PRIVATE(KQOAuthAuthReplyServer);
Q_DISABLE_COPY(KQOAuthAuthReplyServer);
};
#endif // KQOAUTHAUTHREPLYSERVER_H

View file

@ -1,48 +0,0 @@
/**
* KQOAuth - An OAuth authentication library for Qt.
*
* Author: Johan Paul (johan.paul@gmail.com)
* http://www.johanpaul.com
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* KQOAuth 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with KQOAuth. If not, see <http://www.gnu.org/licenses/>.
*/
// Note this class shouldn't be copied or used and the implementation might change later.
#ifndef KQOAUTHAUTHREPLYSERVER_P_H
#define KQOAUTHAUTHREPLYSERVER_P_H
#include "kqoauthauthreplyserver.h"
#include <QMultiMap>
#include <QString>
class KQOAuthAuthReplyServerPrivate: public QObject
{
Q_OBJECT
public:
KQOAuthAuthReplyServerPrivate( KQOAuthAuthReplyServer * parent );
~KQOAuthAuthReplyServerPrivate();
QMultiMap<QString, QString> parseQueryParams(QByteArray *sdata);
public Q_SLOTS:
void onIncomingConnection();
void onBytesReady();
public:
KQOAuthAuthReplyServer * q_ptr;
Q_DECLARE_PUBLIC(KQOAuthAuthReplyServer);
QTcpSocket *socket;
};
#endif // KQOAUTHAUTHREPLYSERVER_P_H

View file

@ -1,38 +0,0 @@
/**
* KQOAuth - An OAuth authentication library for Qt.
*
* Author: Johan Paul (johan.paul@gmail.com)
* http://www.johanpaul.com
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* KQOAuth 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with KQOAuth. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef KQOAUTHGLOBALS_H
#define KQOAUTHGLOBALS_H
#include <QtCore/qglobal.h>
//////////// Static constant definitions ///////////
const QString OAUTH_KEY_CONSUMER("oauth_consumer");
const QString OAUTH_KEY_CONSUMER_KEY("oauth_consumer_key");
const QString OAUTH_KEY_TOKEN("oauth_token");
const QString OAUTH_KEY_TOKEN_SECRET("oauth_token_secret");
const QString OAUTH_KEY_SIGNATURE_METHOD("oauth_signature_method");
const QString OAUTH_KEY_TIMESTAMP("oauth_timestamp");
const QString OAUTH_KEY_NONCE("oauth_nonce");
const QString OAUTH_KEY_SIGNATURE("oauth_signature");
const QString OAUTH_KEY_CALLBACK("oauth_callback");
const QString OAUTH_KEY_VERIFIER("oauth_verifier");
const QString OAUTH_KEY_VERSION("oauth_version");
#endif // KQOAUTHGLOBALS_H

View file

@ -1,783 +0,0 @@
/**
* KQOAuth - An OAuth authentication library for Qt.
*
* Author: Johan Paul (johan.paul@gmail.com)
* http://www.johanpaul.com
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* KQOAuth 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with KQOAuth. If not, see <http://www.gnu.org/licenses/>.
*/
#include <QtCore>
#include <QDesktopServices>
#if QT_VERSION >= 0x050000
#include <QUrlQuery>
#endif
#include <QNetworkCookie>
#include "kqoauthmanager.h"
#include "kqoauthmanager_p.h"
////////////// Private d_ptr implementation ////////////////
KQOAuthManagerPrivate::KQOAuthManagerPrivate(KQOAuthManager *parent) :
error(KQOAuthManager::NoError) ,
r(0) ,
opaqueRequest(new KQOAuthRequest) ,
q_ptr(parent) ,
callbackServer(new KQOAuthAuthReplyServer(parent)) ,
isVerified(false) ,
isAuthorized(false) ,
autoAuth(false),
handleAuthPageOpening(true),
networkManager(new QNetworkAccessManager),
managerUserSet(false)
{
}
KQOAuthManagerPrivate::~KQOAuthManagerPrivate() {
delete opaqueRequest;
opaqueRequest = 0;
if (!managerUserSet) {
delete networkManager;
networkManager = 0;
}
}
QList< QPair<QString, QString> > KQOAuthManagerPrivate::createQueryParams(const KQOAuthParameters &requestParams) {
QList<QString> requestKeys = requestParams.keys();
QList<QString> requestValues = requestParams.values();
QList< QPair<QString, QString> > result;
for(int i=0; i<requestKeys.size(); i++) {
result.append( qMakePair(requestKeys.at(i),
requestValues.at(i))
);
}
return result;
}
QMultiMap<QString, QString> KQOAuthManagerPrivate::createTokensFromResponse(QByteArray reply) {
QMultiMap<QString, QString> result;
QString replyString(reply);
QStringList parameterPairs = replyString.split('&', QString::SkipEmptyParts);
foreach (const QString &parameterPair, parameterPairs) {
QStringList parameter = parameterPair.split('=');
result.insert(parameter.value(0), parameter.value(1));
}
return result;
}
bool KQOAuthManagerPrivate::setSuccessfulRequestToken(const QMultiMap<QString, QString> &request) {
if (currentRequestType == KQOAuthRequest::TemporaryCredentials) {
hasTemporaryToken = (!QString(request.value("oauth_token")).isEmpty() && !QString(request.value("oauth_token_secret")).isEmpty());
} else {
return false;
}
if (hasTemporaryToken) {
requestToken = QUrl::fromPercentEncoding( QString(request.value("oauth_token")).toLocal8Bit() );
requestTokenSecret = QUrl::fromPercentEncoding( QString(request.value("oauth_token_secret")).toLocal8Bit() );
}
return hasTemporaryToken;
}
bool KQOAuthManagerPrivate::setSuccessfulAuthorized(const QMultiMap<QString, QString> &request ) {
if (currentRequestType == KQOAuthRequest::AccessToken) {
isAuthorized = (!QString(request.value("oauth_token")).isEmpty() && !QString(request.value("oauth_token_secret")).isEmpty());
} else {
return false;
}
if (isAuthorized) {
requestToken = QUrl::fromPercentEncoding( QString(request.value("oauth_token")).toLocal8Bit() );
requestTokenSecret = QUrl::fromPercentEncoding( QString(request.value("oauth_token_secret")).toLocal8Bit() );
}
return isAuthorized;
}
void KQOAuthManagerPrivate::emitTokens() {
Q_Q(KQOAuthManager);
if (this->requestToken.isEmpty() || this->requestTokenSecret.isEmpty()) {
error = KQOAuthManager::RequestUnauthorized;
}
if (currentRequestType == KQOAuthRequest::TemporaryCredentials) {
// Signal that we are ready to use the protected resources.
emit q->temporaryTokenReceived(this->requestToken, this->requestTokenSecret);
}
if (currentRequestType == KQOAuthRequest::AccessToken) {
// Signal that we are ready to use the protected resources.
emit q->accessTokenReceived(this->requestToken, this->requestTokenSecret);
}
emit q->receivedToken(this->requestToken, this->requestTokenSecret);
}
bool KQOAuthManagerPrivate::setupCallbackServer() {
return callbackServer->listen();
}
/////////////// Public implementation ////////////////
KQOAuthManager::KQOAuthManager(QObject *parent) :
QObject(parent) ,
d_ptr(new KQOAuthManagerPrivate(this))
{
qsrand(QTime::currentTime().msec()); // We need to seed the nonce random number with something.
// However, we cannot do this while generating the nonce since
// we might get the same seed. So initializing here should be fine.
}
KQOAuthManager::~KQOAuthManager()
{
delete d_ptr;
}
void KQOAuthManager::executeRequest(KQOAuthRequest *request) {
Q_D(KQOAuthManager);
d->r = request;
if (request == 0) {
qWarning() << "Request is NULL. Cannot proceed.";
d->error = KQOAuthManager::RequestError;
return;
}
if (!request->requestEndpoint().isValid()) {
qWarning() << "Request endpoint URL is not valid. Cannot proceed.";
d->error = KQOAuthManager::RequestEndpointError;
return;
}
if (!request->isValid()) {
qWarning() << "Request is not valid. Cannot proceed.";
d->error = KQOAuthManager::RequestValidationError;
return;
}
d->currentRequestType = request->requestType();
QNetworkRequest networkRequest;
networkRequest.setUrl( request->requestEndpoint() );
if (d->autoAuth && d->currentRequestType == KQOAuthRequest::TemporaryCredentials) {
d->setupCallbackServer();
connect(d->callbackServer, SIGNAL(verificationReceived(QMultiMap<QString, QString>)),
this, SLOT( onVerificationReceived(QMultiMap<QString, QString>)));
QString serverString = "http://localhost:";
serverString.append(QString::number(d->callbackServer->serverPort()));
request->setCallbackUrl(QUrl(serverString));
}
// And now fill the request with "Authorization" header data.
QList<QByteArray> requestHeaders = request->requestParameters();
QByteArray authHeader;
bool first = true;
foreach (const QByteArray header, requestHeaders) {
if (!first) {
authHeader.append(", ");
} else {
authHeader.append("OAuth ");
first = false;
}
authHeader.append(header);
}
networkRequest.setRawHeader("Authorization", authHeader);
if (request->httpMethod() == KQOAuthRequest::GET) {
// Get the requested additional params as a list of pairs we can give QUrl
QList< QPair<QString, QString> > urlParams = d->createQueryParams(request->additionalParameters());
// Take the original URL and append the query params to it.
QUrl urlWithParams = networkRequest.url();
#if QT_VERSION < 0x050000
urlWithParams.setQueryItems(urlParams);
#else
QUrlQuery query;
query.setQueryItems(urlParams);
urlWithParams.setQuery(query);
#endif
networkRequest.setUrl(urlWithParams);
// Submit the request including the params.
QNetworkReply *reply = d->networkManager->get(networkRequest);
connect(reply, SIGNAL(finished()),
this, SLOT(onRequestReplyReceived()));
connect(reply, SIGNAL(error(QNetworkReply::NetworkError)),
this, SLOT(slotError(QNetworkReply::NetworkError)));
d->requestMap.insert( request, reply );
} else if (request->httpMethod() == KQOAuthRequest::POST) {
QNetworkReply *reply;
if (request->contentType() == "application/x-www-form-urlencoded") {
networkRequest.setHeader(QNetworkRequest::ContentTypeHeader, request->contentType());
reply = d->networkManager->post(networkRequest, request->requestBody());
} else if (request->contentType() == "multipart/form-data") {
reply = d->networkManager->post(networkRequest, request->httpMultiPart());
} else {
networkRequest.setHeader(QNetworkRequest::ContentTypeHeader, request->contentType());
reply = d->networkManager->post(networkRequest, request->rawData());
}
connect(reply, SIGNAL(finished()),
this, SLOT(onRequestReplyReceived()), Qt::UniqueConnection);
connect(reply, SIGNAL(error(QNetworkReply::NetworkError)),
this, SLOT(slotError(QNetworkReply::NetworkError)));
d->requestMap.insert( request, reply );
}
d->r->requestTimerStart();
}
void KQOAuthManager::executeAuthorizedRequest(KQOAuthRequest *request, int id) {
Q_D(KQOAuthManager);
d->r = request;
if (request == 0) {
qWarning() << "Request is NULL. Cannot proceed.";
d->error = KQOAuthManager::RequestError;
return;
}
if (!request->requestEndpoint().isValid()) {
qWarning() << "Request endpoint URL is not valid. Cannot proceed.";
d->error = KQOAuthManager::RequestEndpointError;
return;
}
if (!request->isValid()) {
qWarning() << "Request is not valid. Cannot proceed.";
d->error = KQOAuthManager::RequestValidationError;
return;
}
d->currentRequestType = request->requestType();
QNetworkRequest networkRequest;
networkRequest.setUrl( request->requestEndpoint() );
if ( d->currentRequestType != KQOAuthRequest::AuthorizedRequest){
qWarning() << "Not Authorized Request. Cannot proceed";
d->error = KQOAuthManager::RequestError;
return;
}
// And now fill the request with "Authorization" header data.
QList<QByteArray> requestHeaders = request->requestParameters();
QByteArray authHeader;
bool first = true;
foreach (const QByteArray header, requestHeaders) {
if (!first) {
authHeader.append(", ");
} else {
authHeader.append("OAuth ");
first = false;
}
authHeader.append(header);
}
networkRequest.setRawHeader("Authorization", authHeader);
QNetworkReply *reply = 0;
if (request->httpMethod() == KQOAuthRequest::POST) {
networkRequest.setHeader(QNetworkRequest::ContentTypeHeader, request->contentType());
/*
qDebug() << networkRequest.rawHeaderList();
qDebug() << networkRequest.rawHeader("Authorization");
qDebug() << networkRequest.rawHeader("Content-Type");
*/
if (request->contentType() == "application/x-www-form-urlencoded") {
reply = d->networkManager->post(networkRequest, request->requestBody());
} else if (request->contentType() == "multipart/form-data") {
reply = d->networkManager->post(networkRequest, request->httpMultiPart());
} else {
reply = d->networkManager->post(networkRequest, request->rawData());
}
connect(reply, SIGNAL(finished(QNetworkReply *)),
this, SLOT(onAuthorizedRequestReplyReceived(QNetworkReply*)), Qt::UniqueConnection);
connect(reply, SIGNAL(error(QNetworkReply::NetworkError)),
this, SLOT(slotError(QNetworkReply::NetworkError)));
connect(request, SIGNAL(requestTimedout()),
this, SLOT(requestTimeout()));
d->requestMap.insert( request, reply );
} else {
// Get the requested additional params as a list of pairs we can give QUrl
QList< QPair<QString, QString> > urlParams = d->createQueryParams(request->additionalParameters());
// Take the original URL and append the query params to it.
QUrl urlWithParams = networkRequest.url();
#if QT_VERSION < 0x050000
urlWithParams.setQueryItems(urlParams);
#else
QUrlQuery query;
query.setQueryItems(urlParams);
urlWithParams.setQuery(query);
#endif
networkRequest.setUrl(urlWithParams);
// Submit the request including the params.
if (request->httpMethod() == KQOAuthRequest::GET)
reply = d->networkManager->get(networkRequest);
else if (request->httpMethod() == KQOAuthRequest::HEAD)
reply = d->networkManager->head(networkRequest);
else if (request->httpMethod() == KQOAuthRequest::DELETE)
reply = d->networkManager->deleteResource(networkRequest);
connect(reply, SIGNAL(finished()),
this, SLOT(onAuthorizedRequestReplyReceived()));
connect(reply, SIGNAL(error(QNetworkReply::NetworkError)),
this, SLOT(slotError(QNetworkReply::NetworkError)));
connect(request, SIGNAL(requestTimedout()),
this, SLOT(requestTimeout()));
d->requestMap.insert( request, reply );
}
d->requestIds.insert(reply, id);
d->r->requestTimerStart();
}
void KQOAuthManager::setHandleUserAuthorization(bool set) {
Q_D(KQOAuthManager);
d->autoAuth = set;
}
void KQOAuthManager::setHandleAuthorizationPageOpening(bool set) {
Q_D(KQOAuthManager);
d->handleAuthPageOpening = set;
}
bool KQOAuthManager::hasTemporaryToken() {
Q_D(KQOAuthManager);
return d->hasTemporaryToken;
}
bool KQOAuthManager::isVerified() {
Q_D(KQOAuthManager);
return d->isVerified;
}
bool KQOAuthManager::isAuthorized() {
Q_D(KQOAuthManager);
return d->isAuthorized;
}
KQOAuthManager::KQOAuthError KQOAuthManager::lastError() {
Q_D(KQOAuthManager);
return d->error;
}
void KQOAuthManager::setNetworkManager(QNetworkAccessManager *manager) {
Q_D(KQOAuthManager);
if (manager == 0) {
d->error = KQOAuthManager::ManagerError;
return;
}
if (!d->managerUserSet) {
delete d->networkManager;
}
d->managerUserSet = true;
d->networkManager = manager;
}
QNetworkAccessManager * KQOAuthManager::networkManager() const {
Q_D(const KQOAuthManager);
if (d->managerUserSet) {
return d->networkManager;
} else {
return NULL;
}
}
//////////// Public convenience API /////////////
void KQOAuthManager::getUserAuthorization(QUrl authorizationEndpoint) {
Q_D(KQOAuthManager);
if (!d->hasTemporaryToken) {
qWarning() << "No temporary tokens retreieved. Cannot get user authorization.";
d->error = KQOAuthManager::RequestUnauthorized;
return;
}
if (!authorizationEndpoint.isValid()) {
qWarning() << "Authorization endpoint not valid. Cannot proceed.";
d->error = KQOAuthManager::RequestEndpointError;
return;
}
d->error = KQOAuthManager::NoError;
QPair<QString, QString> tokenParam = qMakePair(QString("oauth_token"), QString(d->requestToken));
QUrl openWebPageUrl(authorizationEndpoint.toString(), QUrl::StrictMode);
#if QT_VERSION < 0x050000
openWebPageUrl.addQueryItem(tokenParam.first, tokenParam.second);
#else
QUrlQuery query(openWebPageUrl);
query.addQueryItem(tokenParam.first, tokenParam.second);
openWebPageUrl.setQuery(query);
#endif
if (d->handleAuthPageOpening) {
// Open the user's default browser to the resource authorization page provided
// by the service.
QDesktopServices::openUrl(openWebPageUrl);
} else {
emit authorizationPageRequested(openWebPageUrl);
}
}
void KQOAuthManager::getUserAccessTokens(QUrl accessTokenEndpoint) {
Q_D(KQOAuthManager);
if (!d->isVerified) {
qWarning() << "Not verified. Cannot get access tokens.";
d->error = KQOAuthManager::RequestUnauthorized;
return;
}
if (!accessTokenEndpoint.isValid()) {
qWarning() << "Endpoint for access token exchange is not valid. Cannot proceed.";
d->error = KQOAuthManager::RequestEndpointError;
return;
}
d->error = KQOAuthManager::NoError;
d->opaqueRequest->clearRequest();
d->opaqueRequest->initRequest(KQOAuthRequest::AccessToken, accessTokenEndpoint);
d->opaqueRequest->setToken(d->requestToken);
d->opaqueRequest->setTokenSecret(d->requestTokenSecret);
d->opaqueRequest->setVerifier(d->requestVerifier);
d->opaqueRequest->setConsumerKey(d->consumerKey);
d->opaqueRequest->setConsumerSecretKey(d->consumerKeySecret);
d->opaqueRequest->setSignatureMethod(d->signatureMethod);
executeRequest(d->opaqueRequest);
}
void KQOAuthManager::verifyToken(const QString &token, const QString &verifier) {
QMultiMap<QString, QString> params;
params.insert("oauth_token", token);
params.insert("oauth_verifier", verifier);
onVerificationReceived(params);
}
void KQOAuthManager::sendAuthorizedRequest(QUrl requestEndpoint, const KQOAuthParameters &requestParameters) {
Q_D(KQOAuthManager);
if (!d->isAuthorized) {
qWarning() << "No access tokens retrieved. Cannot send authorized requests.";
d->error = KQOAuthManager::RequestUnauthorized;
return;
}
if (!requestEndpoint.isValid()) {
qWarning() << "Endpoint for authorized request is not valid. Cannot proceed.";
d->error = KQOAuthManager::RequestEndpointError;
return;
}
d->error = KQOAuthManager::NoError;
d->opaqueRequest->clearRequest();
d->opaqueRequest->initRequest(KQOAuthRequest::AuthorizedRequest, requestEndpoint);
d->opaqueRequest->setAdditionalParameters(requestParameters);
d->opaqueRequest->setToken(d->requestToken);
d->opaqueRequest->setTokenSecret(d->requestTokenSecret);
d->opaqueRequest->setConsumerKey(d->consumerKey);
d->opaqueRequest->setConsumerSecretKey(d->consumerKeySecret);
executeRequest(d->opaqueRequest);
}
/////////////// Private slots //////////////////
void KQOAuthManager::onRequestReplyReceived() {
Q_D(KQOAuthManager);
QNetworkReply* reply = qobject_cast<QNetworkReply*>(QObject::sender());
QNetworkReply::NetworkError networkError = reply->error();
switch (networkError) {
case QNetworkReply::NoError:
d->error = KQOAuthManager::NoError;
break;
case QNetworkReply::ContentAccessDenied:
case QNetworkReply::UnknownContentError:
case QNetworkReply::AuthenticationRequiredError:
d->error = KQOAuthManager::RequestUnauthorized;
break;
case QNetworkReply::ContentNotFoundError:
d->error = KQOAuthManager::ContentNotFound;
break;
case QNetworkReply::ContentOperationNotPermittedError:
d->error = KQOAuthManager::ContentOperationNotPermittedError;
break;
default:
d->error = KQOAuthManager::NetworkError;
break;
}
// Let's disconnect this slot first
/*
disconnect(d->networkManager, SIGNAL(finished(QNetworkReply *)),
this, SLOT(onRequestReplyReceived(QNetworkReply *)));
*/
// Read the content of the reply from the network.
QByteArray networkReply = reply->readAll();
d->r = d->requestMap.key(reply);
if( d->r ) {
d->requestMap.remove(d->r);
disconnect(d->r, SIGNAL(requestTimedout()),
this, SLOT(requestTimeout()));
// Stop any timer we have set on the request.
d->r->requestTimerStop();
d->currentRequestType = d->r->requestType();
}
QVariant v = reply->header(QNetworkRequest::SetCookieHeader);
/*QList<QNetworkCookie> c = qvariant_cast<QList<QNetworkCookie> >(v);
foreach (QNetworkCookie cookie , c)
qDebug() << cookie.name() << cookie.value();*/
// We need to emit the signal even if we got an error.
if (d->error != KQOAuthManager::NoError) {
reply->deleteLater();
emit requestReady(networkReply);
//d->emitTokens();
return;
}
// Just don't do anything if we didn't get anything useful.
if(networkReply.isEmpty()) {
reply->deleteLater();
return;
}
QMultiMap<QString, QString> responseTokens;
responseTokens = d->createTokensFromResponse(networkReply);
d->opaqueRequest->clearRequest();
d->opaqueRequest->setHttpMethod(KQOAuthRequest::POST); // XXX FIXME: Convenient API does not support GET
emit requestReady(networkReply);
if (!d->isAuthorized || !d->isVerified) {
if (d->setSuccessfulRequestToken(responseTokens)) {
//qDebug() << "Successfully got request tokens.";
d->consumerKey = d->r->consumerKeyForManager();
d->consumerKeySecret = d->r->consumerKeySecretForManager();
d->signatureMethod = d->r->requestSignatureMethodForManager();
d->opaqueRequest->setSignatureMethod(KQOAuthRequest::HMAC_SHA1);
d->opaqueRequest->setCallbackUrl(d->r->callbackUrlForManager());
d->emitTokens();
} else if (d->setSuccessfulAuthorized(responseTokens)) {
//qDebug() << "Successfully got access tokens.";
d->opaqueRequest->setSignatureMethod(KQOAuthRequest::HMAC_SHA1);
d->emitTokens();
} else if (d->currentRequestType == KQOAuthRequest::AuthorizedRequest) {
emit authorizedRequestDone();
}
}
reply->deleteLater(); // We need to clean this up, after the event processing is done.
}
void KQOAuthManager::onAuthorizedRequestReplyReceived() {
Q_D(KQOAuthManager);
QNetworkReply* reply = qobject_cast<QNetworkReply*>(QObject::sender());
QNetworkReply::NetworkError networkError = reply->error();
switch (networkError) {
case QNetworkReply::NoError:
d->error = KQOAuthManager::NoError;
break;
case QNetworkReply::ContentAccessDenied:
case QNetworkReply::UnknownContentError:
case QNetworkReply::AuthenticationRequiredError:
d->error = KQOAuthManager::RequestUnauthorized;
break;
case QNetworkReply::ContentNotFoundError:
d->error = KQOAuthManager::ContentNotFound;
break;
case QNetworkReply::ContentOperationNotPermittedError:
d->error = KQOAuthManager::ContentOperationNotPermittedError;
break;
default:
d->error = KQOAuthManager::NetworkError;
break;
}
/*
disconnect(d->networkManager, SIGNAL(finished(QNetworkReply *)),
this, SLOT(onAuthorizedRequestReplyReceived(QNetworkReply *)));
*/
// Read the content of the reply from the network.
QByteArray networkReply = reply->readAll();
int id = d->requestIds.take(reply);
d->r = d->requestMap.key(reply);
if( d->r ) {
d->requestMap.remove(d->r);
disconnect(d->r, SIGNAL(requestTimedout()),
this, SLOT(requestTimeout()));
// Stop any timer we have set on the request.
d->r->requestTimerStop();
d->currentRequestType = d->r->requestType();
}
// Just don't do anything if we didn't get anything useful.
if(networkReply.isEmpty()) {
reply->deleteLater();
return;
}
// We need to emit the signal even if we got an error.
if (d->error != KQOAuthManager::NoError) {
qWarning() << "Network reply error";
return;
}
d->opaqueRequest->clearRequest();
d->opaqueRequest->setHttpMethod(KQOAuthRequest::POST); // XXX FIXME: Convenient API does not support GET
if (d->currentRequestType == KQOAuthRequest::AuthorizedRequest) {
emit authorizedRequestDone();
}
emit authorizedRequestReady(networkReply, id);
reply->deleteLater();
}
void KQOAuthManager::onVerificationReceived(QMultiMap<QString, QString> response) {
Q_D(KQOAuthManager);
QString token = response.value("oauth_token");
QString verifier = response.value("oauth_verifier");
if (verifier.isEmpty()) {
d->error = KQOAuthManager::RequestUnauthorized;
}
verifier = QUrl::fromPercentEncoding(verifier.toUtf8()); // We get the raw URL response here so we need to convert it back
// to plain string so we can percent encode it again later in requests.
if (d->error == KQOAuthManager::NoError) {
d->requestVerifier = verifier;
d->isVerified = true;
}
emit authorizationReceived(token, verifier);
}
void KQOAuthManager::slotError(QNetworkReply::NetworkError error) {
Q_UNUSED(error)
//qDebug() << error;
Q_D(KQOAuthManager);
switch (error) {
case QNetworkReply::NoError:
d->error = KQOAuthManager::NoError;
break;
case QNetworkReply::ContentAccessDenied:
case QNetworkReply::UnknownContentError:
case QNetworkReply::AuthenticationRequiredError:
d->error = KQOAuthManager::RequestUnauthorized;
break;
case QNetworkReply::ContentNotFoundError:
d->error = KQOAuthManager::ContentNotFound;
break;
case QNetworkReply::ContentOperationNotPermittedError:
d->error = KQOAuthManager::ContentOperationNotPermittedError;
break;
default:
d->error = KQOAuthManager::NetworkError;
break;
}
QByteArray emptyResponse;
QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender());
//qDebug() << "STATUS" << reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
d->r = d->requestMap.key(reply);
d->currentRequestType = d->r->requestType();
if( d->requestIds.contains(reply) ) {
int id = d->requestIds.value(reply);
emit authorizedRequestReady(emptyResponse, id);
reply->deleteLater();
}
else if ( d->currentRequestType == KQOAuthRequest::AuthorizedRequest) {
// does this signal always have to be emitted if there is an error
// or can is it only valid for KQOAuthRequest::AuthorizedRequest?
if (error != QNetworkReply::ContentAccessDenied &&
error != QNetworkReply::AuthenticationRequiredError)
emit requestReady(emptyResponse);
emit authorizedRequestDone();
}
else {
if (error != QNetworkReply::ContentAccessDenied &&
error!= QNetworkReply::AuthenticationRequiredError)
emit requestReady(emptyResponse);
}
}
void KQOAuthManager::requestTimeout() {
Q_D(KQOAuthManager);
KQOAuthRequest *request = qobject_cast<KQOAuthRequest *>(sender());
if( d->requestMap.contains(request)) {
qWarning() << "KQOAuthManager::requestTimeout: Calling abort";
d->requestMap.value(request)->abort();
}
else
qWarning() << "KQOAuthManager::requestTimeout: The KQOAuthRequest was not found";
}

View file

@ -1,203 +0,0 @@
/**
* KQOAuth - An OAuth authentication library for Qt.
*
* Author: Johan Paul (johan.paul@gmail.com)
* http://www.johanpaul.com
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* KQOAuth 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with KQOAuth. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef KQOAUTHMANAGER_H
#define KQOAUTHMANAGER_H
#include <QObject>
#include <QMultiMap>
#include <QNetworkReply>
#include "kqoauthrequest.h"
class KQOAuthRequest;
class KQOAuthManagerThread;
class KQOAuthManagerPrivate;
class QNetworkAccessManager;
class QUrl;
class QByteArray;
class KQOAuthManager : public QObject
{
Q_OBJECT
public:
enum KQOAuthError {
NoError, // No error
NetworkError, // Network error: timeout, cannot connect.
RequestEndpointError, // Request endpoint is not valid.
RequestValidationError, // Request is not valid: some parameter missing?
RequestUnauthorized, // Authorization error: trying to access a resource without tokens.
ContentOperationNotPermittedError,// Authentication is required, key or auth is invalid
ContentNotFound, // Content is not found
RequestError, // The given request to KQOAuthManager is invalid: NULL?,
ManagerError // Manager error, cannot use for sending requests.
};
explicit KQOAuthManager(QObject *parent = 0);
~KQOAuthManager();
KQOAuthError lastError();
/**
* The manager executes the given request. It takes the HTTP parameters from the
* request and uses QNetworkAccessManager to submit the HTTP request to the net.
* When the request is done it will emit signal requestReady(QByteArray networkReply).
* NOTE: At the moment there is no timeout for the request.
*/
void executeRequest(KQOAuthRequest *request);
void executeAuthorizedRequest(KQOAuthRequest *request, int id);
/**
* Indicates to the user that KQOAuthManager should handle user authorization by
* opening the user's default browser and parsing the reply from the service.
* By setting the parameter to true, KQOAuthManager will store intermediate results
* of the OAuth 1.0 process in its own opaque request. This information is used in
* the user authorization process and also when calling sendAuthorizedRequest().
* NOTE: You need to set this to true if you want to use getUserAccessTokens() or
* sendAuthorizedRequest().
*/
void setHandleUserAuthorization(bool set);
/** Indicates whether the KQOAuthManager should launch the browser with the user
* authorization page itself.
*
* If set to true (the default), the KQOAuthManager uses QDesktopServices::openUrl()
* for opening the browser. Otherwise it emits the authorizationPageRequested()
* signal which must then be handled by the calling code.
*/
void setHandleAuthorizationPageOpening(bool set);
/**
* Returns true if the KQOAuthManager has retrieved the oauth_token value. Otherwise
* return false.
*/
bool hasTemporaryToken();
/**
* Returns true if the user has authorized us to use the protected resources. Otherwise
* returns false.
* NOTE: In order for KQOAuthManager to know if the user has authorized us to use the
* protected resources, KQOAuthManager must be in control of the user authorization
* process. Hence, this returns true if setHandleUserAuthorization() is set to true
* and the user is authorized with getUserAuthorization().
*/
bool isVerified();
/**
* Returns true if KQOAuthManager has the access token and hence can access the protected
* resources. Otherwise returns false.
* NOTE: In order for KQOAuthManager to know if we have access to protected resource
* KQOAuthManager must be in control of the user authorization process and requesting
* the acess token. Hence, this returns true if setHandleUserAuthorization() is set to true
* and the user is authorized with getUserAuthorization() and the access token must be retrieved
* with getUserAccessTokens.
*/
bool isAuthorized();
/**
* This is a convenience API for authorizing the user.
* The call will open the user's default browser, setup a local HTTP server and parse the reply from the
* service after the user has authorized us to access protected resources. If the user authorizes
* us to access protected resources, the verifier token is stored in KQOAuthManager for further use.
* In order to use this method, you must set setHandleUserAuthorization() to true.
*/
void getUserAuthorization(QUrl authorizationEndpoint);
/**
* This is a convenience API for retrieving the access token in exchange for the temporary token and the
* verifier.
* This call will create a KQOAuthRequest and use the previously stored temporary token and verifier to
* exchange for the access token, which will be used to access the protected resources.
* Note that in order to use this method, KQOAuthManager must be in control of the user authorization process.
* Set setHandleUserAuthorization() to true and retrieve user authorization with void getUserAuthorization.
*/
void getUserAccessTokens(QUrl accessTokenEndpoint);
/**
* This is a conveience API for setting the token verifier.
* If setHandleUserAuthorization() is set to false you need to call this function before calling
* getUserAccessTokens()
*/
void verifyToken(const QString &token, const QString &verifier);
/**
* Sends a request to the protected resources. Parameters for the request are service specific and
* are given to the 'requestParameters' as parameters.
* Note that in order to use this method, KQOAuthManager must be in control of the user authorization process.
* Set setHandleUserAuthorization() to true and retrieve user authorization with void getUserAuthorization.
*/
void sendAuthorizedRequest(QUrl requestEndpoint, const KQOAuthParameters &requestParameters);
/**
* Sets a custom QNetworkAccessManager to handle network requests. This method can be useful if the
* application is using some proxy settings for example.
* The application is responsible for deleting this manager. KQOAuthManager will not delete any
* previously given manager.
* If the manager is NULL, the manager will not be set and the KQOAuthManager::Error.
* If no manager is given, KQOAuthManager will use the default one it will create by itself.
*/
void setNetworkManager(QNetworkAccessManager *manager);
/**
* Returns the given QNetworkAccessManager. Returns NULL if none is given.
*/
QNetworkAccessManager* networkManager() const;
Q_SIGNALS:
// This signal will be emitted after each request has got a reply.
// Parameter is the raw response from the service.
void requestReady(QByteArray networkReply);
void authorizedRequestReady(QByteArray networkReply, int id);
// This signal will be emitted when the authorization page should be opened if
// setHandleAuthorizationPageOpening() is set to false.
void authorizationPageRequested(QUrl pageUrl);
// This signal will be emited when we have an request tokens available
// (either temporary resource tokens, or authorization tokens).
void receivedToken(QString oauth_token, QString oauth_token_secret); // oauth_token, oauth_token_secret
// This signal is emited when temporary tokens are returned from the service.
// Note that this signal is also emited in case temporary tokens are not available.
void temporaryTokenReceived(QString oauth_token, QString oauth_token_secret); // oauth_token, oauth_token_secret
// This signal is emited when the user has authenticated the application to
// communicate with the protected resources. Next we need to exchange the
// temporary tokens for access tokens.
// Note that this signal is also emited if user denies access.
void authorizationReceived(QString oauth_token, QString oauth_verifier); // oauth_token, oauth_verifier
// This signal is emited when access tokens are received from the service. We are
// ready to start communicating with the protected resources.
void accessTokenReceived(QString oauth_token, QString oauth_token_secret); // oauth_token, oauth_token_secret
// This signal is emited when the authorized request is done.
// This ends the kQOAuth interactions.
void authorizedRequestDone();
private Q_SLOTS:
void onRequestReplyReceived();
void onAuthorizedRequestReplyReceived();
void onVerificationReceived(QMultiMap<QString, QString> response);
void slotError(QNetworkReply::NetworkError error);
void requestTimeout();
private:
KQOAuthManagerPrivate *d_ptr;
Q_DECLARE_PRIVATE(KQOAuthManager);
Q_DISABLE_COPY(KQOAuthManager);
};
#endif // KQOAUTHMANAGER_H

View file

@ -1,76 +0,0 @@
/**
* KQOAuth - An OAuth authentication library for Qt.
*
* Author: Johan Paul (johan.paul@gmail.com)
* http://www.johanpaul.com
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* KQOAuth 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with KQOAuth. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef KQOAUTHMANAGER_P_H
#define KQOAUTHMANAGER_P_H
#include "kqoauthauthreplyserver.h"
#include "kqoauthrequest.h"
class KQOAuthManagerPrivate {
public:
KQOAuthManagerPrivate(KQOAuthManager *parent);
~KQOAuthManagerPrivate();
QList< QPair<QString, QString> > createQueryParams(const KQOAuthParameters &requestParams);
QMultiMap<QString, QString> createTokensFromResponse(QByteArray reply);
bool setSuccessfulRequestToken(const QMultiMap<QString, QString> &request);
bool setSuccessfulAuthorized(const QMultiMap<QString, QString> &request);
void emitTokens();
bool setupCallbackServer();
KQOAuthManager::KQOAuthError error;
KQOAuthRequest *r; // This request is used to cache the user sent request.
KQOAuthRequest *opaqueRequest; // This request is used to creating opaque convenience requests for the user.
KQOAuthManager * const q_ptr;
/**
* The items below are needed in order to store the state of the manager and
* by that be able to do convenience operations for the user.
*/
KQOAuthRequest::RequestType currentRequestType;
// Variables we store here for opaque request handling.
// NOTE: The variables are labeled the same for both access token request
// and protected resource access.
QString requestToken;
QString requestTokenSecret;
QString consumerKey;
QString consumerKeySecret;
QString requestVerifier;
KQOAuthRequest::RequestSignatureMethod signatureMethod;
KQOAuthAuthReplyServer *callbackServer;
bool hasTemporaryToken;
bool isVerified;
bool isAuthorized;
bool autoAuth;
bool handleAuthPageOpening;
QNetworkAccessManager *networkManager;
bool managerUserSet;
QMap<QNetworkReply*, int> requestIds;
QMap<KQOAuthRequest*, QNetworkReply*> requestMap;
Q_DECLARE_PUBLIC(KQOAuthManager);
};
#endif // KQOAUTHMANAGER_P_H

View file

@ -1,617 +0,0 @@
/**
* KQOAuth - An OAuth authentication library for Qt.
*
* Author: Johan Paul (johan.paul@gmail.com)
* http://www.johanpaul.com
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* KQOAuth 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with KQOAuth. If not, see <http://www.gnu.org/licenses/>.
*/
#include <QByteArray>
#include <QDateTime>
#include <QCryptographicHash>
#include <QPair>
#include <QStringList>
#include <QtDebug>
#include <QtAlgorithms>
#include "kqoauthrequest.h"
#include "kqoauthrequest_p.h"
#include "kqoauthutils.h"
#include "kqoauthglobals.h"
//////////// Private d_ptr implementation /////////
KQOAuthRequestPrivate::KQOAuthRequestPrivate() :
timeout(0)
{
}
KQOAuthRequestPrivate::~KQOAuthRequestPrivate()
{
}
// This method will not include the "oauthSignature" paramater, since it is calculated from these parameters.
void KQOAuthRequestPrivate::prepareRequest() {
// If parameter list is not empty, we don't want to insert these values by
// accident a second time. So giving up.
if( !requestParameters.isEmpty() ) {
return;
}
switch ( requestType ) {
case KQOAuthRequest::TemporaryCredentials:
requestParameters.append( qMakePair( OAUTH_KEY_CALLBACK, oauthCallbackUrl.toString()) ); // This is so ugly that it is almost beautiful.
requestParameters.append( qMakePair( OAUTH_KEY_SIGNATURE_METHOD, oauthSignatureMethod) );
requestParameters.append( qMakePair( OAUTH_KEY_CONSUMER_KEY, oauthConsumerKey ));
requestParameters.append( qMakePair( OAUTH_KEY_VERSION, oauthVersion ));
requestParameters.append( qMakePair( OAUTH_KEY_TIMESTAMP, this->oauthTimestamp() ));
requestParameters.append( qMakePair( OAUTH_KEY_NONCE, this->oauthNonce() ));
break;
case KQOAuthRequest::AccessToken:
requestParameters.append( qMakePair( OAUTH_KEY_SIGNATURE_METHOD, oauthSignatureMethod ));
requestParameters.append( qMakePair( OAUTH_KEY_CONSUMER_KEY, oauthConsumerKey ));
requestParameters.append( qMakePair( OAUTH_KEY_VERSION, oauthVersion ));
requestParameters.append( qMakePair( OAUTH_KEY_TIMESTAMP, this->oauthTimestamp() ));
requestParameters.append( qMakePair( OAUTH_KEY_NONCE, this->oauthNonce() ));
requestParameters.append( qMakePair( OAUTH_KEY_VERIFIER, oauthVerifier ));
requestParameters.append( qMakePair( OAUTH_KEY_TOKEN, oauthToken ));
break;
case KQOAuthRequest::AuthorizedRequest:
requestParameters.append( qMakePair( OAUTH_KEY_SIGNATURE_METHOD, oauthSignatureMethod ));
requestParameters.append( qMakePair( OAUTH_KEY_CONSUMER_KEY, oauthConsumerKey ));
requestParameters.append( qMakePair( OAUTH_KEY_VERSION, oauthVersion ));
requestParameters.append( qMakePair( OAUTH_KEY_TIMESTAMP, this->oauthTimestamp() ));
requestParameters.append( qMakePair( OAUTH_KEY_NONCE, this->oauthNonce() ));
requestParameters.append( qMakePair( OAUTH_KEY_TOKEN, oauthToken ));
break;
default:
break;
}
}
void KQOAuthRequestPrivate::signRequest() {
QString signature = this->oauthSignature();
requestParameters.append( qMakePair( OAUTH_KEY_SIGNATURE, signature) );
}
QString KQOAuthRequestPrivate::oauthSignature() {
/**
* http://oauth.net/core/1.0/#anchor16
* The HMAC-SHA1 signature method uses the HMAC-SHA1 signature algorithm as defined in [RFC2104] where the
* Signature Base String is the text and the key is the concatenated values (each first encoded per Parameter
* Encoding) of the Consumer Secret and Token Secret, separated by an & character (ASCII code 38) even if empty.
*
**/
QByteArray baseString = this->requestBaseString();
// Default: Use HMAC-SHA1
QString secret = QString(QUrl::toPercentEncoding(oauthConsumerSecretKey)) + "&" + QString(QUrl::toPercentEncoding(oauthTokenSecret));
QString signature = KQOAuthUtils::hmac_sha1(baseString, secret);
if (debugOutput) {
qDebug() << "========== KQOAuthRequest has the following signature:";
qDebug() << " * Signature : " << QUrl::toPercentEncoding(signature) << "\n";
}
return QString( QUrl::toPercentEncoding(signature) );
}
bool normalizedParameterSort(const QPair<QString, QString> &left, const QPair<QString, QString> &right) {
QString keyLeft = left.first;
QString valueLeft = left.second;
QString keyRight = right.first;
QString valueRight = right.second;
if(keyLeft == keyRight) {
return (valueLeft < valueRight);
} else {
return (keyLeft < keyRight);
}
}
QByteArray KQOAuthRequestPrivate::requestBaseString() {
QByteArray baseString;
// Every request has these as the commont parameters.
baseString.append( oauthHttpMethodString.toUtf8() + "&"); // HTTP method
baseString.append( QUrl::toPercentEncoding( oauthRequestEndpoint.toString(QUrl::RemoveQuery) ) + "&" ); // The path and query components
QList< QPair<QString, QString> > baseStringParameters;
baseStringParameters.append(requestParameters);
baseStringParameters.append(additionalParameters);
// Sort the request parameters. These parameters have been
// initialized earlier.
qSort(baseStringParameters.begin(),
baseStringParameters.end(),
normalizedParameterSort
);
// Last append the request parameters correctly encoded.
baseString.append( encodedParamaterList(baseStringParameters) );
if (debugOutput) {
qDebug() << "========== KQOAuthRequest has the following base string:";
qDebug() << baseString << "\n";
}
return baseString;
}
QByteArray KQOAuthRequestPrivate::encodedParamaterList(const QList< QPair<QString, QString> > &parameters) {
QByteArray resultList;
bool first = true;
QPair<QString, QString> parameter;
// Do the debug output.
if (debugOutput) {
qDebug() << "========== KQOAuthRequest has the following parameters:";
}
foreach (parameter, parameters) {
if(!first) {
resultList.append( "&" );
} else {
first = false;
}
// Here we don't need to explicitely encode the strings to UTF-8 since
// QUrl::toPercentEncoding() takes care of that for us.
resultList.append( QUrl::toPercentEncoding(parameter.first) // Parameter key
+ "="
+ QUrl::toPercentEncoding(parameter.second) // Parameter value
);
if (debugOutput) {
qDebug() << " * "
<< parameter.first
<< " : "
<< parameter.second;
}
}
if (debugOutput) {
qDebug() << "\n";
}
return QUrl::toPercentEncoding(resultList);
}
QString KQOAuthRequestPrivate::oauthTimestamp() const {
// This is basically for unit tests only. In most cases we don't set the nonce beforehand.
if (!oauthTimestamp_.isEmpty()) {
return oauthTimestamp_;
}
#if QT_VERSION >= 0x040700
return QString::number(QDateTime::currentDateTimeUtc().toTime_t());
#else
return QString::number(QDateTime::currentDateTime().toUTC().toTime_t());
#endif
}
QString KQOAuthRequestPrivate::oauthNonce() const {
// This is basically for unit tests only. In most cases we don't set the nonce beforehand.
if (!oauthNonce_.isEmpty()) {
return oauthNonce_;
}
return QString::number(qrand());
}
bool KQOAuthRequestPrivate::validateRequest() const {
switch ( requestType ) {
case KQOAuthRequest::TemporaryCredentials:
if (oauthRequestEndpoint.isEmpty()
|| oauthConsumerKey.isEmpty()
|| oauthNonce_.isEmpty()
|| oauthSignatureMethod.isEmpty()
|| oauthTimestamp_.isEmpty()
|| oauthVersion.isEmpty())
{
return false;
}
return true;
case KQOAuthRequest::AccessToken:
if (oauthRequestEndpoint.isEmpty()
|| oauthVerifier.isEmpty()
|| oauthConsumerKey.isEmpty()
|| oauthNonce_.isEmpty()
|| oauthSignatureMethod.isEmpty()
|| oauthTimestamp_.isEmpty()
|| oauthToken.isEmpty()
|| oauthTokenSecret.isEmpty()
|| oauthVersion.isEmpty())
{
return false;
}
return true;
case KQOAuthRequest::AuthorizedRequest:
if (oauthRequestEndpoint.isEmpty()
|| oauthConsumerKey.isEmpty()
|| oauthNonce_.isEmpty()
|| oauthSignatureMethod.isEmpty()
|| oauthTimestamp_.isEmpty()
|| oauthToken.isEmpty()
|| oauthTokenSecret.isEmpty()
|| oauthVersion.isEmpty())
{
return false;
}
return true;
default:
return false;
}
// We should not come here.
// Prevent "unreachable code" warning.
// return false;
}
//////////// Public implementation ////////////////
KQOAuthRequest::KQOAuthRequest(QObject *parent) :
QObject(parent),
d_ptr(new KQOAuthRequestPrivate)
{
Q_D(KQOAuthRequest);
d_ptr->debugOutput = false; // No debug output by default.
connect(&(d->timer), SIGNAL(timeout()), this, SIGNAL(requestTimedout()));
}
KQOAuthRequest::~KQOAuthRequest()
{
delete d_ptr;
}
void KQOAuthRequest::initRequest(KQOAuthRequest::RequestType type, const QUrl &requestEndpoint) {
Q_D(KQOAuthRequest);
if (!requestEndpoint.isValid()) {
qWarning() << "Endpoint URL is not valid. Ignoring. This request might not work.";
return;
}
if (type < 0 || type > KQOAuthRequest::AuthorizedRequest) {
qWarning() << "Invalid request type. Ignoring. This request might not work.";
return;
}
// Clear the request
clearRequest();
// Set smart defaults.
d->requestType = type;
d->oauthRequestEndpoint = requestEndpoint;
d->oauthTimestamp_ = d->oauthTimestamp();
d->oauthNonce_ = d->oauthNonce();
this->setSignatureMethod(KQOAuthRequest::HMAC_SHA1);
this->setHttpMethod(KQOAuthRequest::POST);
d->oauthVersion = "1.0"; // Currently supports only version 1.0
d->contentType = "application/x-www-form-urlencoded";
}
void KQOAuthRequest::setConsumerKey(const QString &consumerKey) {
Q_D(KQOAuthRequest);
d->oauthConsumerKey = consumerKey;
}
void KQOAuthRequest::setConsumerSecretKey(const QString &consumerSecretKey) {
Q_D(KQOAuthRequest);
d->oauthConsumerSecretKey = consumerSecretKey;
}
void KQOAuthRequest::setCallbackUrl(const QUrl &callbackUrl) {
Q_D(KQOAuthRequest);
d->oauthCallbackUrl = callbackUrl;
}
void KQOAuthRequest::setSignatureMethod(KQOAuthRequest::RequestSignatureMethod requestMethod) {
Q_D(KQOAuthRequest);
QString requestMethodString;
switch (requestMethod) {
case KQOAuthRequest::PLAINTEXT:
requestMethodString = "PLAINTEXT";
break;
case KQOAuthRequest::HMAC_SHA1:
requestMethodString = "HMAC-SHA1";
break;
default:
// We should not come here
qWarning() << "Invalid signature method set.";
break;
}
d->oauthSignatureMethod = requestMethodString;
d->requestSignatureMethod = requestMethod;
}
void KQOAuthRequest::setTokenSecret(const QString &tokenSecret) {
Q_D(KQOAuthRequest);
d->oauthTokenSecret = tokenSecret;
}
void KQOAuthRequest::setToken(const QString &token) {
Q_D(KQOAuthRequest);
d->oauthToken = token;
}
void KQOAuthRequest::setVerifier(const QString &verifier) {
Q_D(KQOAuthRequest);
d->oauthVerifier = verifier;
}
void KQOAuthRequest::setHttpMethod(KQOAuthRequest::RequestHttpMethod httpMethod) {
Q_D(KQOAuthRequest);
QString requestHttpMethodString;
switch (httpMethod) {
case KQOAuthRequest::GET:
requestHttpMethodString = "GET";
break;
case KQOAuthRequest::POST:
requestHttpMethodString = "POST";
break;
case KQOAuthRequest::HEAD:
requestHttpMethodString = "HEAD";
break;
case KQOAuthRequest::DELETE:
requestHttpMethodString = "DELETE";
break;
default:
qWarning() << "Invalid HTTP method set.";
break;
}
d->oauthHttpMethod = httpMethod;
d->oauthHttpMethodString = requestHttpMethodString;
}
KQOAuthRequest::RequestHttpMethod KQOAuthRequest::httpMethod() const {
Q_D(const KQOAuthRequest);
return d->oauthHttpMethod;
}
void KQOAuthRequest::setAdditionalParameters(const KQOAuthParameters &additionalParams) {
Q_D(KQOAuthRequest);
QList<QString> additionalKeys = additionalParams.keys();
QList<QString> additionalValues = additionalParams.values();
int i=0;
foreach(QString key, additionalKeys) {
QString value = additionalValues.at(i);
d->additionalParameters.append( qMakePair(key, value) );
i++;
}
}
KQOAuthParameters KQOAuthRequest::additionalParameters() const {
Q_D(const KQOAuthRequest);
QMultiMap<QString, QString> additionalParams;
for(int i=0; i<d->additionalParameters.size(); i++) {
additionalParams.insert(d->additionalParameters.at(i).first,
d->additionalParameters.at(i).second);
}
return additionalParams;
}
KQOAuthRequest::RequestType KQOAuthRequest::requestType() const {
Q_D(const KQOAuthRequest);
return d->requestType;
}
QUrl KQOAuthRequest::requestEndpoint() const {
Q_D(const KQOAuthRequest);
return d->oauthRequestEndpoint;
}
QList<QByteArray> KQOAuthRequest::requestParameters() {
Q_D(KQOAuthRequest);
QList<QByteArray> requestParamList;
d->prepareRequest();
if (!isValid() ) {
qWarning() << "Request is not valid! I will still sign it, but it will probably not work.";
}
d->signRequest();
QPair<QString, QString> requestParam;
QString param;
QString value;
foreach (requestParam, d->requestParameters) {
param = requestParam.first;
value = requestParam.second;
if (param != OAUTH_KEY_SIGNATURE) {
value = QUrl::toPercentEncoding(value);
}
requestParamList.append(QString(param + "=\"" + value +"\"").toUtf8());
}
return requestParamList;
}
QString KQOAuthRequest::contentType()
{
Q_D(const KQOAuthRequest);
return d->contentType;
}
void KQOAuthRequest::setContentType(const QString &contentType)
{
Q_D(KQOAuthRequest);
d->contentType = contentType;
}
QByteArray KQOAuthRequest::rawData()
{
Q_D(const KQOAuthRequest);
return d->postRawData;
}
void KQOAuthRequest::setRawData(const QByteArray &rawData)
{
Q_D(KQOAuthRequest);
d->postRawData = rawData;
}
QHttpMultiPart* KQOAuthRequest::httpMultiPart()
{
Q_D(const KQOAuthRequest);
return d->httpMultiPart;
}
void KQOAuthRequest::setHttpMultiPart(QHttpMultiPart* httpMultiPart)
{
Q_D(KQOAuthRequest);
d->httpMultiPart = httpMultiPart;
}
QByteArray KQOAuthRequest::requestBody() const {
Q_D(const KQOAuthRequest);
QByteArray postBodyContent;
bool first = true;
for(int i=0; i < d->additionalParameters.size(); i++) {
if(!first) {
postBodyContent.append("&");
} else {
first = false;
}
QString key = d->additionalParameters.at(i).first;
QString value = d->additionalParameters.at(i).second;
postBodyContent.append(QUrl::toPercentEncoding(key) + QString("=").toUtf8() +
QUrl::toPercentEncoding(value));
}
return postBodyContent;
}
bool KQOAuthRequest::isValid() const {
Q_D(const KQOAuthRequest);
return d->validateRequest();
}
void KQOAuthRequest::setTimeout(int timeoutMilliseconds) {
Q_D(KQOAuthRequest);
d->timeout = timeoutMilliseconds;
}
void KQOAuthRequest::clearRequest() {
Q_D(KQOAuthRequest);
d->oauthRequestEndpoint = "";
d->oauthHttpMethodString = "";
d->oauthConsumerKey = "";
d->oauthConsumerSecretKey = "";
d->oauthToken = "";
d->oauthTokenSecret = "";
d->oauthSignatureMethod = "";
d->oauthCallbackUrl = "";
d->oauthVerifier = "";
d->oauthTimestamp_ = "";
d->oauthNonce_ = "";
d->requestParameters.clear();
d->additionalParameters.clear();
d->timeout = 0;
}
void KQOAuthRequest::setEnableDebugOutput(bool enabled) {
Q_D(KQOAuthRequest);
d->debugOutput = enabled;
}
/**
* Protected implementations for inherited classes
*/
bool KQOAuthRequest::validateXAuthRequest() const {
Q_D(const KQOAuthRequest);
if (d->oauthRequestEndpoint.isEmpty()
|| d->oauthConsumerKey.isEmpty()
|| d->oauthNonce_.isEmpty()
|| d->oauthSignatureMethod.isEmpty()
|| d->oauthTimestamp_.isEmpty()
|| d->oauthVersion.isEmpty())
{
return false;
}
return true;
}
/**
* Private implementations for friend classes
*/
QString KQOAuthRequest::consumerKeyForManager() const {
Q_D(const KQOAuthRequest);
return d->oauthConsumerKey;
}
QString KQOAuthRequest::consumerKeySecretForManager() const {
Q_D(const KQOAuthRequest);
return d->oauthConsumerSecretKey;
}
KQOAuthRequest::RequestSignatureMethod KQOAuthRequest::requestSignatureMethodForManager() const {
Q_D(const KQOAuthRequest);
return d->requestSignatureMethod;
}
QUrl KQOAuthRequest::callbackUrlForManager() const {
Q_D(const KQOAuthRequest);
return d->oauthCallbackUrl;
}
void KQOAuthRequest::requestTimerStart()
{
Q_D(KQOAuthRequest);
if (d->timeout > 0) {
d->timer.start(d->timeout);
}
}
void KQOAuthRequest::requestTimerStop()
{
Q_D(KQOAuthRequest);
if( d->timer.isActive() )
d->timer.stop();
}

View file

@ -1,151 +0,0 @@
/**
* KQOAuth - An OAuth authentication library for Qt.
*
* Author: Johan Paul (johan.paul@gmail.com)
* http://www.johanpaul.com
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* KQOAuth 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with KQOAuth. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef KQOAUTHREQUEST_H
#define KQOAUTHREQUEST_H
#include <QObject>
#include <QUrl>
#include <QMultiMap>
#include <QHttpMultiPart>
#include "kqoauthglobals.h"
typedef QMultiMap<QString, QString> KQOAuthParameters;
class KQOAuthRequestPrivate;
class KQOAuthRequest : public QObject
{
Q_OBJECT
public:
explicit KQOAuthRequest(QObject *parent = 0);
~KQOAuthRequest();
enum RequestType {
TemporaryCredentials = 0,
AccessToken,
AuthorizedRequest
};
enum RequestSignatureMethod {
PLAINTEXT = 0,
HMAC_SHA1
};
#undef DELETE
enum RequestHttpMethod {
GET = 0,
POST,
HEAD,
DELETE
};
/**
* These methods can be overridden in child classes which are different types of
* OAuth requests.
*/
// Validate the request of this type.
virtual bool isValid() const;
/**
* These methods are OAuth request type specific and not overridden in child
* classes.
* NOTE: Refactorting still a TODO
*/
// Initialize the request of this type.
void initRequest(KQOAuthRequest::RequestType type, const QUrl &requestEndpoint);
void setConsumerKey(const QString &consumerKey);
void setConsumerSecretKey(const QString &consumerSecretKey);
// Mandatory methods for acquiring a request token
void setCallbackUrl(const QUrl &callbackUrl);
// Mandator methods for acquiring a access token
void setTokenSecret(const QString &tokenSecret);
void setToken(const QString &token);
void setVerifier(const QString &verifier);
// Request signature method to use - HMAC_SHA1 currently only supported
void setSignatureMethod(KQOAuthRequest::RequestSignatureMethod = KQOAuthRequest::HMAC_SHA1);
// Request's HTTP method.
void setHttpMethod(KQOAuthRequest::RequestHttpMethod = KQOAuthRequest::POST);
KQOAuthRequest::RequestHttpMethod httpMethod() const;
// Sets the timeout for this request. If the timeout expires, the signal "requestTimedout" will be
// emitted. The KQOAuthManager will then call the abort() function from QNetworkReply associated with this request
// 0 = If set to zero, timeout is disabled.
// TODO: Do we need some request ID now?
void setTimeout(int timeoutMilliseconds);
// Additional optional parameters to the request.
void setAdditionalParameters(const KQOAuthParameters &additionalParams);
KQOAuthParameters additionalParameters() const;
QList<QByteArray> requestParameters(); // This will return all request's parameters in the raw format given
// to the QNetworkRequest.
QByteArray requestBody() const; // This will return the POST body as given to the QNetworkRequest.
KQOAuthRequest::RequestType requestType() const;
QUrl requestEndpoint() const;
void setContentType(const QString &contentType);
QString contentType();
void setRawData(const QByteArray &rawData);
QByteArray rawData();
void setHttpMultiPart(QHttpMultiPart* httpMultiPart);
QHttpMultiPart* httpMultiPart();
void clearRequest();
// Enable verbose debug output for request content.
void setEnableDebugOutput(bool enabled);
Q_SIGNALS:
// This signal is emited if the request is not completed before the request's timeout
// value has expired.
void requestTimedout();
protected:
bool validateXAuthRequest() const;
private:
KQOAuthRequestPrivate * const d_ptr;
Q_DECLARE_PRIVATE(KQOAuthRequest);
Q_DISABLE_COPY(KQOAuthRequest);
// These classes are only for the internal use of KQOAuthManager so it can
// work with the opaque request.
QString consumerKeyForManager() const;
QString consumerKeySecretForManager() const;
KQOAuthRequest::RequestSignatureMethod requestSignatureMethodForManager() const;
QUrl callbackUrlForManager() const;
// This method is for timeout handling by the KQOAuthManager.
void requestTimerStart();
void requestTimerStop();
friend class KQOAuthManager;
#ifdef UNIT_TEST
friend class Ut_KQOAuth;
#endif
};
#endif // KQOAUTHREQUEST_H

View file

@ -1,98 +0,0 @@
/**
* KQOAuth - An OAuth authentication library for Qt.
*
* Author: Johan Paul (johan.paul@gmail.com)
* http://www.johanpaul.com
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* KQOAuth 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with KQOAuth. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef KQOAUTHREQUEST_P_H
#define KQOAUTHREQUEST_P_H
#include "kqoauthglobals.h"
#include "kqoauthrequest.h"
#include <QString>
#include <QUrl>
#include <QMap>
#include <QPair>
#include <QMultiMap>
#include <QTimer>
#include <QHttpMultiPart>
class KQOAuthRequestPrivate {
public:
KQOAuthRequestPrivate();
~KQOAuthRequestPrivate();
// Helper methods to get the values for the OAuth request parameters.
QString oauthTimestamp() const;
QString oauthNonce() const;
QString oauthSignature();
// Utility methods for making the request happen.
void prepareRequest();
void signRequest();
bool validateRequest() const;
QByteArray requestBaseString();
QByteArray encodedParamaterList(const QList< QPair<QString, QString> > &requestParameters);
void insertAdditionalParams();
void insertPostBody();
QUrl oauthRequestEndpoint;
KQOAuthRequest::RequestHttpMethod oauthHttpMethod;
QString oauthHttpMethodString;
QString oauthConsumerKey;
QString oauthConsumerSecretKey;
QString oauthToken;
QString oauthTokenSecret;
QString oauthSignatureMethod;
KQOAuthRequest::RequestSignatureMethod requestSignatureMethod;
QUrl oauthCallbackUrl;
QString oauthVersion;
QString oauthVerifier;
// These will be generated by the helper methods
QString oauthTimestamp_;
QString oauthNonce_;
// User specified additional parameters needed for the request.
QList< QPair<QString, QString> > additionalParameters;
// The raw POST body content as given to the HTTP request.
QByteArray postBodyContent;
// Protocol parameters.
// These parameters are used in the "Authorized" header of the HTTP request.
QList< QPair<QString, QString> > requestParameters;
KQOAuthRequest::RequestType requestType;
//The Content-Type HTTP header
QString contentType;
//Raw data to post if type is not url-encoded
QByteArray postRawData;
//Raw data to post if type is not url-encoded
QHttpMultiPart* httpMultiPart;
// Timeout for this request in milliseconds.
int timeout;
QTimer timer;
bool debugOutput;
};
#endif // KQOAUTHREQUEST_P_H

View file

@ -1,89 +0,0 @@
/**
* KQOAuth - An OAuth authentication library for Qt.
*
* Author: Johan Paul (johan.paul@gmail.com)
* http://www.johanpaul.com
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* KQOAuth 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with KQOAuth. If not, see <http://www.gnu.org/licenses/>.
*/
#include <QtDebug>
#include "kqoauthrequest_xauth_p.h"
#include "kqoauthrequest_xauth.h"
/**
* Private d_ptr implementations.
*/
KQOAuthRequest_XAuthPrivate::KQOAuthRequest_XAuthPrivate()
{
}
KQOAuthRequest_XAuthPrivate::~KQOAuthRequest_XAuthPrivate()
{
}
/**
* Public implementations.
*/
KQOAuthRequest_XAuth::KQOAuthRequest_XAuth(QObject *parent) :
KQOAuthRequest(parent),
d_ptr(new KQOAuthRequest_XAuthPrivate)
{
}
bool KQOAuthRequest_XAuth::isValid() const {
// An xAuth can never request temporary credentials.
if (requestType() == KQOAuthRequest::TemporaryCredentials) {
qWarning() << "XAuth request cannot be of type KQOAuthRequest::TemporaryCredentials. Aborting.";
return false;
}
// Access token must always be retrieved using the POST HTTP method.
if (requestType() == KQOAuthRequest::AccessToken
&& httpMethod() != KQOAuthRequest::POST) {
qWarning() << "Access tokens must be fetched using the POST HTTP method. Aborting.";
return false;
}
if (!xauth_parameters_set) {
qWarning() << "No XAuth parameters set. Aborting.";
return false;
}
// And then check the validity of the XAuth request.
// Provided by the base class as a protected method for us.
return validateXAuthRequest();
}
void KQOAuthRequest_XAuth::setXAuthLogin(const QString &username,
const QString &password) {
if (username.isEmpty() || password.isEmpty()) {
qWarning() << "Username or password cannot be empty. Aborting.";
return;
}
xauth_parameters_set = true;
KQOAuthParameters xauthParams;
xauthParams.insert("x_auth_username", username);
xauthParams.insert("x_auth_password", password);
xauthParams.insert("x_auth_mode", "client_auth");
setAdditionalParameters(xauthParams);
}

View file

@ -1,48 +0,0 @@
/**
* KQOAuth - An OAuth authentication library for Qt.
*
* Author: Johan Paul (johan.paul@gmail.com)
* http://www.johanpaul.com
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* KQOAuth 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with KQOAuth. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef KQOAUTHREQUEST_XAUTH_H
#define KQOAUTHREQUEST_XAUTH_H
#include "kqoauthrequest.h"
class KQOAuthRequest_XAuthPrivate;
class KQOAuthRequest_XAuth : public KQOAuthRequest
{
Q_OBJECT
public:
KQOAuthRequest_XAuth(QObject *parent = 0);
/**
* These methods can be overridden in child classes which are different types of
* OAuth requests.
*/
// Validate the request of this type.
bool isValid() const;
// Give the xAuth specific parameters.
void setXAuthLogin(const QString &username = "",
const QString &password = "");
private:
KQOAuthRequest_XAuthPrivate * const d_ptr;
bool xauth_parameters_set;
};
#endif // KQOAUTHREQUEST_XAUTH_H

View file

@ -1,33 +0,0 @@
/**
* KQOAuth - An OAuth authentication library for Qt.
*
* Author: Johan Paul (johan.paul@gmail.com)
* http://www.johanpaul.com
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* KQOAuth 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with KQOAuth. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef KQOAUTHREQUEST_XAUTH_P_H
#define KQOAUTHREQUEST_XAUTH_P_H
#include "kqoauthglobals.h"
class KQOAuthRequest;
class KQOAuthRequest_XAuthPrivate
{
public:
KQOAuthRequest_XAuthPrivate();
~KQOAuthRequest_XAuthPrivate();
};
#endif // KQOAUTHREQUEST_XAUTH_P_H

View file

@ -1,85 +0,0 @@
/**
* KQOAuth - An OAuth authentication library for Qt.
*
* Author: Johan Paul (johan.paul@gmail.com)
* http://www.johanpaul.com
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* KQOAuth 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with KQOAuth. If not, see <http://www.gnu.org/licenses/>.
*/
#include <QString>
#include <QCryptographicHash>
#include <QByteArray>
#include <QtDebug>
#include "kqoauthutils.h"
#include <openssl/pem.h>
#include <openssl/err.h>
#include <openssl/ssl.h>
#include <openssl/evp.h>
QString KQOAuthUtils::hmac_sha1(const QString &message, const QString &key)
{
QByteArray keyBytes = key.toLatin1();
int keyLength; // Length of key word
const int blockSize = 64; // Both MD5 and SHA-1 have a block size of 64.
keyLength = keyBytes.size();
// If key is longer than block size, we need to hash the key
if (keyLength > blockSize) {
QCryptographicHash hash(QCryptographicHash::Sha1);
hash.addData(keyBytes);
keyBytes = hash.result();
}
/* http://tools.ietf.org/html/rfc2104 - (1) */
// Create the opad and ipad for the hash function.
QByteArray ipad;
QByteArray opad;
ipad.fill( 0, blockSize);
opad.fill( 0, blockSize);
ipad.replace(0, keyBytes.length(), keyBytes);
opad.replace(0, keyBytes.length(), keyBytes);
/* http://tools.ietf.org/html/rfc2104 - (2) & (5) */
for (int i=0; i<64; i++) {
ipad[i] = ipad[i] ^ 0x36;
opad[i] = opad[i] ^ 0x5c;
}
QByteArray workArray;
workArray.clear();
workArray.append(ipad, 64);
/* http://tools.ietf.org/html/rfc2104 - (3) */
workArray.append(message.toLatin1());
/* http://tools.ietf.org/html/rfc2104 - (4) */
QByteArray sha1 = QCryptographicHash::hash(workArray, QCryptographicHash::Sha1);
/* http://tools.ietf.org/html/rfc2104 - (6) */
workArray.clear();
workArray.append(opad, 64);
workArray.append(sha1);
sha1.clear();
/* http://tools.ietf.org/html/rfc2104 - (7) */
sha1 = QCryptographicHash::hash(workArray, QCryptographicHash::Sha1);
return QString(sha1.toBase64());
}

View file

@ -1,32 +0,0 @@
/**
* KQOAuth - An OAuth authentication library for Qt.
*
* Author: Johan Paul (johan.paul@gmail.com)
* http://www.johanpaul.com
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* KQOAuth 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with KQOAuth. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef KQOAUTHUTILS_H
#define KQOAUTHUTILS_H
#include "kqoauthglobals.h"
class QString;
class KQOAuthUtils
{
public:
static QString hmac_sha1(const QString &message, const QString &key);
};
#endif // KQOAUTHUTILS_H