signon-plugin-oauth2-0.19+14.04.20140305/0000755000015201777760000000000012305566066020040 5ustar pbusernogroup00000000000000signon-plugin-oauth2-0.19+14.04.20140305/tests/0000755000015201777760000000000012305566066021202 5ustar pbusernogroup00000000000000signon-plugin-oauth2-0.19+14.04.20140305/tests/oauth2plugintest.cpp0000644000015201777760000005414512305565653025241 0ustar pbusernogroup00000000000000/* * This file is part of oauth2 plugin * * Copyright (C) 2010 Nokia Corporation. * Copyright (C) 2012 Canonical Ltd. * * Contact: Alberto Mardegan * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * 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 St, Fifth Floor, Boston, MA * 02110-1301 USA */ #include #include "plugin.h" #include "oauth1data.h" #include "oauth2data.h" #include "oauth2tokendata.h" #include "oauth2plugintest.h" using namespace OAuth2PluginNS; using namespace SignOn; #define TEST_START qDebug("\n\n\n\n ----------------- %s ----------------\n\n", __func__); #define TEST_DONE qDebug("\n\n ----------------- %s DONE ----------------\n\n", __func__); void OAuth2PluginTest::initTestCase() { TEST_START qRegisterMetaType(); qRegisterMetaType(); qRegisterMetaType(); TEST_DONE } void OAuth2PluginTest::cleanupTestCase() { TEST_START TEST_DONE } //prepare each test by creating new plugin void OAuth2PluginTest::init() { m_testPlugin = new Plugin(); } //finnish each test by deleting plugin void OAuth2PluginTest::cleanup() { delete m_testPlugin; m_testPlugin=NULL; } //slot for receiving result void OAuth2PluginTest::result(const SignOn::SessionData& data) { qDebug() << "got result"; m_response = data; m_loop.exit(); } //slot for receiving error void OAuth2PluginTest::pluginError(const SignOn::Error &err) { qDebug() << "got error" << err.type() << ": " << err.message(); m_error = err; m_loop.exit(); } //slot for receiving result void OAuth2PluginTest::uiRequest(const SignOn::UiSessionData& data) { Q_UNUSED(data); qDebug() << "got ui request"; m_uiResponse.setUrlResponse(QString("UI request received")); m_loop.exit(); } //slot for store void OAuth2PluginTest::store(const SignOn::SessionData &data) { qDebug() << "got store"; m_stored = data; } void OAuth2PluginTest::aborted(QNetworkReply* reply) { qDebug() << "aborted"; //we should get error code if request was aborted qDebug() << reply->error(); QVERIFY(reply->error()); m_loop.exit(); } // TEST CASES void OAuth2PluginTest::testPlugin() { TEST_START qDebug() << "Checking plugin integrity."; QVERIFY(m_testPlugin); TEST_DONE } void OAuth2PluginTest::testPluginType() { TEST_START qDebug() << "Checking plugin type."; QCOMPARE(m_testPlugin->type(), QString("oauth2")); TEST_DONE } void OAuth2PluginTest::testPluginMechanisms() { TEST_START qDebug() << "Checking plugin mechanisms."; QStringList mechs = m_testPlugin->mechanisms(); QVERIFY(!mechs.isEmpty()); QVERIFY(mechs.contains(QString("user_agent"))); QVERIFY(mechs.contains(QString("web_server"))); qDebug() << mechs; TEST_DONE } void OAuth2PluginTest::testPluginCancel() { TEST_START QTimer::singleShot(10*1000, &m_loop, SLOT(quit())); //does nothing as no active connections m_testPlugin->cancel(); //then real cancel QObject::connect(m_testPlugin, SIGNAL(error(const SignOn::Error &)), this, SLOT(pluginError(const SignOn::Error &)), Qt::QueuedConnection); OAuth2PluginData userAgentData; userAgentData.setHost("https://localhost"); userAgentData.setAuthPath("access_token"); userAgentData.setClientId("104660106251471"); userAgentData.setClientSecret("fa28f40b5a1f8c1d5628963d880636fbkjkjkj"); userAgentData.setRedirectUri("http://localhost/connect/login_success.html"); m_testPlugin->process(userAgentData, QString("user_agent")); m_testPlugin->cancel(); m_loop.exec(); QCOMPARE(m_error.type(), int(Error::SessionCanceled)); TEST_DONE } void OAuth2PluginTest::testPluginProcess() { TEST_START OAuth2PluginData userAgentData; userAgentData.setHost("https://localhost"); userAgentData.setTokenPath("access_token"); userAgentData.setClientId("104660106251471"); userAgentData.setClientSecret("fa28f40b5a1f8c1d5628963d880636fbkjkjkj"); userAgentData.setRedirectUri("http://localhost/connect/login_success.html"); QObject::connect(m_testPlugin, SIGNAL(result(const SignOn::SessionData&)), this, SLOT(result(const SignOn::SessionData&)),Qt::QueuedConnection); QObject::connect(m_testPlugin, SIGNAL(error(const SignOn::Error & )), this, SLOT(pluginError(const SignOn::Error &)),Qt::QueuedConnection); QObject::connect(m_testPlugin, SIGNAL(userActionRequired(const SignOn::UiSessionData&)), this, SLOT(uiRequest(const SignOn::UiSessionData&)),Qt::QueuedConnection); QObject::connect(m_testPlugin, SIGNAL(store(const SignOn::SessionData&)), this, SLOT(store(const SignOn::SessionData&)),Qt::QueuedConnection); QTimer::singleShot(10*1000, &m_loop, SLOT(quit())); // Invalid mechanism m_testPlugin->process(userAgentData, QString("ANONYMOUS")); m_loop.exec(); QCOMPARE(m_error.type(), int(Error::MechanismNotAvailable)); //try without params m_testPlugin->process(userAgentData, QString("user_agent")); m_loop.exec(); QCOMPARE(m_error.type(), int(Error::MissingData)); OAuth2PluginData webServerData; webServerData.setHost("https://localhost"); webServerData.setAuthPath("authorize"); webServerData.setClientId("104660106251471"); webServerData.setClientSecret("fa28f40b5a1f8c1d5628963d880636fbkjkjkj"); webServerData.setRedirectUri("http://localhost/connect/login_success.html"); webServerData.setScope(QStringList() << "scope1" << "scope2"); //try without params m_testPlugin->process(webServerData, QString("web_server")); m_loop.exec(); QCOMPARE(m_error.type(), int(Error::MissingData)); // Check for signon UI request for user_agent userAgentData.setAuthPath("authorize"); m_testPlugin->process(userAgentData, QString("user_agent")); m_loop.exec(); qDebug() << "Data = " << m_uiResponse.UrlResponse(); QCOMPARE(m_uiResponse.UrlResponse(), QString("UI request received")); // Check for signon UI request for web_server m_uiResponse.setUrlResponse(QString("")); webServerData.setTokenPath("token"); m_testPlugin->process(userAgentData, QString("web_server")); m_loop.exec(); qDebug() << "Data = " << m_uiResponse.UrlResponse(); QCOMPARE(m_uiResponse.UrlResponse(), QString("UI request received")); // Check using stored responses QVariantMap tokens; QVariantMap token; token.insert("Token", QLatin1String("tokenfromtest")); token.insert("Token2", QLatin1String("token2fromtest")); token.insert("timestamp", QDateTime::currentDateTime().toTime_t()); token.insert("Expiry", 10000); tokens.insert( QLatin1String("invalidid"), QVariant::fromValue(token)); webServerData.m_data.insert(QLatin1String("Tokens"), tokens); //try without params m_testPlugin->process(webServerData, QString("web_server")); m_loop.exec(); OAuth2PluginTokenData resp = m_response.data(); QVERIFY(resp.AccessToken() != QLatin1String("tokenfromtest")); QCOMPARE(m_error.type(), int(Error::MissingData)); tokens.insert( webServerData.ClientId(), QVariant::fromValue(token)); webServerData.m_data.insert(QLatin1String("Tokens"), tokens); /* try with missing cached scopes */ m_testPlugin->process(webServerData, QString("web_server")); m_loop.exec(); resp = m_response.data(); QVERIFY(resp.AccessToken() != QLatin1String("tokenfromtest")); QCOMPARE(m_error.type(), int(Error::MissingData)); /* try with incomplete cached scopes */ token.insert("Scopes", QStringList("scope2")); tokens.insert(webServerData.ClientId(), QVariant::fromValue(token)); webServerData.m_data.insert(QLatin1String("Tokens"), tokens); m_testPlugin->process(webServerData, QString("web_server")); m_loop.exec(); resp = m_response.data(); QVERIFY(resp.AccessToken() != QLatin1String("tokenfromtest")); QCOMPARE(m_error.type(), int(Error::MissingData)); /* try with sufficient cached scopes */ token.insert("Scopes", QStringList() << "scope1" << "scope3" << "scope2"); tokens.insert(webServerData.ClientId(), QVariant::fromValue(token)); webServerData.m_data.insert(QLatin1String("Tokens"), tokens); m_testPlugin->process(webServerData, QString("web_server")); m_loop.exec(); resp = m_response.data(); QCOMPARE(resp.AccessToken(), QLatin1String("tokenfromtest")); /* test the ProvidedTokens semantics */ OAuth2PluginData providedTokensWebServerData; providedTokensWebServerData.setHost("https://localhost"); providedTokensWebServerData.setAuthPath("authorize"); providedTokensWebServerData.setClientId("104660106251471"); providedTokensWebServerData.setClientSecret("fa28f40b5a1f8c1d5628963d880636fbkjkjkj"); providedTokensWebServerData.setRedirectUri("http://localhost/connect/login_success.html"); providedTokensWebServerData.setTokenPath("token"); providedTokensWebServerData.setScope(QStringList() << "scope1" << "scope3" << "scope2"); QVariantMap providedTokens; providedTokens.insert("AccessToken", "providedtokenfromtest"); providedTokens.insert("RefreshToken", "providedrefreshfromtest"); providedTokens.insert("ExpiresIn", 12345); /* try providing tokens to be stored */ m_stored = SignOn::SessionData(QVariantMap()); m_response = SignOn::SessionData(QVariantMap()); providedTokensWebServerData.m_data.insert("ProvidedTokens", providedTokens); m_testPlugin->process(providedTokensWebServerData, QString("web_server")); m_loop.exec(); resp = m_response.data(); QCOMPARE(resp.AccessToken(), QLatin1String("providedtokenfromtest")); QVariantMap storedTokens = m_stored.getProperty("Tokens").toMap(); QVariantMap storedTokensForKey = storedTokens.value(providedTokensWebServerData.ClientId()).toMap(); QCOMPARE(storedTokensForKey.value("Token"), providedTokens.value("AccessToken")); QCOMPARE(storedTokensForKey.value("refresh_token"), providedTokens.value("RefreshToken")); /* ensure that subsequent requests return the provided tokens */ m_response = SignOn::SessionData(QVariantMap()); providedTokensWebServerData.m_data.insert("ProvidedTokens", QVariantMap()); providedTokensWebServerData.m_data.insert("Tokens", storedTokens); m_testPlugin->process(providedTokensWebServerData, QString("web_server")); m_loop.exec(); resp = m_response.data(); QCOMPARE(resp.AccessToken(), QLatin1String("providedtokenfromtest")); TEST_DONE } void OAuth2PluginTest::testPluginHmacSha1Process() { TEST_START OAuth1PluginData hmacSha1Data; hmacSha1Data.setRequestEndpoint("https://localhost/oauth/request_token"); hmacSha1Data.setTokenEndpoint("https://localhost/oauth/access_token"); hmacSha1Data.setAuthorizationEndpoint("https://localhost/oauth/authorize"); hmacSha1Data.setCallback("https://localhost/connect/login_success.html"); hmacSha1Data.setConsumerKey("104660106251471"); hmacSha1Data.setConsumerSecret("fa28f40b5a1f8c1d5628963d880636fbkjkjkj"); QObject::connect(m_testPlugin, SIGNAL(result(const SignOn::SessionData&)), this, SLOT(result(const SignOn::SessionData&)),Qt::QueuedConnection); QObject::connect(m_testPlugin, SIGNAL(error(const SignOn::Error & )), this, SLOT(pluginError(const SignOn::Error &)),Qt::QueuedConnection); QObject::connect(m_testPlugin, SIGNAL(userActionRequired(const SignOn::UiSessionData&)), this, SLOT(uiRequest(const SignOn::UiSessionData&)),Qt::QueuedConnection); QObject::connect(m_testPlugin, SIGNAL(store(const SignOn::SessionData&)), this, SLOT(store(const SignOn::SessionData&)),Qt::QueuedConnection); QTimer::singleShot(10*1000, &m_loop, SLOT(quit())); // Invalid mechanism m_testPlugin->process(hmacSha1Data, QString("ANONYMOUS")); m_loop.exec(); QCOMPARE(m_error.type(), int(Error::MechanismNotAvailable)); // Try without params hmacSha1Data.setAuthorizationEndpoint(QString()); m_testPlugin->process(hmacSha1Data, QString("HMAC-SHA1")); m_loop.exec(); QCOMPARE(m_error.type(), int(Error::MissingData)); // Check for signon UI request for HMAC-SHA1 hmacSha1Data.setAuthorizationEndpoint("https://localhost/oauth/authorize"); m_testPlugin->process(hmacSha1Data, QString("HMAC-SHA1")); m_loop.exec(); qDebug() << "Data = " << m_uiResponse.UrlResponse(); QCOMPARE(m_uiResponse.UrlResponse(), QString("UI request received")); /* Now store some tokens and test the responses */ hmacSha1Data.m_data.insert("UiPolicy", NoUserInteractionPolicy); QVariantMap tokens; // ConsumerKey to Token map QVariantMap token; token.insert("oauth_token", QLatin1String("hmactokenfromtest")); token.insert("oauth_token_secret", QLatin1String("hmacsecretfromtest")); token.insert("timestamp", QDateTime::currentDateTime().toTime_t()); token.insert("Expiry", (uint)50000); tokens.insert(QLatin1String("invalidid"), QVariant::fromValue(token)); hmacSha1Data.m_data.insert(QLatin1String("Tokens"), tokens); // Try without cached token for our ConsumerKey m_response = SignOn::SessionData(QVariantMap()); m_testPlugin->process(hmacSha1Data, QString("HMAC-SHA1")); m_loop.exec(); OAuth1PluginTokenData resp = m_response.data(); QVERIFY(resp.AccessToken() != QLatin1String("hmactokenfromtest")); // Ensure that the cached token is returned as required m_response = SignOn::SessionData(QVariantMap()); tokens.insert(hmacSha1Data.ConsumerKey(), QVariant::fromValue(token)); hmacSha1Data.m_data.insert(QLatin1String("Tokens"), tokens); m_testPlugin->process(hmacSha1Data, QString("HMAC-SHA1")); m_loop.exec(); resp = m_response.data(); QCOMPARE(resp.AccessToken(), QLatin1String("hmactokenfromtest")); /* test the ProvidedTokens semantics */ OAuth1PluginData providedTokensHmacSha1Data; providedTokensHmacSha1Data.setRequestEndpoint("https://localhost/oauth/request_token"); providedTokensHmacSha1Data.setTokenEndpoint("https://localhost/oauth/access_token"); providedTokensHmacSha1Data.setAuthorizationEndpoint("https://localhost/oauth/authorize"); providedTokensHmacSha1Data.setCallback("https://localhost/connect/login_success.html"); providedTokensHmacSha1Data.setConsumerKey("104660106251471"); providedTokensHmacSha1Data.setConsumerSecret("fa28f40b5a1f8c1d5628963d880636fbkjkjkj"); QVariantMap providedTokens; providedTokens.insert("AccessToken", "providedhmactokenfromtest"); providedTokens.insert("TokenSecret", "providedhmacsecretfromtest"); providedTokens.insert("ScreenName", "providedhmacscreennamefromtest"); // try providing tokens to be stored m_stored = SignOn::SessionData(QVariantMap()); m_response = SignOn::SessionData(QVariantMap()); providedTokensHmacSha1Data.m_data.insert("ProvidedTokens", providedTokens); m_testPlugin->process(providedTokensHmacSha1Data, QString("HMAC-SHA1")); m_loop.exec(); resp = m_response.data(); QCOMPARE(resp.AccessToken(), QLatin1String("providedhmactokenfromtest")); QVariantMap storedTokens = m_stored.getProperty("Tokens").toMap(); QVariantMap storedTokensForKey = storedTokens.value(providedTokensHmacSha1Data.ConsumerKey()).toMap(); QCOMPARE(storedTokensForKey.value("oauth_token"), providedTokens.value("AccessToken")); QCOMPARE(storedTokensForKey.value("oauth_token_secret"), providedTokens.value("TokenSecret")); // ensure that subsequent requests return the provided tokens m_response = SignOn::SessionData(QVariantMap()); providedTokensHmacSha1Data.m_data.insert("UiPolicy", NoUserInteractionPolicy); providedTokensHmacSha1Data.m_data.insert("ProvidedTokens", QVariantMap()); providedTokensHmacSha1Data.m_data.insert("Tokens", storedTokens); m_testPlugin->process(providedTokensHmacSha1Data, QString("HMAC-SHA1")); m_loop.exec(); resp = m_response.data(); QCOMPARE(resp.AccessToken(), QLatin1String("providedhmactokenfromtest")); TEST_DONE } void OAuth2PluginTest::testPluginUseragentUserActionFinished() { TEST_START SignOn::UiSessionData info; OAuth2PluginData data; data.setHost("https://localhost"); data.setAuthPath("authorize"); data.setTokenPath("access_token"); data.setClientId("104660106251471"); data.setClientSecret("fa28f40b5a1f8c1d5628963d880636fbkjkjkj"); data.setRedirectUri("http://localhost/connect/login_success.html"); QStringList scopes = QStringList() << "scope1" << "scope2"; data.setScope(scopes); QObject::connect(m_testPlugin, SIGNAL(result(const SignOn::SessionData&)), this, SLOT(result(const SignOn::SessionData&)),Qt::QueuedConnection); QObject::connect(m_testPlugin, SIGNAL(error(const SignOn::Error & )), this, SLOT(pluginError(const SignOn::Error &)),Qt::QueuedConnection); QObject::connect(m_testPlugin, SIGNAL(userActionRequired(const SignOn::UiSessionData&)), this, SLOT(uiRequest(const SignOn::UiSessionData&)),Qt::QueuedConnection); QObject::connect(m_testPlugin, SIGNAL(store(const SignOn::SessionData&)), this, SLOT(store(const SignOn::SessionData&)), Qt::QueuedConnection); QTimer::singleShot(10*1000, &m_loop, SLOT(quit())); m_testPlugin->process(data, QString("user_agent")); m_loop.exec(); qDebug() << "Data = " << m_uiResponse.UrlResponse(); QCOMPARE(m_uiResponse.UrlResponse(), QString("UI request received")); //empty data m_testPlugin->userActionFinished(info); m_loop.exec(); QCOMPARE(m_error.type(), int(Error::NotAuthorized)); //invalid data info.setUrlResponse(QString("http://www.facebook.com/connect/login_success.html#access_token=&expires_in=4776")); m_testPlugin->userActionFinished(info); m_loop.exec(); QCOMPARE(m_error.type(), int(Error::NotAuthorized)); //Invalid data info.setUrlResponse(QString("http://www.facebook.com/connect/login_success.html")); m_testPlugin->userActionFinished(info); m_loop.exec(); QCOMPARE(m_error.type(), int(Error::NotAuthorized)); //valid data info.setUrlResponse(QString("http://www.facebook.com/connect/login_success.html#access_token=testtoken.&expires_in=4776")); m_testPlugin->userActionFinished(info); m_loop.exec(); OAuth2PluginTokenData *result = (OAuth2PluginTokenData*)&m_response; QCOMPARE(result->AccessToken(), QString("testtoken.")); QCOMPARE(result->ExpiresIn(), 4776); QVariantMap storedTokenData = m_stored.data().Tokens(); QVariantMap storedClientData = storedTokenData.value(data.ClientId()).toMap(); QVERIFY(!storedClientData.isEmpty()); QCOMPARE(storedClientData["Scopes"].toStringList(), scopes); //valid data info.setUrlResponse(QString("http://www.facebook.com/connect/login_success.html#access_token=testtoken.")); m_testPlugin->userActionFinished(info); m_loop.exec(); result = (OAuth2PluginTokenData*)&m_response; QCOMPARE(result->AccessToken(), QString("testtoken.")); QCOMPARE(result->ExpiresIn(), 0); //Permission denied info.setUrlResponse(QString("http://www.facebook.com/connect/login_success.html?error=user_denied")); m_testPlugin->userActionFinished(info); m_loop.exec(); QCOMPARE(m_error.type(), int(Error::NotAuthorized)); TEST_DONE } void OAuth2PluginTest::testPluginWebserverUserActionFinished() { TEST_START SignOn::UiSessionData info; OAuth2PluginData data; data.setHost("https://localhost"); data.setAuthPath("authorize"); data.setTokenPath("access_token"); data.setClientId("104660106251471"); data.setClientSecret("fa28f40b5a1f8c1d5628963d880636fbkjkjkj"); data.setRedirectUri("http://localhost/connect/login_success.html"); QObject::connect(m_testPlugin, SIGNAL(result(const SignOn::SessionData&)), this, SLOT(result(const SignOn::SessionData&)),Qt::QueuedConnection); QObject::connect(m_testPlugin, SIGNAL(error(const SignOn::Error & )), this, SLOT(pluginError(const SignOn::Error &)),Qt::QueuedConnection); QObject::connect(m_testPlugin, SIGNAL(userActionRequired(const SignOn::UiSessionData&)), this, SLOT(uiRequest(const SignOn::UiSessionData&)),Qt::QueuedConnection); QTimer::singleShot(10*1000, &m_loop, SLOT(quit())); m_testPlugin->process(data, QString("web_server")); m_loop.exec(); qDebug() << "Data = " << m_uiResponse.UrlResponse(); QCOMPARE(m_uiResponse.UrlResponse(), QString("UI request received")); //empty data m_testPlugin->userActionFinished(info); m_loop.exec(); QCOMPARE(m_error.type(), int(Error::NotAuthorized)); //invalid data info.setUrlResponse(QString("http://www.facebook.com/connect/login_success.html")); m_testPlugin->userActionFinished(info); m_loop.exec(); QCOMPARE(m_error.type(), int(Error::NotAuthorized)); //Permission denied info.setUrlResponse(QString("http://www.facebook.com/connect/login_success.html?error=user_denied")); m_testPlugin->userActionFinished(info); m_loop.exec(); QCOMPARE(m_error.type(), int(Error::NotAuthorized)); //invalid data info.setUrlResponse(QString("http://www.facebook.com/connect/login_success.html?sdsdsds=access.grant.")); m_testPlugin->userActionFinished(info); m_loop.exec(); QCOMPARE(m_error.type(), int(Error::NotAuthorized)); TEST_DONE } //end test cases QTEST_MAIN(OAuth2PluginTest) signon-plugin-oauth2-0.19+14.04.20140305/tests/tests.pro0000644000015201777760000000205212305565653023066 0ustar pbusernogroup00000000000000include( ../common-project-config.pri ) include( ../common-vars.pri ) TARGET = signon-oauth2plugin-tests QT += core \ network \ testlib QT -= gui CONFIG += \ link_pkgconfig SOURCES += \ $${TOP_SRC_DIR}/src/base-plugin.cpp \ $${TOP_SRC_DIR}/src/oauth2plugin.cpp \ $${TOP_SRC_DIR}/src/oauth1plugin.cpp \ $${TOP_SRC_DIR}/src/plugin.cpp \ oauth2plugintest.cpp HEADERS += \ $${TOP_SRC_DIR}/src/base-plugin.h \ $${TOP_SRC_DIR}/src/oauth2plugin.h \ $${TOP_SRC_DIR}/src/oauth1plugin.h \ $${TOP_SRC_DIR}/src/plugin.h \ oauth2plugintest.h INCLUDEPATH += . \ $${TOP_SRC_DIR}/src \ /usr/include/signon-qt PKGCONFIG += \ signon-plugins lessThan(QT_MAJOR_VERSION, 5) { PKGCONFIG += \ QJson \ libsignon-qt } else { PKGCONFIG += \ libsignon-qt5 } target.path = /usr/bin testsuite.path = /usr/share/$$TARGET testsuite.files = tests.xml INSTALLS += target \ testsuite check.depends = $$TARGET check.commands = ./$$TARGET || : QMAKE_EXTRA_TARGETS += check QMAKE_CLEAN += $$TARGET signon-plugin-oauth2-0.19+14.04.20140305/tests/oauth2plugintest.h0000644000015201777760000000372312305565653024702 0ustar pbusernogroup00000000000000/* * This file is part of oauth2 plugin * * Copyright (C) 2010 Nokia Corporation. * Copyright (C) 2012 Canonical Ltd. * * Contact: Alberto Mardegan * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * 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 St, Fifth Floor, Boston, MA * 02110-1301 USA */ #ifndef OAUTH2PLUGINTEST_H #define OAUTH2PLUGINTEST_H #include #include #include "plugin.h" #include "SignOn/AuthPluginInterface" using namespace OAuth2PluginNS; class OAuth2PluginTest : public QObject { Q_OBJECT public slots: void result(const SignOn::SessionData &data); void pluginError(const SignOn::Error &err); void uiRequest(const SignOn::UiSessionData &data); void store(const SignOn::SessionData &data); void aborted(QNetworkReply *reply); private slots: void initTestCase(); void cleanupTestCase(); void init(); void cleanup(); //test cases void testPlugin(); void testPluginType(); void testPluginMechanisms(); void testPluginCancel(); void testPluginProcess(); void testPluginHmacSha1Process(); void testPluginUseragentUserActionFinished(); void testPluginWebserverUserActionFinished(); private: Plugin *m_testPlugin; SignOn::Error m_error; SignOn::SessionData m_response; SignOn::UiSessionData m_uiResponse; SignOn::SessionData m_stored; QEventLoop m_loop; }; #endif // OAUTH2PLUGINTEST_H signon-plugin-oauth2-0.19+14.04.20140305/tests/tests.xml0000644000015201777760000000435212305565653023073 0ustar pbusernogroup00000000000000 signon-oauth2plugin-tests:signon-oauth2plugin-tests signon-oauth2plugin-tests:signon-oauth2plugin-tests:testPlugin /usr/bin/signon-oauth2plugin-tests testPlugin signon-oauth2plugin-tests:signon-oauth2plugin-tests:testPluginType /usr/bin/signon-oauth2plugin-tests testPluginType signon-oauth2plugin-tests:signon-oauth2plugin-tests:testPluginMechanisms /usr/bin/signon-oauth2plugin-tests testPluginMechanisms signon-oauth2plugin-tests:signon-oauth2plugin-tests:testPluginCancel /usr/bin/signon-oauth2plugin-tests testPluginCancel signon-oauth2plugin-tests:signon-oauth2plugin-tests:testPluginProcess /usr/bin/signon-oauth2plugin-tests testPluginProcess signon-oauth2plugin-tests:signon-oauth2plugin-tests:testPluginWebserverUserActionFinished /usr/bin/signon-oauth2plugin-tests testPluginProcess true true signon-plugin-oauth2-0.19+14.04.20140305/signon-oauth2.pro0000644000015201777760000000072712305565653023266 0ustar pbusernogroup00000000000000include( common-vars.pri ) include( common-project-config.pri ) TEMPLATE = subdirs CONFIG += ordered SUBDIRS = src tests example include( common-installs-config.pri ) #include( doc/doc.pri ) DISTNAME = $${PROJECT_NAME}-$${PROJECT_VERSION} EXCLUDES = \ --exclude-vcs \ --exclude-from .gitignore dist.commands = "tar -cvjf $${DISTNAME}.tar.bz2 $$EXCLUDES --transform='s,^,$$DISTNAME/,' *" dist.depends = distclean QMAKE_EXTRA_TARGETS += dist # End of File signon-plugin-oauth2-0.19+14.04.20140305/common-vars.pri0000644000015201777760000000172012305565653023016 0ustar pbusernogroup00000000000000#----------------------------------------------------------------------------- # Common variables for all projects. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Project name (used e.g. in include file and doc install path). # remember to update debian/* files if you changes this #----------------------------------------------------------------------------- PROJECT_NAME = signon-oauth2 #----------------------------------------------------------------------------- # Project version # remember to update debian/* files if you changes this #----------------------------------------------------------------------------- PROJECT_VERSION = 0.19 #----------------------------------------------------------------------------- # Library version #----------------------------------------------------------------------------- LIBRARY_VERSION = 0.5 # End of File signon-plugin-oauth2-0.19+14.04.20140305/.gitignore0000644000015201777760000000026212305565653022031 0ustar pbusernogroup00000000000000.moc .obj Makefile* builddir build-stamp configure-stamp core coverage-html debian moc_* tests/signon-oauth2plugin-tests *~ *.a *.gcda *.gcno *.moc *.o *.so *.swp *.so.* *.tar.* signon-plugin-oauth2-0.19+14.04.20140305/common-installs-config.pri0000644000015201777760000000361112305565653025140 0ustar pbusernogroup00000000000000#----------------------------------------------------------------------------- # Installation configuration for all SSO plugins #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # default installation target for applications #----------------------------------------------------------------------------- contains( TEMPLATE, app ) { target.path = $${INSTALL_PREFIX}/bin INSTALLS += target message("====") message("==== INSTALLS += target") } #----------------------------------------------------------------------------- # default installation target for libraries #----------------------------------------------------------------------------- contains( TEMPLATE, lib ) { target.path = $${SIGNON_PLUGINS_DIR} INSTALLS += target message("====") message("==== INSTALLS += target") } #----------------------------------------------------------------------------- # target for header files #----------------------------------------------------------------------------- !isEmpty( headers.files ) { headers.path = $${INSTALL_PREFIX}/include/signon-plugins INSTALLS += headers message("====") message("==== INSTALLS += headers") } else { message("====") message("==== NOTE: Remember to add your plugin headers into `headers.files' for installation!") } #----------------------------------------------------------------------------- # target for header files #----------------------------------------------------------------------------- !isEmpty( pkgconfig.files ) { pkgconfig.path = $${INSTALL_LIBDIR}/pkgconfig INSTALLS += pkgconfig message("====") message("==== INSTALLS += pkgconfig") } else { message("====") message("==== NOTE: Remember to add your pkgconfig into `pkgconfig.files' for installation!") } # End of File signon-plugin-oauth2-0.19+14.04.20140305/common-project-config.pri0000644000015201777760000000462612305565653024764 0ustar pbusernogroup00000000000000#----------------------------------------------------------------------------- # Common variables for all projects. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Common configuration for all projects. #----------------------------------------------------------------------------- CONFIG += link_pkgconfig #MOC_DIR = .moc #OBJECTS_DIR = .obj RCC_DIR = resources UI_DIR = ui UI_HEADERS_DIR = ui/include UI_SOURCES_DIR = ui/src QMAKE_CXXFLAGS += -fno-exceptions \ -fno-rtti # we don't like warnings... QMAKE_CXXFLAGS += -Werror TOP_SRC_DIR = $$PWD #DEFINES += QT_NO_DEBUG_OUTPUT DEFINES += SIGNON_TRACE #----------------------------------------------------------------------------- # setup the installation prefix #----------------------------------------------------------------------------- INSTALL_PREFIX = /usr # default installation prefix # default prefix can be overriden by defining PREFIX when running qmake isEmpty( PREFIX ) { message("====") message("==== NOTE: To override the installation path run: `qmake PREFIX=/custom/path'") message("==== (current installation path is `$${INSTALL_PREFIX}')") } else { INSTALL_PREFIX = $${PREFIX} message("====") message("==== install prefix set to `$${INSTALL_PREFIX}'") } # Setup the library installation directory exists( meego-release ) { ARCH = $$system(tail -n1 meego-release) } else { ARCH = $$system(uname -m) } contains( ARCH, x86_64 ) { INSTALL_LIBDIR = $${INSTALL_PREFIX}/lib64 } else { INSTALL_LIBDIR = $${INSTALL_PREFIX}/lib } # default library directory can be overriden by defining LIBDIR when # running qmake isEmpty( LIBDIR ) { message("====") message("==== NOTE: To override the library installation path run: `qmake LIBDIR=/custom/path'") message("==== (current installation path is `$${INSTALL_LIBDIR}')") } else { INSTALL_LIBDIR = $${LIBDIR} message("====") message("==== library install path set to `$${INSTALL_LIBDIR}'") } # Default directory for signond extensions _PLUGINS = $$system(pkg-config --variable=plugindir signon-plugins) isEmpty(_PLUGINS) { error("plugin directory not available through pkg-config") } else { SIGNON_PLUGINS_DIR = $$_PLUGINS } SIGNON_PLUGINS_DIR_QUOTED = \\\"$$SIGNON_PLUGINS_DIR\\\" include( coverage.pri ) signon-plugin-oauth2-0.19+14.04.20140305/coverage.pri0000644000015201777760000000346412305565653022357 0ustar pbusernogroup00000000000000# Coverage CONFIG(coverage) { LIBS += -lgcov QMAKE_CXXFLAGS += --coverage QMAKE_LDFLAGS += --coverage QMAKE_EXTRA_TARGETS += coverage cov QMAKE_EXTRA_TARGETS += clean-gcno clean-gcda coverage-html \ generate-coverage-html clean-coverage-html coverage-gcovr \ generate-gcovr generate-coverage-gcovr clean-coverage-gcovr clean-gcno.commands = \ "@echo Removing old coverage instrumentation"; \ "find -name '*.gcno' -print | xargs -r rm" clean-gcda.commands = \ "@echo Removing old coverage results"; \ "find -name '*.gcda' -print | xargs -r rm" coverage-html.depends = clean-gcda check generate-coverage-html generate-coverage-html.commands = \ "@echo Collecting coverage data"; \ "lcov --directory $${TOP_SRC_DIR} --capture --output-file coverage.info --no-checksum --compat-libtool"; \ "lcov --extract coverage.info \"*/src/*.cpp\" -o coverage.info"; \ "lcov --remove coverage.info \"moc_*.cpp\" -o coverage.info"; \ "LANG=C genhtml --prefix $${TOP_SRC_DIR} --output-directory coverage-html --title \"Code Coverage\" --legend --show-details coverage.info" clean-coverage-html.depends = clean-gcda clean-coverage-html.commands = \ "lcov --directory $${TOP_SRC_DIR} -z"; \ "rm -rf coverage.info coverage-html" coverage-gcovr.depends = clean-gcda check generate-coverage-gcovr generate-coverage-gcovr.commands = \ "@echo Generating coverage GCOVR report"; \ "gcovr -x -r $${TOP_SRC_DIR} -o $${TOP_SRC_DIR}/coverage.xml -e \".*/moc_.*\" -e \"tests/.*\" -e \".*\\.h\"" clean-coverage-gcovr.depends = clean-gcda clean-coverage-gcovr.commands = \ "rm -rf $${TOP_SRC_DIR}/coverage.xml" QMAKE_CLEAN += *.gcda *.gcno coverage.info coverage.xml } signon-plugin-oauth2-0.19+14.04.20140305/src/0000755000015201777760000000000012305566066020627 5ustar pbusernogroup00000000000000signon-plugin-oauth2-0.19+14.04.20140305/src/base-plugin.cpp0000644000015201777760000001076012305565653023546 0ustar pbusernogroup00000000000000/* * This file is part of oauth2 plugin * * Copyright (C) 2010 Nokia Corporation. * Copyright (C) 2012 Canonical Ltd. * * Contact: Alberto Mardegan * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * 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 St, Fifth Floor, Boston, MA * 02110-1301 USA */ #include "common.h" #include "base-plugin.h" #include "oauth2tokendata.h" #include #include #include #include #include #include using namespace SignOn; using namespace OAuth2PluginNS; namespace OAuth2PluginNS { class BasePluginPrivate { public: BasePluginPrivate(); ~BasePluginPrivate(); QNetworkAccessManager *m_networkAccessManager; QNetworkReply *m_reply; }; //Private } //namespace OAuth2PluginNS BasePluginPrivate::BasePluginPrivate(): m_networkAccessManager(0), m_reply(0) { } BasePluginPrivate::~BasePluginPrivate() { if (m_reply != 0) { m_reply->deleteLater(); m_reply = 0; } } BasePlugin::BasePlugin(QObject *parent): QObject(parent), d_ptr(new BasePluginPrivate()) { } BasePlugin::~BasePlugin() { delete d_ptr; d_ptr = 0; } void BasePlugin::cancel() { Q_D(BasePlugin); TRACE(); emit error(Error(Error::SessionCanceled)); if (d->m_reply) d->m_reply->abort(); } void BasePlugin::refresh(const SignOn::UiSessionData &data) { TRACE(); emit refreshed(data); } void BasePlugin::setNetworkAccessManager(QNetworkAccessManager *nam) { Q_D(BasePlugin); d->m_networkAccessManager = nam; } QNetworkAccessManager *BasePlugin::networkAccessManager() const { Q_D(const BasePlugin); return d->m_networkAccessManager; } void BasePlugin::postRequest(const QNetworkRequest &request, const QByteArray &data) { Q_D(BasePlugin); d->m_reply = d->m_networkAccessManager->post(request, data); connect(d->m_reply, SIGNAL(finished()), this, SLOT(onPostFinished())); connect(d->m_reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(handleNetworkError(QNetworkReply::NetworkError))); connect(d->m_reply, SIGNAL(sslErrors(QList)), this, SLOT(handleSslErrors(QList))); } void BasePlugin::serverReply(QNetworkReply *reply) { Q_UNUSED(reply); // Implemented by subclasses } void BasePlugin::onPostFinished() { Q_D(BasePlugin); QNetworkReply *reply = (QNetworkReply*)sender(); TRACE() << "Finished signal received"; if (reply->error() != QNetworkReply::NoError) { if (handleNetworkError(reply->error())) return; } if (d->m_reply) { d->m_reply->deleteLater(); d->m_reply = 0; } serverReply(reply); } bool BasePlugin::handleNetworkError(QNetworkReply::NetworkError err) { Q_D(BasePlugin); TRACE() << "error signal received:" << err; /* Has been handled by handleSslErrors already */ if (err == QNetworkReply::SslHandshakeFailedError) { return true; } /* HTTP errors handled in slots attached to signal */ if ((err > QNetworkReply::UnknownProxyError) && (err <= QNetworkReply::UnknownContentError)) { return false; } Error::ErrorType type = Error::Network; if (err <= QNetworkReply::UnknownNetworkError) type = Error::NoConnection; QString errorString = ""; if (d->m_reply) { errorString = d->m_reply->errorString(); d->m_reply->deleteLater(); d->m_reply = 0; } emit error(Error(type, errorString)); return true; } void BasePlugin::handleSslErrors(QList errorList) { Q_D(BasePlugin); TRACE() << "Error: " << errorList; QString errorString = ""; foreach (QSslError error, errorList) { errorString += error.errorString() + ";"; } if (d->m_reply) { d->m_reply->deleteLater(); d->m_reply = 0; } emit error(Error(Error::Ssl, errorString)); } signon-plugin-oauth2-0.19+14.04.20140305/src/plugin.h0000644000015201777760000000351212305565653022300 0ustar pbusernogroup00000000000000/* * This file is part of oauth2 plugin * * Copyright (C) 2010 Nokia Corporation. * Copyright (C) 2012 Canonical Ltd. * * Contact: Alberto Mardegan * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * 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 St, Fifth Floor, Boston, MA * 02110-1301 USA */ #ifndef SIGNON_PLUGIN_OAUTH2_MAIN #define SIGNON_PLUGIN_OAUTH2_MAIN #include #include #include #include class OAuth2PluginTest; class QNetworkAccessManager; namespace OAuth2PluginNS { class BasePlugin; /*! * @class Plugin * OAuth authentication plugin. */ class PluginPrivate; class Plugin: public AuthPluginInterface { Q_OBJECT Q_INTERFACES(AuthPluginInterface); friend class ::OAuth2PluginTest; public: Plugin(QObject *parent = 0); ~Plugin(); public Q_SLOTS: QString type() const; QStringList mechanisms() const; void cancel(); void process(const SignOn::SessionData &inData, const QString &mechanism = 0); void userActionFinished(const SignOn::UiSessionData &data); void refresh(const SignOn::UiSessionData &data); private: BasePlugin *impl; QNetworkAccessManager *m_networkAccessManager; }; } //namespace OAuth2PluginNS #endif // SIGNON_PLUGIN_OAUTH2_MAIN signon-plugin-oauth2-0.19+14.04.20140305/src/oauth2data.h0000644000015201777760000000530512305565653023040 0ustar pbusernogroup00000000000000/* * This file is part of oauth2 plugin * * Copyright (C) 2010 Nokia Corporation. * * Contact: Alberto Mardegan * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * 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 St, Fifth Floor, Boston, MA * 02110-1301 USA */ #ifndef OAUTH2DATA_H #define OAUTH2DATA_H #include class OAuth2PluginTest; namespace OAuth2PluginNS { /*! * @class OAuth2PluginData * Data container to hold values for OAuth 2.0 authentication session. */ class OAuth2PluginData : public SignOn::SessionData { friend class ::OAuth2PluginTest; public: /*! * hostname of the server */ SIGNON_SESSION_DECLARE_PROPERTY(QString, Host); /*! * Authorization endpoint of the server */ SIGNON_SESSION_DECLARE_PROPERTY(QString, AuthPath); /*! * token endpoint of the server */ SIGNON_SESSION_DECLARE_PROPERTY(QString, TokenPath); /*! * Application client ID and secret */ SIGNON_SESSION_DECLARE_PROPERTY(QString, ClientId); SIGNON_SESSION_DECLARE_PROPERTY(QString, ClientSecret); /*! * redirection URI */ SIGNON_SESSION_DECLARE_PROPERTY(QString, RedirectUri); /*! * access scope */ SIGNON_SESSION_DECLARE_PROPERTY(QStringList, Scope); /*! * response type */ SIGNON_SESSION_DECLARE_PROPERTY(QStringList, ResponseType); /*! * Not in the OAuth2 standard: display type */ SIGNON_SESSION_DECLARE_PROPERTY(QString, Display); }; class OAuth2PluginTokenData : public SignOn::SessionData { public: /*! * Access token received from the server */ SIGNON_SESSION_DECLARE_PROPERTY(QString, AccessToken); /*! * Refresh token received from the server */ SIGNON_SESSION_DECLARE_PROPERTY(QString, RefreshToken); /*! * Access token expiry time */ SIGNON_SESSION_DECLARE_PROPERTY(int, ExpiresIn); }; } // namespace OAuth2PluginNS #endif // OAUTH2DATA_H signon-plugin-oauth2-0.19+14.04.20140305/src/oauth2plugin.cpp0000644000015201777760000005652612305565653023773 0ustar pbusernogroup00000000000000/* * This file is part of oauth2 plugin * * Copyright (C) 2010 Nokia Corporation. * Copyright (C) 2012 Canonical Ltd. * * Contact: Alberto Mardegan * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * 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 St, Fifth Floor, Boston, MA * 02110-1301 USA */ #include "common.h" #include "oauth2plugin.h" #include "oauth2tokendata.h" #include #include #include #include #define USE_LIBQJSON (QT_VERSION < QT_VERSION_CHECK(5, 0, 0)) #if USE_LIBQJSON #include #else #include #endif using namespace SignOn; using namespace OAuth2PluginNS; namespace OAuth2PluginNS { const QString WEB_SERVER = QString("web_server"); const QString USER_AGENT = QString("user_agent"); const QString TOKEN = QString("Token"); const QString EXPIRY = QString("Expiry"); const QString SCOPES = QString("Scopes"); const int HTTP_STATUS_OK = 200; const QString AUTH_CODE = QString("code"); const QString REDIRECT_URI = QString("redirect_uri"); const QString RESPONSE_TYPE = QString("response_type"); const QString USERNAME = QString("username"); const QString PASSWORD = QString("password"); const QString ASSERTION_TYPE = QString("assertion_type"); const QString ASSERTION = QString("assertion"); const QString ACCESS_TOKEN = QString("access_token"); const QString DISPLAY = QString("display"); const QString EXPIRES_IN = QString("expires_in"); const QString TIMESTAMP = QString("timestamp"); const QString GRANT_TYPE = QString("grant_type"); const QString AUTHORIZATION_CODE = QString("authorization_code"); const QString USER_BASIC = QString("user_basic"); const QString CLIENT_ID = QString("client_id"); const QString CLIENT_SECRET = QString("client_secret"); const QString REFRESH_TOKEN = QString("refresh_token"); const QString AUTH_ERROR = QString("error"); const QByteArray CONTENT_TYPE = QByteArray("Content-Type"); const QByteArray CONTENT_APP_URLENCODED = QByteArray("application/x-www-form-urlencoded"); const QByteArray CONTENT_APP_JSON = QByteArray("application/json"); const QByteArray CONTENT_TEXT_PLAIN = QByteArray("text/plain"); class OAuth2PluginPrivate { public: OAuth2PluginPrivate(): m_grantType(GrantType::Undefined) { TRACE(); // Initialize randomizer qsrand(QTime::currentTime().msec()); } ~OAuth2PluginPrivate() { TRACE(); } QString m_mechanism; OAuth2PluginData m_oauth2Data; QVariantMap m_tokens; QString m_key; QString m_username; QString m_password; GrantType::e m_grantType; }; //Private } //namespace OAuth2PluginNS OAuth2Plugin::OAuth2Plugin(QObject *parent): BasePlugin(parent), d_ptr(new OAuth2PluginPrivate()) { TRACE(); } OAuth2Plugin::~OAuth2Plugin() { TRACE(); delete d_ptr; d_ptr = 0; } QStringList OAuth2Plugin::mechanisms() { QStringList res = QStringList(); res.append(WEB_SERVER); res.append(USER_AGENT); return res; } void OAuth2Plugin::sendOAuth2AuthRequest() { Q_D(OAuth2Plugin); QUrl url(QString("https://%1/%2").arg(d->m_oauth2Data.Host()).arg(d->m_oauth2Data.AuthPath())); url.addQueryItem(CLIENT_ID, d->m_oauth2Data.ClientId()); url.addQueryItem(REDIRECT_URI, d->m_oauth2Data.RedirectUri()); if (!d->m_oauth2Data.ResponseType().isEmpty()) { url.addQueryItem(RESPONSE_TYPE, d->m_oauth2Data.ResponseType().join(" ")); } if (!d->m_oauth2Data.Display().isEmpty()) { url.addQueryItem(DISPLAY, d->m_oauth2Data.Display()); } url.addQueryItem(QString("type"), d->m_mechanism); if (!d->m_oauth2Data.Scope().empty()) { QString separator = QLatin1String(" "); /* The scopes separator defined in the OAuth 2.0 spec is a space; * unfortunately facebook accepts only a comma, so we have to treat * it as a special case. See: * http://bugs.developers.facebook.net/show_bug.cgi?id=11120 */ if (d->m_oauth2Data.Host().contains(QLatin1String("facebook.com"))) { separator = QLatin1String(","); } // Passing list of scopes url.addQueryItem(QString("scope"), d->m_oauth2Data.Scope().join(separator)); } TRACE() << "Url = " << url.toString(); SignOn::UiSessionData uiSession; uiSession.setOpenUrl(url.toString()); if (!d->m_oauth2Data.RedirectUri().isEmpty()) uiSession.setFinalUrl(d->m_oauth2Data.RedirectUri()); /* add username and password, for fields initialization (the * decision on whether to actually use them is up to the signon UI */ uiSession.setUserName(d->m_username); uiSession.setSecret(d->m_password); emit userActionRequired(uiSession); } bool OAuth2Plugin::validateInput(const SignOn::SessionData &inData, const QString &mechanism) { OAuth2PluginData input = inData.data(); if (input.Host().isEmpty() || input.ClientId().isEmpty() || input.RedirectUri().isEmpty() || input.AuthPath().isEmpty()) return false; if (mechanism == WEB_SERVER) { /* According to the specs, the client secret is also required; however, * some services do not require it, see for instance point 8 from * http://msdn.microsoft.com/en-us/library/live/hh243647.aspx#authcodegrant */ if (input.TokenPath().isEmpty()) return false; } return true; } bool OAuth2Plugin::respondWithStoredToken(const QVariantMap &token, const QStringList &scopes) { int timeToExpiry = 0; // if the token is expired, ignore it if (token.contains(EXPIRY)) { timeToExpiry = token.value(EXPIRY).toUInt() + token.value(TIMESTAMP).toUInt() - QDateTime::currentDateTime().toTime_t(); if (timeToExpiry < 0) { TRACE() << "Stored token is expired"; return false; } } /* if the stored token does not contain all the requested scopes, * we cannot use it now */ if (!scopes.isEmpty()) { if (!token.contains(SCOPES)) return false; QSet cachedScopes = token.value(SCOPES).toStringList().toSet(); if (!cachedScopes.contains(scopes.toSet())) return false; } if (token.contains(TOKEN)) { OAuth2PluginTokenData response; response.setAccessToken(token.value(TOKEN).toByteArray()); if (token.contains(REFRESH_TOKEN)) { response.setRefreshToken(token.value(REFRESH_TOKEN).toByteArray()); } if (token.contains(EXPIRY)) { response.setExpiresIn(timeToExpiry); } TRACE() << "Responding with stored token"; emit result(response); return true; } return false; } void OAuth2Plugin::process(const SignOn::SessionData &inData, const QString &mechanism) { Q_D(OAuth2Plugin); if ((!mechanism.isEmpty()) && (!mechanisms().contains(mechanism))) { emit error(Error(Error::MechanismNotAvailable)); return; } if (!validateInput(inData, mechanism)) { TRACE() << "Invalid parameters passed"; emit error(Error(Error::MissingData)); return; } d->m_mechanism = mechanism; d->m_oauth2Data = inData.data(); d->m_key = d->m_oauth2Data.ClientId(); //get stored data OAuth2TokenData tokens = inData.data(); d->m_tokens = tokens.Tokens(); if (inData.UiPolicy() == RequestPasswordPolicy) { //remove old token for given Key TRACE() << d->m_tokens; d->m_tokens.remove(d->m_key); OAuth2TokenData tokens; tokens.setTokens(d->m_tokens); emit store(tokens); TRACE() << d->m_tokens; } //get provided token data if specified if (!tokens.ProvidedTokens().isEmpty()) { //check that the provided tokens contain required values OAuth2PluginTokenData providedTokens = SignOn::SessionData(tokens.ProvidedTokens()) .data(); if (providedTokens.AccessToken().isEmpty() || providedTokens.RefreshToken().isEmpty()) { //note: we don't check ExpiresIn as it might not be required TRACE() << "Invalid provided tokens data - continuing normal process flow"; } else { TRACE() << "Storing provided tokens"; OAuth2PluginTokenData storeTokens; storeTokens.setAccessToken(providedTokens.AccessToken()); storeTokens.setRefreshToken(providedTokens.RefreshToken()); storeTokens.setExpiresIn(providedTokens.ExpiresIn()); storeResponse(storeTokens); } } QVariant tokenVar = d->m_tokens.value(d->m_key); QVariantMap storedData; if (tokenVar.canConvert()) { storedData = tokenVar.value(); if (respondWithStoredToken(storedData, d->m_oauth2Data.Scope())) { return; } } /* Get username and password; the plugin doesn't use them, but forwards * them to the signon UI */ d->m_username = inData.UserName(); d->m_password = inData.Secret(); if (mechanism == WEB_SERVER || mechanism == USER_AGENT) { if (mechanism == WEB_SERVER && storedData.contains(REFRESH_TOKEN) && !storedData[REFRESH_TOKEN].toString().isEmpty()) { /* If we have a refresh token, use it to get a renewed * access token */ refreshOAuth2Token(storedData[REFRESH_TOKEN].toString()); } else { sendOAuth2AuthRequest(); } } else { emit error(Error(Error::MechanismNotAvailable)); } } QString OAuth2Plugin::urlEncode(QString strData) { return QUrl::toPercentEncoding(strData).constData(); } void OAuth2Plugin::userActionFinished(const SignOn::UiSessionData &data) { Q_D(OAuth2Plugin); TRACE(); if (data.QueryErrorCode() != QUERY_ERROR_NONE) { TRACE() << "userActionFinished with error: " << data.QueryErrorCode(); if (data.QueryErrorCode() == QUERY_ERROR_CANCELED) emit error(Error(Error::SessionCanceled, QLatin1String("Cancelled by user"))); else emit error(Error(Error::UserInteraction, QString("userActionFinished error: ") + QString::number(data.QueryErrorCode()))); return; } TRACE() << data.UrlResponse(); // Checking if authorization server granted access QUrl url = QUrl(data.UrlResponse()); if (url.hasQueryItem(AUTH_ERROR)) { TRACE() << "Server denied access permission"; emit error(Error(Error::NotAuthorized, url.queryItemValue(AUTH_ERROR))); return; } if (d->m_mechanism == USER_AGENT) { // Response should contain the access token OAuth2PluginTokenData respData; QString fragment; if (url.hasFragment()) { fragment = url.fragment(); QStringList list = fragment.split(QRegExp("&|="), QString::SkipEmptyParts); for (int i = 1; i < list.count(); i += 2) { if (list.at(i - 1) == ACCESS_TOKEN) { respData.setAccessToken(list.at(i)); } else if (list.at(i - 1) == EXPIRES_IN) { respData.setExpiresIn(QString(list.at(i)).toInt()); } else if (list.at(i - 1) == REFRESH_TOKEN) { respData.setRefreshToken(list.at(i)); } } if (respData.AccessToken().isEmpty()) { emit error(Error(Error::NotAuthorized, QString("Access token not present"))); } else { storeResponse(respData); emit result(respData); } } else { emit error(Error(Error::NotAuthorized, QString("Access token not present"))); } } else if (d->m_mechanism == WEB_SERVER) { // Access grant can be one of the floolwing types // 1. Authorization code (code, redirect_uri) // 2. Resource owner credentials (username, password) // 3. Assertion (assertion_type, assertion) // 4. Refresh Token (refresh_token) QUrl newUrl; if (url.hasQueryItem(AUTH_CODE)) { QString code = url.queryItemValue(AUTH_CODE); newUrl.addQueryItem(GRANT_TYPE, AUTHORIZATION_CODE); newUrl.addQueryItem(CLIENT_ID, d->m_oauth2Data.ClientId()); newUrl.addQueryItem(CLIENT_SECRET, d->m_oauth2Data.ClientSecret()); newUrl.addQueryItem(AUTH_CODE, code); newUrl.addQueryItem(REDIRECT_URI, d->m_oauth2Data.RedirectUri()); sendOAuth2PostRequest(newUrl.encodedQuery(), GrantType::AuthorizationCode); } else if (url.hasQueryItem(USERNAME) && url.hasQueryItem(PASSWORD)) { QString username = url.queryItemValue(USERNAME); QString password = url.queryItemValue(PASSWORD); newUrl.addQueryItem(GRANT_TYPE, USER_BASIC); newUrl.addQueryItem(CLIENT_ID, d->m_oauth2Data.ClientId()); newUrl.addQueryItem(CLIENT_SECRET, d->m_oauth2Data.ClientSecret()); newUrl.addQueryItem(USERNAME, username); newUrl.addQueryItem(PASSWORD, password); sendOAuth2PostRequest(newUrl.encodedQuery(), GrantType::UserBasic); } else if (url.hasQueryItem(ASSERTION_TYPE) && url.hasQueryItem(ASSERTION)) { QString assertion_type = url.queryItemValue(ASSERTION_TYPE); QString assertion = url.queryItemValue(ASSERTION); newUrl.addQueryItem(GRANT_TYPE, ASSERTION); newUrl.addQueryItem(CLIENT_ID, d->m_oauth2Data.ClientId()); newUrl.addQueryItem(CLIENT_SECRET, d->m_oauth2Data.ClientSecret()); newUrl.addQueryItem(ASSERTION_TYPE, assertion_type); newUrl.addQueryItem(ASSERTION, assertion); sendOAuth2PostRequest(newUrl.encodedQuery(), GrantType::Assertion); } else if (url.hasQueryItem(REFRESH_TOKEN)) { QString refresh_token = url.queryItemValue(REFRESH_TOKEN); refreshOAuth2Token(refresh_token); } else { emit error(Error(Error::NotAuthorized, QString("Access grant not present"))); } } } // Method to handle responses for OAuth 2.0 requests void OAuth2Plugin::serverReply(QNetworkReply *reply) { QByteArray replyContent = reply->readAll(); TRACE() << replyContent; // Handle error responses QVariant statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute); TRACE() << statusCode; if (statusCode != HTTP_STATUS_OK) { handleOAuth2Error(replyContent); return; } // Handling 200 OK response (HTTP_STATUS_OK) WITH content if (reply->hasRawHeader(CONTENT_TYPE)) { // Handling application/json content type if (reply->rawHeader(CONTENT_TYPE).startsWith(CONTENT_APP_JSON)) { TRACE()<< "application/json content received"; QVariantMap map = parseJSONReply(replyContent); QByteArray accessToken = map["access_token"].toByteArray(); QVariant expiresIn = map["expires_in"]; QByteArray refreshToken = map["refresh_token"].toByteArray(); if (accessToken.isEmpty()) { TRACE()<< "Access token is empty"; emit error(Error(Error::NotAuthorized, QString("Access token is empty"))); } else { OAuth2PluginTokenData response; response.setAccessToken(accessToken); response.setRefreshToken(refreshToken); response.setExpiresIn(expiresIn.toInt()); storeResponse(response); emit result(response); } } // Added to test with facebook Graph API's (handling text/plain content type) else if (reply->rawHeader(CONTENT_TYPE).startsWith(CONTENT_TEXT_PLAIN) || reply->rawHeader(CONTENT_TYPE).startsWith(CONTENT_APP_URLENCODED)) { TRACE()<< reply->rawHeader(CONTENT_TYPE) << "content received"; QMap map = parseTextReply(replyContent); QByteArray accessToken = map["access_token"].toAscii(); QByteArray expiresIn = map["expires"].toAscii(); QByteArray refreshToken = map["refresh_token"].toAscii(); if (accessToken.isEmpty()) { TRACE()<< "Access token is empty"; emit error(Error(Error::NotAuthorized, QString("Access token is empty"))); } else { OAuth2PluginTokenData response; response.setAccessToken(accessToken); response.setRefreshToken(refreshToken); response.setExpiresIn(expiresIn.toInt()); storeResponse(response); emit result(response); } } else { TRACE()<< "Unsupported content type received: " << reply->rawHeader(CONTENT_TYPE); emit error(Error(Error::OperationFailed, QString("Unsupported content type received"))); } } // Handling 200 OK response (HTTP_STATUS_OK) WITHOUT content else { TRACE()<< "Content is not present"; emit error(Error(Error::OperationFailed, QString("Content missing"))); } } void OAuth2Plugin::handleOAuth2Error(const QByteArray &reply) { Q_D(OAuth2Plugin); TRACE(); QVariantMap map = parseJSONReply(reply); QByteArray errorString = map["error"].toByteArray(); if (!errorString.isEmpty()) { Error::ErrorType type = Error::OperationFailed; if (errorString == QByteArray("incorrect_client_credentials")) { type = Error::InvalidCredentials; } else if (errorString == QByteArray("redirect_uri_mismatch")) { type = Error::InvalidCredentials; } else if (errorString == QByteArray("bad_authorization_code")) { type = Error::InvalidCredentials; } else if (errorString == QByteArray("invalid_client_credentials")) { type = Error::InvalidCredentials; } else if (errorString == QByteArray("unauthorized_client")) { type = Error::NotAuthorized; } else if (errorString == QByteArray("invalid_assertion")) { type = Error::InvalidCredentials; } else if (errorString == QByteArray("unknown_format")) { type = Error::InvalidQuery; } else if (errorString == QByteArray("authorization_expired")) { type = Error::InvalidCredentials; } else if (errorString == QByteArray("multiple_credentials")) { type = Error::InvalidQuery; } else if (errorString == QByteArray("invalid_user_credentials")) { type = Error::InvalidCredentials; } else if (errorString == QByteArray("invalid_grant")) { if (d->m_grantType == GrantType::RefreshToken) { /* The refresh token has expired; try once more using * the web-based authentication flow. */ TRACE() << "Authenticating without refresh token"; sendOAuth2AuthRequest(); return; } type = Error::NotAuthorized; } TRACE() << "Error Emitted"; emit error(Error(type, errorString)); return; } // Added to work with facebook Graph API's errorString = map["message"].toByteArray(); TRACE() << "Error Emitted"; emit error(Error(Error::OperationFailed, errorString)); } void OAuth2Plugin::refreshOAuth2Token(const QString &refreshToken) { Q_D(OAuth2Plugin); TRACE() << refreshToken; QUrl url; url.addQueryItem(GRANT_TYPE, REFRESH_TOKEN); url.addQueryItem(CLIENT_ID, d->m_oauth2Data.ClientId()); if (!d->m_oauth2Data.ClientSecret().isEmpty()) { url.addQueryItem(CLIENT_SECRET, d->m_oauth2Data.ClientSecret()); } url.addQueryItem(REFRESH_TOKEN, refreshToken); sendOAuth2PostRequest(url.encodedQuery(), GrantType::RefreshToken); } void OAuth2Plugin::sendOAuth2PostRequest(const QByteArray &postData, GrantType::e grantType) { Q_D(OAuth2Plugin); TRACE(); QUrl url(QString("https://%1/%2").arg(d->m_oauth2Data.Host()) .arg(d->m_oauth2Data.TokenPath())); QNetworkRequest request(url); request.setRawHeader(CONTENT_TYPE, CONTENT_APP_URLENCODED); d->m_grantType = grantType; TRACE() << "Query string = " << postData; postRequest(request, postData); } void OAuth2Plugin::storeResponse(const OAuth2PluginTokenData &response) { Q_D(OAuth2Plugin); OAuth2TokenData tokens; QVariantMap token; token.insert(TOKEN, response.AccessToken()); /* Do not overwrite the refresh token with an empty one: when using the * refresh token to obtain a new access token, the replie could not contain * a refresh token (or contain an empty one). * In such cases, we should re-store the old refresh token. */ QString refreshToken; if (response.RefreshToken().isEmpty()) { QVariant tokenVar = d->m_tokens.value(d->m_key); QVariantMap storedData; if (tokenVar.canConvert()) { storedData = tokenVar.value(); if (storedData.contains(REFRESH_TOKEN) && !storedData[REFRESH_TOKEN].toString().isEmpty()) { refreshToken = storedData[REFRESH_TOKEN].toString(); } } } else { refreshToken = response.RefreshToken(); } token.insert(REFRESH_TOKEN, refreshToken); token.insert(EXPIRY, response.ExpiresIn()); token.insert(TIMESTAMP, QDateTime::currentDateTime().toTime_t()); token.insert(SCOPES, d->m_oauth2Data.Scope()); d->m_tokens.insert(d->m_key, QVariant::fromValue(token)); tokens.setTokens(d->m_tokens); Q_EMIT store(tokens); TRACE() << d->m_tokens; } const QVariantMap OAuth2Plugin::parseJSONReply(const QByteArray &reply) { TRACE(); bool ok = false; #if USE_LIBQJSON QJson::Parser parser; QVariant tree = parser.parse(reply, &ok); #else QJsonDocument doc = QJsonDocument::fromJson(reply); ok = !doc.isEmpty(); QVariant tree = doc.toVariant(); #endif if (ok) { return tree.toMap(); } return QVariantMap(); } const QMap OAuth2Plugin::parseTextReply(const QByteArray &reply) { TRACE(); QMap map; QList items = reply.split('&'); foreach (QByteArray item, items) { int idx = item.indexOf("="); if (idx > -1) { map.insert(item.left(idx), QByteArray::fromPercentEncoding(item.mid(idx + 1))); } } return map; } signon-plugin-oauth2-0.19+14.04.20140305/src/oauth1plugin.cpp0000644000015201777760000006003112305565653023754 0ustar pbusernogroup00000000000000/* * This file is part of oauth2 plugin * * Copyright (C) 2010 Nokia Corporation. * Copyright (C) 2012 Canonical Ltd. * * Contact: Alberto Mardegan * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * 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 St, Fifth Floor, Boston, MA * 02110-1301 USA */ #include "common.h" #include "oauth1data.h" #include "oauth1plugin.h" #include "oauth2tokendata.h" #include #include #include #include #include using namespace SignOn; using namespace OAuth2PluginNS; namespace OAuth2PluginNS { // Enum for OAuth 1.0 POST request type typedef enum { OAUTH1_POST_REQUEST_INVALID = 0, OAUTH1_POST_REQUEST_TOKEN, OAUTH1_POST_ACCESS_TOKEN } OAuth1RequestType; const QString HMAC_SHA1 = QString("HMAC-SHA1"); const QString PLAINTEXT = QString("PLAINTEXT"); const QString RSA_SHA1 = QString("RSA-SHA1"); const QString EXPIRY = QString ("Expiry"); const QString USER_ID = QString("user_id"); const QString SCREEN_NAME = QString("screen_name"); const QString FORCE_LOGIN = QString("force_login"); const int HTTP_STATUS_OK = 200; const QString TIMESTAMP = QString("timestamp"); const QString AUTH_ERROR = QString("error"); const QString EQUAL = QString("="); const QString AMPERSAND = QString("&"); const QString EQUAL_WITH_QUOTES = QString("%1=\"%2\""); const QString DELIMITER = QString(", "); const QString SPACE = QString(" "); const QString OAUTH = QString("OAuth"); const QString OAUTH_REALM = QString("realm"); const QString OAUTH_CALLBACK = QString("oauth_callback"); const QString OAUTH_CONSUMERKEY = QString("oauth_consumer_key"); const QString OAUTH_NONCE = QString("oauth_nonce"); const QString OAUTH_TIMESTAMP = QString("oauth_timestamp"); const QString OAUTH_SIGNATURE = QString("oauth_signature"); const QString OAUTH_SIGNATURE_METHOD = QString("oauth_signature_method"); const QString OAUTH_VERSION = QString("oauth_version"); const QString OAUTH_VERSION_1 = QString("1.0"); const QString OAUTH_TOKEN = QString("oauth_token"); const QString OAUTH_TOKEN_SECRET = QString("oauth_token_secret"); const QString OAUTH_VERIFIER = QString("oauth_verifier"); const QString OAUTH_PROBLEM = QString("oauth_problem"); const QString OAUTH_USER_REFUSED = QString("user_refused"); const QString OAUTH_PERMISSION_DENIED = QString("permission_denied"); const QByteArray CONTENT_TYPE = QByteArray("Content-Type"); const QByteArray CONTENT_APP_URLENCODED = QByteArray("application/x-www-form-urlencoded"); const QByteArray CONTENT_TEXT_PLAIN = QByteArray("text/plain"); const QByteArray CONTENT_TEXT_HTML = QByteArray("text/html"); class OAuth1PluginPrivate { public: OAuth1PluginPrivate() { TRACE(); // Initialize randomizer qsrand(QTime::currentTime().msec()); } ~OAuth1PluginPrivate() { TRACE(); } QString m_mechanism; OAuth1PluginData m_oauth1Data; QByteArray m_oauth1Token; QByteArray m_oauth1TokenSecret; QString m_oauth1UserId; QString m_oauth1ScreenName; QString m_oauth1TokenVerifier; OAuth1RequestType m_oauth1RequestType; QVariantMap m_tokens; QString m_key; QString m_username; QString m_password; }; //Private } //namespace OAuth2PluginNS OAuth1Plugin::OAuth1Plugin(QObject *parent): BasePlugin(parent), d_ptr(new OAuth1PluginPrivate()) { TRACE(); } OAuth1Plugin::~OAuth1Plugin() { TRACE(); delete d_ptr; d_ptr = 0; } QStringList OAuth1Plugin::mechanisms() { QStringList res = QStringList(); res.append(HMAC_SHA1); res.append(PLAINTEXT); return res; } void OAuth1Plugin::sendOAuth1AuthRequest(const QString &captchaUrl) { Q_D(OAuth1Plugin); QUrl url(d->m_oauth1Data.AuthorizationEndpoint()); url.addQueryItem(OAUTH_TOKEN, d->m_oauth1Token); if (!d->m_oauth1ScreenName.isEmpty()) { // Prefill username for Twitter url.addQueryItem(SCREEN_NAME, d->m_oauth1ScreenName); url.addQueryItem(FORCE_LOGIN, d->m_oauth1ScreenName); } TRACE() << "URL = " << url.toString(); SignOn::UiSessionData uiSession; uiSession.setOpenUrl(url.toString()); if (d->m_oauth1Data.Callback() != "oob") uiSession.setFinalUrl(d->m_oauth1Data.Callback()); if (!captchaUrl.isEmpty()) { uiSession.setCaptchaUrl(captchaUrl); } /* add username and password, for fields initialization (the * decision on whether to actually use them is up to the signon UI */ uiSession.setUserName(d->m_username); uiSession.setSecret(d->m_password); emit userActionRequired(uiSession); } bool OAuth1Plugin::validateInput(const SignOn::SessionData &inData, const QString &mechanism) { Q_UNUSED(mechanism); OAuth1PluginData input = inData.data(); if (input.AuthorizationEndpoint().isEmpty() || input.ConsumerKey().isEmpty() || input.ConsumerSecret().isEmpty() || input.Callback().isEmpty() || input.TokenEndpoint().isEmpty() || input.RequestEndpoint().isEmpty()){ return false; } return true; } bool OAuth1Plugin::respondWithStoredToken(const QVariantMap &token, const QString &mechanism) { int timeToExpiry = 0; // if the token is expired, ignore it if (token.contains(EXPIRY)) { timeToExpiry = token.value(EXPIRY).toUInt() + token.value(TIMESTAMP).toUInt() - QDateTime::currentDateTime().toTime_t(); if (timeToExpiry < 0) { TRACE() << "Stored token is expired"; return false; } } if (mechanism == HMAC_SHA1 || mechanism == RSA_SHA1 || mechanism == PLAINTEXT) { if (token.contains(OAUTH_TOKEN) && token.contains(OAUTH_TOKEN_SECRET)) { OAuth1PluginTokenData response = oauth1responseFromMap(token); emit result(response); return true; } } return false; } void OAuth1Plugin::process(const SignOn::SessionData &inData, const QString &mechanism) { Q_D(OAuth1Plugin); if (!validateInput(inData, mechanism)) { TRACE() << "Invalid parameters passed"; emit error(Error(Error::MissingData)); return; } d->m_mechanism = mechanism; d->m_key = inData.data().ConsumerKey(); //get stored data OAuth2TokenData tokens = inData.data(); d->m_tokens = tokens.Tokens(); if (inData.UiPolicy() == RequestPasswordPolicy) { //remove old token for given Key TRACE() << d->m_tokens; d->m_tokens.remove(d->m_key); OAuth2TokenData tokens; tokens.setTokens(d->m_tokens); emit store(tokens); TRACE() << d->m_tokens; } //get provided token data if specified if (!tokens.ProvidedTokens().isEmpty()) { //check that the provided tokens contain required values OAuth1PluginTokenData providedTokens = SignOn::SessionData(tokens.ProvidedTokens()) .data(); if (providedTokens.AccessToken().isEmpty() || providedTokens.TokenSecret().isEmpty()) { //note: we don't check UserId or ScreenName as it might not be required TRACE() << "Invalid provided tokens data - continuing normal process flow"; } else { TRACE() << "Storing provided tokens"; QVariantMap storeTokens; storeTokens.insert(OAUTH_TOKEN, providedTokens.AccessToken()); storeTokens.insert(OAUTH_TOKEN_SECRET, providedTokens.TokenSecret()); if (!providedTokens.UserId().isNull()) storeTokens.insert(USER_ID, providedTokens.UserId()); if (!providedTokens.ScreenName().isNull()) storeTokens.insert(SCREEN_NAME, providedTokens.ScreenName()); d->m_oauth1Token = providedTokens.AccessToken().toAscii(); d->m_oauth1TokenSecret = providedTokens.TokenSecret().toAscii(); d->m_oauth1UserId = providedTokens.UserId().toAscii(); d->m_oauth1ScreenName = providedTokens.ScreenName().toAscii(); OAuth2TokenData tokens; d->m_tokens.insert(d->m_key, QVariant::fromValue(storeTokens)); tokens.setTokens(d->m_tokens); emit store(tokens); } } QVariant tokenVar = d->m_tokens.value(d->m_key); QVariantMap storedData; if (tokenVar.canConvert()) { storedData = tokenVar.value(); if (respondWithStoredToken(storedData, mechanism)) { return; } } /* Get username and password; the plugin doesn't use them, but forwards * them to the signon UI */ d->m_username = inData.UserName(); d->m_password = inData.Secret(); d->m_oauth1Token.clear(); d->m_oauth1TokenSecret.clear(); d->m_oauth1TokenVerifier.clear(); d->m_oauth1RequestType = OAUTH1_POST_REQUEST_INVALID; d->m_oauth1Data = inData.data(); d->m_oauth1RequestType = OAUTH1_POST_REQUEST_TOKEN; if (!d->m_oauth1Data.UserName().isEmpty()) { d->m_oauth1ScreenName = d->m_oauth1Data.UserName(); //qDebug() << "Found username:" << d->m_oauth1ScreenName; } sendOAuth1PostRequest(); } QString OAuth1Plugin::urlEncode(QString strData) { return QUrl::toPercentEncoding(strData).constData(); } // Create a HMAC-SHA1 signature QByteArray OAuth1Plugin::hashHMACSHA1(const QByteArray &baseSignatureString, const QByteArray &secret) { // The algorithm is defined in RFC 2104 int blockSize = 64; QByteArray key(baseSignatureString); QByteArray opad(blockSize, 0x5c); QByteArray ipad(blockSize, 0x36); // If key size is too large, compute the hash if (key.size() > blockSize) { key = QCryptographicHash::hash(key, QCryptographicHash::Sha1); } // If too small, pad with 0x00 if (key.size() < blockSize) { key += QByteArray(blockSize - key.size(), 0x00); } // Compute the XOR operations for (int i=0; i <= key.size() - 1; i++) { ipad[i] = (char) (ipad[i] ^ key[i]); opad[i] = (char) (opad[i] ^ key[i]); } // Append the data to ipad ipad += secret; // Hash sha1 of ipad and append the data to opad opad += QCryptographicHash::hash(ipad, QCryptographicHash::Sha1); // Return array contains the result of HMAC-SHA1 return QCryptographicHash::hash(opad, QCryptographicHash::Sha1); } QByteArray OAuth1Plugin::constructSignatureBaseString(const QString &aUrl, const OAuth1PluginData &inData, const QString ×tamp, const QString &nonce) { Q_D(OAuth1Plugin); QMap oAuthHeaderMap; QUrl fullUrl(aUrl); // Constructing the base string as per RFC 5849. Sec 3.4.1 QList > queryItems = fullUrl.queryItems(); QPair queryItem; foreach (queryItem, queryItems) { oAuthHeaderMap[queryItem.first] = queryItem.second; } if (!inData.Callback().isEmpty()) { oAuthHeaderMap[OAUTH_CALLBACK] = inData.Callback(); } oAuthHeaderMap[OAUTH_CONSUMERKEY] = inData.ConsumerKey(); oAuthHeaderMap[OAUTH_NONCE] = nonce; oAuthHeaderMap[OAUTH_SIGNATURE_METHOD] = d->m_mechanism; oAuthHeaderMap[OAUTH_TIMESTAMP] = timestamp; if (!d->m_oauth1Token.isEmpty()) { oAuthHeaderMap[OAUTH_TOKEN] = d->m_oauth1Token; } if (!d->m_oauth1TokenVerifier.isEmpty()) { oAuthHeaderMap[OAUTH_VERIFIER] = d->m_oauth1TokenVerifier; } oAuthHeaderMap[OAUTH_VERSION] = OAUTH_VERSION_1; QString oAuthHeaderString; QMap::iterator i; bool first = true; for (i = oAuthHeaderMap.begin(); i != oAuthHeaderMap.end(); ++i) { if(!first) { oAuthHeaderString.append(AMPERSAND); } else { first = false; } oAuthHeaderString.append(urlEncode(i.key()) + EQUAL + urlEncode(i.value())); } QString urlWithHostAndPath = fullUrl.toString(QUrl::RemoveUserInfo | QUrl::RemoveQuery | QUrl::RemoveFragment | QUrl::StripTrailingSlash); QByteArray signatureBase; signatureBase.append("POST"); signatureBase.append(AMPERSAND); signatureBase.append(urlEncode(urlWithHostAndPath)); signatureBase.append(AMPERSAND); signatureBase.append(urlEncode(oAuthHeaderString)); return signatureBase; } // Method to create the Authorization header QString OAuth1Plugin::createOAuth1Header(const QString &aUrl, OAuth1PluginData inData) { Q_D(OAuth1Plugin); QString authHeader = OAUTH + SPACE; if (!inData.Realm().isEmpty()) { authHeader.append(EQUAL_WITH_QUOTES.arg(OAUTH_REALM) .arg(urlEncode(inData.Realm()))); authHeader.append(DELIMITER); } if (!inData.Callback().isEmpty()) { authHeader.append(EQUAL_WITH_QUOTES.arg(OAUTH_CALLBACK) .arg(urlEncode(inData.Callback()))); authHeader.append(DELIMITER); } authHeader.append(EQUAL_WITH_QUOTES.arg(OAUTH_CONSUMERKEY) .arg(urlEncode(inData.ConsumerKey()))); authHeader.append(DELIMITER); // Nonce unsigned long nonce1 = (unsigned long) qrand(); unsigned long nonce2 = (unsigned long) qrand(); QString oauthNonce = QString("%1%2").arg(nonce1).arg(nonce2); authHeader.append(EQUAL_WITH_QUOTES.arg(OAUTH_NONCE) .arg(urlEncode(oauthNonce))); authHeader.append(DELIMITER); // Timestamp QString oauthTimestamp = QString("%1").arg(QDateTime::currentDateTime().toTime_t()); authHeader.append(EQUAL_WITH_QUOTES.arg(OAUTH_TIMESTAMP) .arg(urlEncode(oauthTimestamp))); authHeader.append(DELIMITER); if (!d->m_oauth1Token.isEmpty()) { authHeader.append(EQUAL_WITH_QUOTES.arg(OAUTH_TOKEN) .arg(urlEncode(d->m_oauth1Token))); authHeader.append(DELIMITER); } authHeader.append(EQUAL_WITH_QUOTES.arg(OAUTH_SIGNATURE_METHOD) .arg(urlEncode(d->m_mechanism))); authHeader.append(DELIMITER); // Creating the signature // PLAINTEXT signature method QByteArray secretKey; secretKey.append(urlEncode(inData.ConsumerSecret()) + AMPERSAND + urlEncode(d->m_oauth1TokenSecret)); if (d->m_mechanism == PLAINTEXT) { TRACE() << "Signature = " << secretKey; authHeader.append(EQUAL_WITH_QUOTES.arg(OAUTH_SIGNATURE) .arg(urlEncode(secretKey))); authHeader.append(DELIMITER); } // HMAC-SHA1 signature method else if (d->m_mechanism == HMAC_SHA1) { QByteArray signatureBase = constructSignatureBaseString(aUrl, inData, oauthTimestamp, oauthNonce); TRACE() << "Signature Base = " << signatureBase; QByteArray signature = hashHMACSHA1(secretKey, signatureBase); TRACE() << "Signature = " << signature; authHeader.append(EQUAL_WITH_QUOTES.arg(OAUTH_SIGNATURE) .arg(urlEncode(signature.toBase64()))); authHeader.append(DELIMITER); } // TODO: RSA-SHA1 signature method should be implemented else { Q_ASSERT_X(false, __FUNCTION__, "Unsupported mechanism"); } if (!d->m_oauth1TokenVerifier.isEmpty()) { authHeader.append(EQUAL_WITH_QUOTES.arg(OAUTH_VERIFIER) .arg(urlEncode(d->m_oauth1TokenVerifier))); authHeader.append(DELIMITER); } authHeader.append(EQUAL_WITH_QUOTES.arg(OAUTH_VERSION) .arg(urlEncode(OAUTH_VERSION_1))); return authHeader; } void OAuth1Plugin::userActionFinished(const SignOn::UiSessionData &data) { Q_D(OAuth1Plugin); TRACE(); if (data.QueryErrorCode() != QUERY_ERROR_NONE) { TRACE() << "userActionFinished with error: " << data.QueryErrorCode(); if (data.QueryErrorCode() == QUERY_ERROR_CANCELED) emit error(Error(Error::SessionCanceled, QLatin1String("Cancelled by user"))); else emit error(Error(Error::UserInteraction, QString("userActionFinished error: ") + QString::number(data.QueryErrorCode()))); return; } TRACE() << data.UrlResponse(); // Checking if authorization server granted access QUrl url = QUrl(data.UrlResponse()); if (url.hasQueryItem(AUTH_ERROR)) { TRACE() << "Server denied access permission"; emit error(Error(Error::NotAuthorized, url.queryItemValue(AUTH_ERROR))); return; } if (url.hasQueryItem(OAUTH_VERIFIER)) { d->m_oauth1TokenVerifier = url.queryItemValue(OAUTH_VERIFIER); d->m_oauth1Data.setCallback(QString()); d->m_oauth1RequestType = OAUTH1_POST_ACCESS_TOKEN; sendOAuth1PostRequest(); } else if (url.hasQueryItem(OAUTH_PROBLEM)) { handleOAuth1ProblemError(url.queryItemValue(OAUTH_PROBLEM)); } else { emit error(Error(Error::NotAuthorized, QString("oauth_verifier missing"))); } } // Method to handle responses for OAuth 1.0a Request token request void OAuth1Plugin::serverReply(QNetworkReply *reply) { Q_D(OAuth1Plugin); QByteArray replyContent = reply->readAll(); TRACE() << replyContent; if (reply->error() != QNetworkReply::NoError) { d->m_oauth1RequestType = OAUTH1_POST_REQUEST_INVALID; } // Handle error responses QVariant statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute); TRACE() << statusCode; if (statusCode != HTTP_STATUS_OK) { handleOAuth1Error(replyContent); d->m_oauth1RequestType = OAUTH1_POST_REQUEST_INVALID; return; } // Handling 200 OK response (HTTP_STATUS_OK) WITH content if (reply->hasRawHeader(CONTENT_TYPE)) { // Checking if supported content type received if ((reply->rawHeader(CONTENT_TYPE).startsWith(CONTENT_APP_URLENCODED)) || (reply->rawHeader(CONTENT_TYPE).startsWith(CONTENT_TEXT_HTML)) || (reply->rawHeader(CONTENT_TYPE).startsWith(CONTENT_TEXT_PLAIN))) { QMap map = parseTextReply(replyContent); if (d->m_oauth1RequestType == OAUTH1_POST_REQUEST_TOKEN) { // Extracting the request token, token secret d->m_oauth1Token = map[OAUTH_TOKEN].toAscii(); d->m_oauth1TokenSecret = map[OAUTH_TOKEN_SECRET].toAscii(); if (d->m_oauth1Token.isEmpty() || !map.contains(OAUTH_TOKEN_SECRET)) { TRACE() << "OAuth request token is empty or secret is missing"; emit error(Error(Error::OperationFailed, QString("Request token or secret missing"))); } else { sendOAuth1AuthRequest(); } } else if (d->m_oauth1RequestType == OAUTH1_POST_ACCESS_TOKEN) { // Extracting the access token d->m_oauth1Token = map[OAUTH_TOKEN].toAscii(); d->m_oauth1TokenSecret = map[OAUTH_TOKEN_SECRET].toAscii(); if (d->m_oauth1Token.isEmpty() || !map.contains(OAUTH_TOKEN_SECRET)) { TRACE()<< "OAuth access token is empty or secret is missing"; emit error(Error(Error::OperationFailed, QString("Access token or secret missing"))); } else { QVariantMap siteResponse; QMap::iterator i; for (i = map.begin(); i != map.end(); i++) { siteResponse.insert(i.key(), i.value()); } OAuth1PluginTokenData response = oauth1responseFromMap(siteResponse); // storing token and token secret for later use OAuth2TokenData tokens; d->m_tokens.insert(d->m_key, QVariant::fromValue(siteResponse)); tokens.setTokens(d->m_tokens); emit store(tokens); emit result(response); } } else { Q_ASSERT_X(false, __FUNCTION__, "Invalid OAuth1 POST request"); } } else { TRACE()<< "Unsupported content type received: " << reply->rawHeader(CONTENT_TYPE); emit error(Error(Error::OperationFailed, QString("Unsupported content type received"))); } } // Handling 200 OK response (HTTP_STATUS_OK) WITHOUT content else { TRACE()<< "Content is not present"; emit error(Error(Error::OperationFailed, QString("Content missing"))); } d->m_oauth1RequestType = OAUTH1_POST_REQUEST_INVALID; } OAuth1PluginTokenData OAuth1Plugin::oauth1responseFromMap(const QVariantMap &map) { Q_D(OAuth1Plugin); TRACE() << "Response:" << map; OAuth1PluginTokenData response(map); response.setAccessToken(map[OAUTH_TOKEN].toString().toAscii()); response.setTokenSecret(map[OAUTH_TOKEN_SECRET].toString().toAscii()); // Store also (possible) user_id & screen_name if (map.contains(USER_ID)) { d->m_oauth1UserId = map[USER_ID].toString(); response.setUserId(d->m_oauth1UserId); } if (map.contains(SCREEN_NAME)) { d->m_oauth1ScreenName = map[SCREEN_NAME].toString(); response.setScreenName(d->m_oauth1ScreenName); } return response; } void OAuth1Plugin::handleOAuth1ProblemError(const QString &errorString) { TRACE(); Error::ErrorType type = Error::OperationFailed; if (errorString == OAUTH_USER_REFUSED || errorString == OAUTH_PERMISSION_DENIED) { type = Error::PermissionDenied; } TRACE() << "Error Emitted"; emit error(Error(type, errorString)); } void OAuth1Plugin::handleOAuth1Error(const QByteArray &reply) { TRACE(); QMap map = parseTextReply(reply); QString errorString = map[OAUTH_PROBLEM]; if (!errorString.isEmpty()) { handleOAuth1ProblemError(errorString); return; } TRACE() << "Error Emitted"; emit error(Error(Error::OperationFailed, errorString)); } void OAuth1Plugin::sendOAuth1PostRequest() { Q_D(OAuth1Plugin); TRACE(); QNetworkRequest request; request.setRawHeader(CONTENT_TYPE, CONTENT_APP_URLENCODED); QString authHeader; if (d->m_oauth1RequestType == OAUTH1_POST_REQUEST_TOKEN) { request.setUrl(d->m_oauth1Data.RequestEndpoint()); authHeader = createOAuth1Header(d->m_oauth1Data.RequestEndpoint(), d->m_oauth1Data); } else if (d->m_oauth1RequestType == OAUTH1_POST_ACCESS_TOKEN) { request.setUrl(d->m_oauth1Data.TokenEndpoint()); authHeader = createOAuth1Header(d->m_oauth1Data.TokenEndpoint(), d->m_oauth1Data); } else { Q_ASSERT_X(false, __FUNCTION__, "Invalid OAuth1 POST request"); } request.setRawHeader(QByteArray("Authorization"), authHeader.toAscii()); postRequest(request, QByteArray()); } const QMap OAuth1Plugin::parseTextReply(const QByteArray &reply) { TRACE(); QMap map; QList items = reply.split('&'); foreach (QByteArray item, items) { int idx = item.indexOf("="); if (idx > -1) { map.insert(item.left(idx), QByteArray::fromPercentEncoding(item.mid(idx + 1))); } } return map; } signon-plugin-oauth2-0.19+14.04.20140305/src/common.h0000644000015201777760000000217012305565653022271 0ustar pbusernogroup00000000000000/* * This file is part of oauth2 plugin * * Copyright (C) 2010 Nokia Corporation. * Copyright (C) 2012 Canonical Ltd. * * Contact: Alberto Mardegan * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * 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 St, Fifth Floor, Boston, MA * 02110-1301 USA */ #ifndef SIGNON_PLUGIN_OAUTH2_COMMON #define SIGNON_PLUGIN_OAUTH2_COMMON #ifdef TRACE #undef TRACE #endif #define TRACE() qDebug() << __FILE__ << __LINE__ << __func__ << ":" #define QT_DISABLE_DEPRECATED_BEFORE QT_VERSION_CHECK(4, 0, 0) #endif // SIGNON_PLUGIN_OAUTH2_COMMON signon-plugin-oauth2-0.19+14.04.20140305/src/plugin.cpp0000644000015201777760000000764112305565653022642 0ustar pbusernogroup00000000000000/* * This file is part of oauth2 plugin * * Copyright (C) 2010 Nokia Corporation. * Copyright (C) 2012 Canonical Ltd. * * Contact: Alberto Mardegan * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * 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 St, Fifth Floor, Boston, MA * 02110-1301 USA */ #include "common.h" #include "oauth1plugin.h" #include "oauth2plugin.h" #include "plugin.h" #include #include using namespace SignOn; using namespace OAuth2PluginNS; namespace OAuth2PluginNS { SIGNON_DECL_AUTH_PLUGIN(Plugin) } //namespace OAuth2PluginNS Plugin::Plugin(QObject *parent): AuthPluginInterface(parent), impl(0), m_networkAccessManager(new QNetworkAccessManager(this)) { TRACE(); } Plugin::~Plugin() { TRACE(); delete impl; impl = 0; } QString Plugin::type() const { TRACE(); return QString("oauth2"); } QStringList Plugin::mechanisms() const { TRACE(); return OAuth1Plugin::mechanisms() + OAuth2Plugin::mechanisms(); } void Plugin::cancel() { TRACE(); if (impl != 0) impl->cancel(); } void Plugin::process(const SignOn::SessionData &inData, const QString &mechanism) { if (impl != 0) delete impl; if (OAuth1Plugin::mechanisms().contains(mechanism)) { impl = new OAuth1Plugin(this); } else if (OAuth2Plugin::mechanisms().contains(mechanism)) { impl = new OAuth2Plugin(this); } else { emit error(Error(Error::MechanismNotAvailable)); return; } QNetworkProxy networkProxy = QNetworkProxy::applicationProxy(); // Override proxy, if given in the parameters QString proxy = inData.NetworkProxy(); if (!proxy.isEmpty()) { QUrl proxyUrl(proxy); if (!proxyUrl.host().isEmpty()) { networkProxy = QNetworkProxy(QNetworkProxy::HttpProxy, proxyUrl.host(), proxyUrl.port(), proxyUrl.userName(), proxyUrl.password()); TRACE() << proxyUrl.host() << ":" << proxyUrl.port(); } } m_networkAccessManager->setProxy(networkProxy); impl->setNetworkAccessManager(m_networkAccessManager); // Forward the signals from the implementation connect(impl, SIGNAL(result(const SignOn::SessionData &)), SIGNAL(result(const SignOn::SessionData &))); connect(impl, SIGNAL(store(const SignOn::SessionData &)), SIGNAL(store(const SignOn::SessionData &))); connect(impl, SIGNAL(error(const SignOn::Error &)), SIGNAL(error(const SignOn::Error &))); connect(impl, SIGNAL(userActionRequired(const SignOn::UiSessionData &)), SIGNAL(userActionRequired(const SignOn::UiSessionData &))); connect(impl, SIGNAL(refreshed(const SignOn::UiSessionData &)), SIGNAL(refreshed(const SignOn::UiSessionData &))); connect(impl, SIGNAL(statusChanged(const AuthPluginState, const QString&)), SIGNAL(statusChanged(const AuthPluginState, const QString&))); impl->process(inData, mechanism); } void Plugin::userActionFinished(const SignOn::UiSessionData &data) { TRACE(); if (impl != 0) impl->userActionFinished(data); } void Plugin::refresh(const SignOn::UiSessionData &data) { TRACE(); if (impl != 0) impl->refresh(data); } signon-plugin-oauth2-0.19+14.04.20140305/src/signon-oauth2plugin.pc0000644000015201777760000000033712305565653025073 0ustar pbusernogroup00000000000000prefix=/usr exec_prefix=${prefix} libdir=${prefix}/lib/ includedir=${prefix}/include Name: signon-oauth2plugin Description: Signon OAuth 2.0 plugin Version: 0.0.1 Requires: signon-plugins Libs.private: -L/usr/lib -lQtCore signon-plugin-oauth2-0.19+14.04.20140305/src/src.pro0000644000015201777760000000154112305565653022142 0ustar pbusernogroup00000000000000include( ../common-project-config.pri ) include( ../common-vars.pri ) TEMPLATE = lib TARGET = oauth2plugin DESTDIR = lib/signon QT += core \ network \ xmlpatterns QT -= gui CONFIG += plugin \ build_all \ warn_on \ link_pkgconfig public_headers += oauth2data.h oauth1data.h private_headers = \ base-plugin.h \ common.h \ oauth1plugin.h \ oauth2plugin.h \ oauth2tokendata.h \ plugin.h HEADERS = $$public_headers \ $$private_headers SOURCES += \ base-plugin.cpp \ oauth1plugin.cpp \ oauth2plugin.cpp \ plugin.cpp PKGCONFIG += \ signon-plugins lessThan(QT_MAJOR_VERSION, 5) { PKGCONFIG += \ QJson \ libsignon-qt } else { PKGCONFIG += \ libsignon-qt5 } headers.files = $$public_headers pkgconfig.files = signon-oauth2plugin.pc include( ../common-installs-config.pri ) signon-plugin-oauth2-0.19+14.04.20140305/src/oauth2plugin.h0000644000015201777760000000501012305565653023416 0ustar pbusernogroup00000000000000/* * This file is part of oauth2 plugin * * Copyright (C) 2010 Nokia Corporation. * Copyright (C) 2012 Canonical Ltd. * * Contact: Alberto Mardegan * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * 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 St, Fifth Floor, Boston, MA * 02110-1301 USA */ #ifndef SIGNON_PLUGIN_OAUTH2 #define SIGNON_PLUGIN_OAUTH2 #include #include #include #include #include "base-plugin.h" #include "oauth2data.h" namespace OAuth2PluginNS { namespace GrantType { enum e { Undefined = 0, RefreshToken, UserBasic, Assertion, AuthorizationCode, }; }; /*! * @class OAuth2Plugin * OAuth 2.0 authentication plugin. */ class OAuth2PluginPrivate; class OAuth2Plugin: public BasePlugin { Q_OBJECT public: OAuth2Plugin(QObject *parent = 0); ~OAuth2Plugin(); static QStringList mechanisms(); void process(const SignOn::SessionData &inData, const QString &mechanism); void userActionFinished(const SignOn::UiSessionData &data); protected: void serverReply(QNetworkReply *); private: void sendOAuth2AuthRequest(); bool validateInput(const SignOn::SessionData &inData, const QString &mechanism); bool respondWithStoredToken(const QVariantMap &token, const QStringList &scopes); void refreshOAuth2Token(const QString &refreshToken); void sendOAuth2PostRequest(const QByteArray &postData, GrantType::e grantType); void storeResponse(const OAuth2PluginTokenData &response); const QVariantMap parseJSONReply(const QByteArray &reply); const QMap parseTextReply(const QByteArray &reply); void handleOAuth2Error(const QByteArray &reply); QString urlEncode(QString strData); OAuth2PluginPrivate *d_ptr; Q_DECLARE_PRIVATE(OAuth2Plugin) }; } //namespace OAuth2PluginNS #endif // SIGNON_PLUGIN_OAUTH2 signon-plugin-oauth2-0.19+14.04.20140305/src/oauth1data.h0000644000015201777760000000535112305565653023040 0ustar pbusernogroup00000000000000/* * This file is part of oauth2 plugin * * Copyright (C) 2010 Nokia Corporation. * * Contact: Alberto Mardegan * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * 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 St, Fifth Floor, Boston, MA * 02110-1301 USA */ #ifndef OAUTH1DATA_H #define OAUTH1DATA_H #include class OAuth2PluginTest; namespace OAuth2PluginNS { /*! * @class OAuth1PluginData * Data container to hold values for OAuth 1.0a authentication session. */ class OAuth1PluginData : public SignOn::SessionData { friend class ::OAuth2PluginTest; public: /*! * Request token endpoint of the server */ SIGNON_SESSION_DECLARE_PROPERTY(QString, RequestEndpoint); /*! * Access token endpoint of the server */ SIGNON_SESSION_DECLARE_PROPERTY(QString, TokenEndpoint); SIGNON_SESSION_DECLARE_PROPERTY(QString, AuthorizationEndpoint); /*! * Application client ID and secret */ SIGNON_SESSION_DECLARE_PROPERTY(QString, ConsumerKey); SIGNON_SESSION_DECLARE_PROPERTY(QString, ConsumerSecret); /*! * redirection URI */ SIGNON_SESSION_DECLARE_PROPERTY(QString, Callback); SIGNON_SESSION_DECLARE_PROPERTY(QString, Realm); /* Optional username */ SIGNON_SESSION_DECLARE_PROPERTY(QString, UserName); }; class OAuth1PluginTokenData : public SignOn::SessionData { public: OAuth1PluginTokenData(const QVariantMap &data = QVariantMap()): SignOn::SessionData(data) {} /*! * Access token received from the server */ SIGNON_SESSION_DECLARE_PROPERTY(QString, AccessToken); /*! * Token secret received from the server */ SIGNON_SESSION_DECLARE_PROPERTY(QString, TokenSecret); /*! * Possible user ID received from the server */ SIGNON_SESSION_DECLARE_PROPERTY(QString, UserId); /*! * Possible screen name received from the server */ SIGNON_SESSION_DECLARE_PROPERTY(QString, ScreenName); }; } // namespace OAuth2PluginNS #endif // OAUTH1DATA_H signon-plugin-oauth2-0.19+14.04.20140305/src/oauth2tokendata.h0000644000015201777760000000445612305565653024107 0ustar pbusernogroup00000000000000/* * This file is part of oauth2 plugin * * Copyright (C) 2010 Nokia Corporation. * * Contact: Alberto Mardegan * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * 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 St, Fifth Floor, Boston, MA * 02110-1301 USA */ #ifndef OAUTH2TOKENDATA_H #define OAUTH2TOKENDATA_H #include #include #include class OAuth2PluginTest; namespace OAuth2PluginNS { /*! * Data container to hold values for storing Token. */ class OAuth2TokenData : public SignOn::SessionData { public: friend class ::OAuth2PluginTest; /*! * Declare property Tokens setter and getter * Received tokens are stored in this map */ SIGNON_SESSION_DECLARE_PROPERTY(QVariantMap, Tokens); /*! * Declares the property ProvidedTokens setter and getter. * If this property is set then process() will store the value * of this property and return the appropriate response data. * This should be used only if the signon process is performed * manually, and you wish to store the resulting credentials * into the identity. * * If the flow is OAuth2 then the ProvidedTokens value must * contain values for the following keys: * - AccessToken * - ExpiresIn * - RefreshToken * and clients should use the OAuth2PluginTokenData class. * * If the flow is OAuth1.0a then the ProvidedTokens value * must contain values for the following keys: * - AccessToken * - TokenSecret * and optionally for: * - UserId * - ScreenName * and clients should use the OAuth1PluginTokenData class. */ SIGNON_SESSION_DECLARE_PROPERTY(QVariantMap, ProvidedTokens); }; } // namespace #endif // OAUTH2TOKENDATA_H signon-plugin-oauth2-0.19+14.04.20140305/src/oauth1plugin.h0000644000015201777760000000515512305565653023427 0ustar pbusernogroup00000000000000/* * This file is part of oauth2 plugin * * Copyright (C) 2010 Nokia Corporation. * Copyright (C) 2012 Canonical Ltd. * * Contact: Alberto Mardegan * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * 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 St, Fifth Floor, Boston, MA * 02110-1301 USA */ #ifndef SIGNON_PLUGIN_OAUTH1 #define SIGNON_PLUGIN_OAUTH1 #include #include "base-plugin.h" #include "oauth1data.h" namespace OAuth2PluginNS { /*! * @class OAuth1Plugin * OAuth 1.0a authentication plugin. */ class OAuth1PluginPrivate; class OAuth1Plugin: public BasePlugin { Q_OBJECT public: OAuth1Plugin(QObject *parent = 0); ~OAuth1Plugin(); static QStringList mechanisms(); void process(const SignOn::SessionData &inData, const QString &mechanism = 0); void userActionFinished(const SignOn::UiSessionData &data); protected: void serverReply(QNetworkReply *reply); private: void sendOAuth1AuthRequest(const QString &captchaUrl = 0); bool validateInput(const SignOn::SessionData &inData, const QString &mechanism); bool respondWithStoredToken(const QVariantMap &token, const QString &mechanism); void sendOAuth1PostRequest(); const QMap parseTextReply(const QByteArray &reply); void handleOAuth1ProblemError(const QString &errorString); void handleOAuth1Error(const QByteArray &reply); QByteArray constructSignatureBaseString(const QString &aUrl, const OAuth1PluginData &inData, const QString ×tamp, const QString &nonce); QString urlEncode(QString strData); QString createOAuth1Header(const QString &aUrl, OAuth1PluginData inData); QByteArray hashHMACSHA1(const QByteArray &keyForHash ,const QByteArray &secret); OAuth1PluginTokenData oauth1responseFromMap(const QVariantMap &map); OAuth1PluginPrivate *d_ptr; Q_DECLARE_PRIVATE(OAuth1Plugin) }; } //namespace OAuth2PluginNS #endif // SIGNON_PLUGIN_OAUTH1 signon-plugin-oauth2-0.19+14.04.20140305/src/base-plugin.h0000644000015201777760000000505612305565653023215 0ustar pbusernogroup00000000000000/* * This file is part of oauth2 plugin * * Copyright (C) 2010 Nokia Corporation. * Copyright (C) 2012 Canonical Ltd. * * Contact: Alberto Mardegan * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * 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 St, Fifth Floor, Boston, MA * 02110-1301 USA */ #ifndef SIGNON_PLUGIN_BASE #define SIGNON_PLUGIN_BASE #include #include #include #include #include #include #include class QNetworkAccessManager; namespace OAuth2PluginNS { /*! * @class BasePlugin * Base class for OAuth-based plugins. */ class BasePluginPrivate; class BasePlugin: public QObject { Q_OBJECT public: BasePlugin(QObject *parent = 0); ~BasePlugin(); virtual void cancel(); virtual void process(const SignOn::SessionData &inData, const QString &mechanism) = 0; virtual void userActionFinished(const SignOn::UiSessionData &data) = 0; virtual void refresh(const SignOn::UiSessionData &data); void setNetworkAccessManager(QNetworkAccessManager *nam); QNetworkAccessManager *networkAccessManager() const; protected: void postRequest(const QNetworkRequest &request, const QByteArray &data); virtual void serverReply(QNetworkReply *reply); protected Q_SLOTS: void onPostFinished(); virtual bool handleNetworkError(QNetworkReply::NetworkError err); virtual void handleSslErrors(QList errorList); Q_SIGNALS: void result(const SignOn::SessionData &data); void store(const SignOn::SessionData &data); void error(const SignOn::Error &err); void userActionRequired(const SignOn::UiSessionData &data); void refreshed(const SignOn::UiSessionData &data); void statusChanged(const AuthPluginState state, const QString &message); private: BasePluginPrivate *d_ptr; Q_DECLARE_PRIVATE(BasePlugin) }; } //namespace OAuth2PluginNS #endif // SIGNON_PLUGIN_BASE signon-plugin-oauth2-0.19+14.04.20140305/COPYING0000644000015201777760000006350212305565653021102 0ustar pbusernogroup00000000000000 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. Copyright (C) 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. , 1 April 1990 Ty Coon, President of Vice That's all there is to it! signon-plugin-oauth2-0.19+14.04.20140305/example/0000755000015201777760000000000012305566066021473 5ustar pbusernogroup00000000000000signon-plugin-oauth2-0.19+14.04.20140305/example/www.facebook.com.conf0000644000015201777760000000004512305565653025513 0ustar pbusernogroup00000000000000PreferredWidth = 220 ZoomFactor = 2 signon-plugin-oauth2-0.19+14.04.20140305/example/m.facebook.com.conf0000644000015201777760000000004512305565653025123 0ustar pbusernogroup00000000000000PreferredWidth = 220 ZoomFactor = 2 signon-plugin-oauth2-0.19+14.04.20140305/example/.gitignore0000644000015201777760000000001412305565653023457 0ustar pbusernogroup00000000000000oauthclient signon-plugin-oauth2-0.19+14.04.20140305/example/example.pro0000644000015201777760000000111212305565653023644 0ustar pbusernogroup00000000000000include( ../common-project-config.pri ) include( ../common-vars.pri ) TEMPLATE = app TARGET = oauthclient INCLUDEPATH += . \ $$TOP_SRC_DIR/src/ CONFIG += \ debug \ link_pkgconfig QT -= gui lessThan(QT_MAJOR_VERSION, 5) { PKGCONFIG += libsignon-qt } else { PKGCONFIG += libsignon-qt5 } HEADERS += \ oauthclient.h SOURCES += \ main.cpp \ oauthclient.cpp # install include( ../common-installs-config.pri ) signon-ui.files = \ m.facebook.com.conf \ www.facebook.com.conf signon-ui.path = /etc/signon-ui/webkit-options.d/ INSTALLS += signon-ui signon-plugin-oauth2-0.19+14.04.20140305/example/main.cpp0000644000015201777760000000215612305565653023130 0ustar pbusernogroup00000000000000/* * This file is part of signon * * Copyright (C) 2009-2010 Nokia Corporation. * * Contact: Alberto Mardegan * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * 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 St, Fifth Floor, Boston, MA * 02110-1301 USA */ #include "oauthclient.h" #include using namespace SignOn; int main(int argc, char *argv[]) { QCoreApplication app(argc, argv); OAuthClient client("213156715390803", "bf89c2d9de5e929fe5c5921e9a1f2924"); client.authenticate(); return app.exec(); } signon-plugin-oauth2-0.19+14.04.20140305/example/oauthclient.h0000644000015201777760000000270412305565653024167 0ustar pbusernogroup00000000000000/* * This file is part of signon * * Copyright (C) 2009-2010 Nokia Corporation. * * Contact: Alberto Mardegan * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * 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 St, Fifth Floor, Boston, MA * 02110-1301 USA */ #ifndef OAUTHCLIENT_H #define OAUTHCLIENT_H #include #include #include class OAuthClient: public QObject { Q_OBJECT public: OAuthClient(const QString &clientId, const QString &clientSecret, QObject *parent = 0); ~OAuthClient(); public Q_SLOTS: void authenticate(); private Q_SLOTS: void onResponse(const SignOn::SessionData &sessionData); void onError(const SignOn::Error &error); private: QString m_clientId; QString m_clientSecret; SignOn::Identity *m_identity; SignOn::AuthSession *m_session; }; #endif // OAUTHCLIENT_H signon-plugin-oauth2-0.19+14.04.20140305/example/oauthclient.cpp0000644000015201777760000000465312305565653024527 0ustar pbusernogroup00000000000000/* * This file is part of signon * * Copyright (C) 2011 Nokia Corporation. * * Contact: Alberto Mardegan * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * 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 St, Fifth Floor, Boston, MA * 02110-1301 USA */ #include "oauthclient.h" #include "oauth2data.h" #include #include using namespace OAuth2PluginNS; OAuthClient::OAuthClient(const QString &clientId, const QString &clientSecret, QObject *parent): QObject(parent), m_clientId(clientId), m_clientSecret(clientSecret), m_identity(0), m_session(0) { m_identity = SignOn::Identity::newIdentity(SignOn::IdentityInfo(), this); } OAuthClient::~OAuthClient() { } void OAuthClient::authenticate() { SignOn::AuthSession *m_session = m_identity->createSession("oauth2"); QObject::connect(m_session, SIGNAL(response(const SignOn::SessionData &)), this, SLOT(onResponse(const SignOn::SessionData &))); QObject::connect(m_session, SIGNAL(error(const SignOn::Error &)), this, SLOT(onError(const SignOn::Error &))); OAuth2PluginData data; data.setHost("www.facebook.com"); data.setAuthPath("/dialog/oauth"); data.setRedirectUri("https://www.facebook.com/connect/login_success.html"); data.setClientId(m_clientId); data.setClientSecret(m_clientSecret); m_session->process(data, "user_agent"); } void OAuthClient::onResponse(const SignOn::SessionData &sessionData) { OAuth2PluginTokenData response = sessionData.data(); qDebug() << "Access token:" << response.AccessToken(); qDebug() << "Expires in:" << response.ExpiresIn(); QCoreApplication::quit(); } void OAuthClient::onError(const SignOn::Error &error) { qDebug() << "Got error:" << error.message(); QCoreApplication::quit(); }