Merge branch 'master' into situare_interact
[situare] / src / facebookservice / facebookauthentication.cpp
index e02391e..8475f29 100644 (file)
@@ -4,6 +4,7 @@
 
        Ville Tiensuu - ville.tiensuu@ixonos.com
        Kaj Wallin - kaj.wallin@ixonos.com
+       Henri Lampela - henri.lampela@ixonos.com
 
    Situare is free software; you can redistribute it and/or
    modify it under the terms of the GNU General Public License
    USA.
 */
 
-#include "facebookauthentication.h"
-#include <QtGui>
+#include <qjson/parser.h>
+
 #include <QtDebug>
 #include <QDateTime>
+#include <QNetworkReply>
+#include <QSettings>
+#include <QStringList>
+#include <QVariantMap>
+#include <QWebView>
+
+#ifdef Q_WS_MAEMO_5
+#include <QMaemo5InformationBox>
+#endif // Q_WS_MAEMO_5
+
+#include "common.h"
+#include "../error.h"
+#include "network/networkcookiejar.h"
+#include "situareservice/situarecommon.h"
+#include "ui/mainwindow.h"
 
-FacebookAuthentication::FacebookAuthentication(QWidget *parent)
-    : QMainWindow(parent)
-{
-    qDebug() << __PRETTY_FUNCTION__;
-
-    webView = new QWebView;
-    mainlayout = new QHBoxLayout;
+#include "facebookauthentication.h"
 
-    QString facebookLoginBase = "http://www.facebook.com/login.php?";
-    QString situarePublicFacebookApiKey = "api_key=4197c64da2fb6b927236feaea32d7d81";
-    //QString situareDeveloperFacebookApiKey = "api_key=cf77865a5070f2c2ba3b52cbf3371579";
-    QString interval1 = "&connect_display=popup&v=1.0&next=";
-    QString situareLoginSuccess = "http://www.facebook.com/connect/login_success.html";
-    QString interval2 = "&cancel_url=";
-    QString situareLoginFailure = "http://www.facebook.com/connect/login_failure.html";
-    QString facebookLoginEnding = "&fbconnect=true&return_session=true&";
+const QString FB_LOGIN_SUCCESS_URL = "http://www.facebook.com/connect/login_success.html";
+const QString FB_LOGIN_URL = "https://www.facebook.com/login.php";
 
-    facebookLoginPage.append(facebookLoginBase);
-    facebookLoginPage.append(situarePublicFacebookApiKey);
-    facebookLoginPage.append(interval1);
-    facebookLoginPage.append(situareLoginSuccess);
-    facebookLoginPage.append(interval2);
-    facebookLoginPage.append(situareLoginFailure);
-    facebookLoginPage.append(facebookLoginEnding);
+const QString URL_SESSION_PARAMETER_BEGIN("session={");
 
-    connect(webView, SIGNAL(urlChanged(const QUrl &)), this, SLOT(updateCredentials(const QUrl &)));   
+FacebookAuthentication::FacebookAuthentication(MainWindow *mainWindow, QObject *parent)
+    : QObject(parent),
+      m_loggedIn(false),
+      m_browser(0),
+      m_mainWindow(mainWindow)
+{
+    qDebug() << __PRETTY_FUNCTION__;
+}
 
-    readCredentials(loginCredentials);
+void FacebookAuthentication::browserDestroyed()
+{
+    qDebug() << __PRETTY_FUNCTION__;
 
-    if (!verifyCredentials(loginCredentials))
-        start();
-    else
-        emit credentialsReady();
+    m_mainWindow->toggleProgressIndicator(false);
+    m_browser = 0;
+}
 
+void FacebookAuthentication::clearAccountInformation(bool clearUserInformation)
+{
+    /// @todo Parameter not needed
+    qDebug() << __PRETTY_FUNCTION__ << "clearUserInformation:" << clearUserInformation;
+
+    if (clearUserInformation) {
+        NetworkCookieJar::clearCookiesSetting();
+        QSettings settings(SETTINGS_ORGANIZATION_NAME, SETTINGS_APPLICATION_NAME);
+        settings.remove(SETTINGS_AUTOMATIC_UPDATE_ENABLED);
+        settings.remove(SETTINGS_AUTOMATIC_UPDATE_INTERVAL);
+    }
 }
 
-FacebookAuthentication::~FacebookAuthentication()
+void FacebookAuthentication::destroyLogin()
 {
     qDebug() << __PRETTY_FUNCTION__;
-    delete webView;
-    delete mainlayout;
+
+    m_mainWindow->destroyLoginDialog();
+    m_browser->deleteLater();
 }
 
-void FacebookAuthentication::start()
+bool FacebookAuthentication::isLoggedIn() const
 {
     qDebug() << __PRETTY_FUNCTION__;
 
-    const double fontSizeLarge = 1.2;
-    //const double fontSizeNormal = 1.0;
-
-    webView->setZoomFactor(fontSizeLarge);
-    webView->load(facebookLoginPage);
-    setCentralWidget(webView);    
+    return m_loggedIn;
 }
 
-
-bool FacebookAuthentication::updateCredentials(const QUrl &url)
-{    
+void FacebookAuthentication::login()
+{
     qDebug() << __PRETTY_FUNCTION__;
-//    setCurrentUrl(url);
-
-    bool foundSessionKey = FALSE;
-    bool foundUserID = FALSE;
-    bool foundExpires = FALSE;
-    bool foundSessionSecret = FALSE;
-    bool foundSig = FALSE;
-
-    if (url.isValid()){
-         //qDebug() << "url is valid" << endl;
-
-        QString callbackUrl = url.toString(); //tmpUrl.toString();
-        QString urlEdit(callbackUrl);
-        //qDebug() << "callbackUrl:  " << endl << callbackUrl.toAscii() << endl;
-        //qDebug() << "webView zoom factor" << webView->zoomFactor() << endl;
-
-        if ( callbackUrl.indexOf("http://www.facebook.com/connect/login_success.html") == 0 ){
-            //qDebug() << "login success" << endl;
-
-            // let's find out session key            
-            int indexOfCredential = callbackUrl.indexOf("session_key");
-            int index2;
-
-            if (indexOfCredential != -1){
-                foundSessionKey = TRUE;
-
-                indexOfCredential += 14; //lenght of string "session_key"
-                index2 = callbackUrl.indexOf("uid");
-                index2 -= 4;
-                urlEdit.remove(0,indexOfCredential);
-                index2 = urlEdit.indexOf("uid");
-                urlEdit.remove(index2, urlEdit.length());
-                urlEdit.remove("\",\"");
-
-                //qDebug() << "session_key" << endl << urlEdit.toAscii() << endl;
-                loginCredentials.setSessionKey(urlEdit);
-            }
-
-            // let's find out uid            
-            urlEdit = callbackUrl;
-            indexOfCredential = callbackUrl.indexOf("uid");
-
-            if (indexOfCredential != -1){
-                foundUserID = TRUE;
-                indexOfCredential += 5; //length of string "uid"
-                urlEdit.remove(0,indexOfCredential);
-
-                index2 = urlEdit.indexOf("expires");
-                urlEdit.remove(index2, urlEdit.length());
-                urlEdit.remove(",\"");
-                //qDebug() << "urlEdit" << endl << urlEdit.toStdString() << endl;
-
-                //qDebug() << "userID" << endl << urlEdit.toAscii() << endl;
-                loginCredentials.setUserID(urlEdit);
-            }
-
-            // let's find out expires           
-            urlEdit = callbackUrl;
-            indexOfCredential = callbackUrl.indexOf("expires");
-
-            if (indexOfCredential != -1){
-                foundExpires = TRUE;
-
-                indexOfCredential += 9; //length of string "expires"
-                urlEdit.remove(0,indexOfCredential);
-                index2 = urlEdit.indexOf("secret");
-                urlEdit.remove(index2, urlEdit.length());
-                urlEdit.remove(",\"");
-
-                //qDebug() << "expires" << endl << urlEdit.toAscii() << endl;
-                loginCredentials.setExpires(urlEdit);
-            }
-
-            // let's find out sessionsecret            
-            urlEdit = callbackUrl;
-            indexOfCredential = callbackUrl.indexOf("secret");
-
-            if (indexOfCredential != -1){
-                foundSessionSecret = TRUE;
-
-                indexOfCredential += 9; //" length of "secret"
-                urlEdit.remove(0,indexOfCredential);
-                index2 = urlEdit.indexOf("sig");
-                urlEdit.remove(index2, urlEdit.length());
-                urlEdit.remove("\",\"");
-
-                //*sessionSecret = urlEdit;
-                //qDebug() << "sessionSecret" << endl << urlEdit.toAscii() << endl;
-                loginCredentials.setSessionSecret(urlEdit);
-            }
-
-            // let's find out sig            
-            urlEdit = callbackUrl;
-            indexOfCredential = callbackUrl.indexOf("sig");
-
-            if (indexOfCredential != -1){
-                foundSig = TRUE;
-
-                indexOfCredential += 6; //" length of sig":"
-                urlEdit.remove(0,indexOfCredential);
-                urlEdit.remove("\"}");
-
-                //qDebug() << "sig" << endl << urlEdit.toAscii() << endl;
-                loginCredentials.setSig(urlEdit);
-            }
-
-
-            webView->hide(); //let's close the webview after successful login.
-            emit credentialsReady();
-            writeCredentials(loginCredentials);
-        }
 
-        else if ( callbackUrl.indexOf("https://login.facebook.com/login.php?login_attempt=") == 0){
-            qWarning() << "login failure" << endl;
-            emit loginFailure();
-        }
+    if (!m_browser) {
+        m_browser = new QWebView(m_mainWindow);
 
-        else if ( callbackUrl.indexOf("http://www.facebook.com/login.php?api_key=") == 0){
-            //qDebug() << "correct loginPage";
-        }
+        if (m_browser) {
+            m_browser->page()->networkAccessManager()->setCookieJar(new NetworkCookieJar());
+
+            connect(m_browser, SIGNAL(urlChanged(QUrl)),
+                    this, SLOT(urlChanged(QUrl)));
 
-        else { // totally wrong webPage. User will be redirected to basic login page...
-            //qDebug() << "totally wrong webPage";
-            emit loginFailure();
-            start();
+            connect(m_browser, SIGNAL(destroyed(QObject*)),
+                    this, SLOT(browserDestroyed()));
+
+            connect(m_browser->page()->networkAccessManager(),
+                    SIGNAL(sslErrors(QNetworkReply*, QList<QSslError>)),
+                    this, SLOT(sslErrors(QNetworkReply*, QList<QSslError>)));
+
+            connect(m_browser->page()->networkAccessManager(), SIGNAL(finished(QNetworkReply*)),
+                    this, SLOT(networkReplyHandler(QNetworkReply*)));
         }
     }
 
+    if (m_browser) {
+        QString url = FB_LOGIN_URL + "?";
+        url.append("api_key=" + API_KEY +"&");
+        url.append("display=touch&");
+        url.append("fbconnect=1&");
+        url.append("next=" + FB_LOGIN_SUCCESS_URL + "&");
+        url.append("return_session=1&");
+        url.append("session_version=3&");
+        url.append("v=1.0&");
+        url.append("req_perms=publish_stream");
+
+        m_browser->load(QUrl(url));
 
-    else { // show error message that page cant be loaded in QWebView
-        //qDebug() << " Loading of page failed invalid URL" << endl;
-        emit loginFailure();
-        return FALSE;
+        m_mainWindow->toggleProgressIndicator(true);
     }
+}
 
+void FacebookAuthentication::logOut(bool clearUserInformation)
+{
+    qDebug() << __PRETTY_FUNCTION__;
 
-    return (foundSessionKey && foundUserID && foundExpires && foundSessionSecret && foundSig);
+    clearAccountInformation(clearUserInformation);
+    m_loggedIn = false;
+    emit loggedOut();
 }
 
-void FacebookAuthentication::writeCredentials(const FacebookCredentials &credentials)
+void FacebookAuthentication::networkReplyHandler(QNetworkReply *reply)
 {
-    qDebug() << __PRETTY_FUNCTION__;
-    QSettings settings("Ixonos", "Situare");
+    qDebug() <<__PRETTY_FUNCTION__;
+
+    if ((reply->error() != QNetworkReply::NoError)
+        && (reply->error() != QNetworkReply::OperationCanceledError)) {
 
-    settings.setValue("Session Key", credentials.getSessionKey());
-    settings.setValue("User ID", credentials.getUserID());
-    settings.setValue("Expires", credentials.getExpires());
-    settings.setValue("Session Secret", credentials.getSessionSecret());
-    settings.setValue("Sig", credentials.getSig());
+        qCritical() << __PRETTY_FUNCTION__ << "error:" << reply->error() << reply->errorString();
+        emit error(ErrorContext::NETWORK, reply->error());
+        destroyLogin();
+    }
 }
 
-void FacebookAuthentication::readCredentials(FacebookCredentials &credentialsFromFile)
+QString FacebookAuthentication::parseSession(const QUrl &url)
 {
     qDebug() << __PRETTY_FUNCTION__;
 
-    QSettings settings("Ixonos", "Situare");
+    const QString END("}");
 
-    credentialsFromFile.setSessionKey(settings.value("Session Key", "Error").toString());
-    credentialsFromFile.setUserID(settings.value("User ID", "Error").toString());
-    credentialsFromFile.setExpires(settings.value("Expires", "Error").toString());
-    credentialsFromFile.setSessionSecret(settings.value("Session Secret", "Error").toString());
-    credentialsFromFile.setSig(settings.value("Sig", "Error").toString());
-}
+    QString urlString = url.toString();
+
+    int begin = urlString.indexOf(URL_SESSION_PARAMETER_BEGIN);
+    int end = urlString.indexOf(END, begin);
 
- FacebookCredentials FacebookAuthentication::getLoginCredentials() const
- {
-     qDebug() << __PRETTY_FUNCTION__;
-     return loginCredentials;
- }
+    if ((begin > -1) && (end > -1))
+        return urlString.mid(begin, end - begin + 1);
+    else
+        return QString();
+}
 
- bool FacebookAuthentication::verifyCredentials(const FacebookCredentials &credentials) const
- {
-     QString expires = credentials.getExpires();
-     QDateTime expireTime;
-     expireTime.setTime_t(expires.toInt());
-     QString expiresString = expireTime.toString("dd.MM.yyyy  hh:mm:ss");
-     qDebug() << expiresString.toAscii();
+void FacebookAuthentication::sslErrors(QNetworkReply *reply, const QList<QSslError> &errors)
+{
+    qDebug() << __PRETTY_FUNCTION__;
 
-     QDateTime currentTime;
-     currentTime = QDateTime::currentDateTime();
-     QString currentTimeString = currentTime.toString("dd.MM.yyyy  hh:mm:ss");
-     qDebug() << currentTimeString.toAscii();
+    Q_UNUSED(errors);
+    reply->ignoreSslErrors();
+}
 
-     return currentTime < expireTime;
- }
+void FacebookAuthentication::urlChanged(const QUrl &url)
+{
+    qDebug() << __PRETTY_FUNCTION__;
 
+    const QString WALL_POST_PERMISSION = "publish_stream";
+
+    /*
+      URL changes in different use cases:
+        * Login with cookie failed:
+            1) http://m.facebook.com/login.php?api_key=cf77865a5070f2c2ba3b52cbf3371579&cancel_url=http://www.facebook.com/connect/login_failure.html&display=touch&fbconnect=1&next=http://www.facebook.com/connect/uiserver.php?app_id=286811277465&next=http%3A%2F%2Fwww.facebook.com%2Fconnect%2Flogin_success.html&display=touch&cancel_url=http%3A%2F%2Fwww.facebook.com%2Fconnect%2Flogin_failure.html&perms=publish_stream&return_session=1&session_version=3&fbconnect=1&canvas=0&legacy_return=1&method=permissions.request&return_session=1&session_version=3&v=1.0&req_perms=publish_stream&app_id=286811277465&refsrc=http://www.facebook.com/login.php&fbb=ra985c5e9
+
+        * Login without cookie, not allowed to publish:
+            1) http://m.facebook.com/login.php?api_key=cf77865a5070f2c2ba3b52cbf3371579&display=touch&fbconnect=1&next=http://www.facebook.com/connect/uiserver.php?app_id=286811277465&next=http%3A%2F%2Fwww.facebook.com%2Fconnect%2Flogin_success.html&display=touch&perms=publish_stream&return_session=1&session_version=3&fbconnect=1&canvas=0&legacy_return=1&method=permissions.request&return_session=1&session_version=3&v=1.0&req_perms=publish_stream&app_id=286811277465&refsrc=http://www.facebook.com/login.php&fbb=r03cdf104"
+                 --> browser dialog is invoked, user enters correct username and password
+            2) http://www.facebook.com/connect/uiserver.php?app_id=286811277465&next=http://www.facebook.com/connect/login_success.html&display=touch&perms=publish_stream&return_session=1&session_version=3&fbconnect=1&canvas=0&legacy_return=1&method=permissions.request&session={"session_key":"2.isKv9bMtGmylvP1N6Il3IQ__.3600.1289394000-100001006647973","uid":100001006647973,"expires":1289394000,"secret":"PWiqZ9_aJjfKKJT4hJMTqA__","sig":"8f054aeca3c4d81e7efce3b90fb17d7e"}&installed=1&refsrc=http://www.facebook.com/login.php&fbb=rff1cc1be&refid=9&m_sess=sozzGNi5-SOBSb3AU
+                 --> click allow
+            3) http://www.facebook.com/connect/uiserver.php
+            4) http://www.facebook.com/connect/login_success.html?perms=publish_stream&selected_profiles=100001006647973&session={"session_key":"2.isKv9bMtGmylvP1N6Il3IQ__.3600.1289394000-100001006647973","uid":"100001006647973","expires":1289394000,"secret":"PWiqZ9_aJjfKKJT4hJMTqA__","access_token":"286811277465|2.isKv9bMtGmylvP1N6Il3IQ__.3600.1289394000-100001006647973|bo9YniMczKY7PwlUEy9f40w3v5I","sig":"6b80d6928cf8f61b4c0c59d33d3127b6"}
+
+        * Login without cookie, not allowed to publish:
+            1) http://m.facebook.com/login.php?api_key=cf77865a5070f2c2ba3b52cbf3371579&display=touch&fbconnect=1&next=http://www.facebook.com/connect/uiserver.php?app_id=286811277465&next=http%3A%2F%2Fwww.facebook.com%2Fconnect%2Flogin_success.html&display=touch&perms=publish_stream&return_session=1&session_version=3&fbconnect=1&canvas=0&legacy_return=1&method=permissions.request&return_session=1&session_version=3&v=1.0&req_perms=publish_stream&app_id=286811277465&refsrc=http://www.facebook.com/login.php&fbb=r3fa0d31d
+                 --> browser dialog is invoked, user enters correct username and password
+            2) http://www.facebook.com/connect/uiserver.php?app_id=286811277465&next=http://www.facebook.com/connect/login_success.html&display=touch&perms=publish_stream&return_session=1&session_version=3&fbconnect=1&canvas=0&legacy_return=1&method=permissions.request&session={"session_key":"2.isKv9bMtGmylvP1N6Il3IQ__.3600.1289394000-100001006647973","uid":100001006647973,"expires":1289394000,"secret":"PWiqZ9_aJjfKKJT4hJMTqA__","sig":"8f054aeca3c4d81e7efce3b90fb17d7e"}&installed=1&refsrc=http://www.facebook.com/login.php&fbb=r29076109&refid=9&m_sess=sozzGNi5-SOBSb3AU
+                 --> click deny
+            3) http://www.facebook.com/connect/uiserver.php
+            4) http://www.facebook.com/connect/login_success.html?perms&selected_profiles=100001006647973&session={"session_key":"2.isKv9bMtGmylvP1N6Il3IQ__.3600.1289394000-100001006647973","uid":"100001006647973","expires":1289394000,"secret":"PWiqZ9_aJjfKKJT4hJMTqA__","access_token":"286811277465|2.isKv9bMtGmylvP1N6Il3IQ__.3600.1289394000-100001006647973|bo9YniMczKY7PwlUEy9f40w3v5I","sig":"6b80d6928cf8f61b4c0c59d33d3127b6"}
+
+        * Login with cookie succeeded, already allowed to publish:
+            1) http://www.facebook.com/connect/uiserver.php?app_id=286811277465&next=http://www.facebook.com/connect/login_success.html&display=touch&cancel_url=http://www.facebook.com/connect/login_failure.html&perms=publish_stream&return_session=1&session_version=3&fbconnect=1&canvas=0&legacy_return=1&method=permissions.request&session={"session_key":"2.iHXi5fLKlHktva2R71xSAw__.3600.1289228400-100001006647973","uid":100001006647973,"expires":1289228400,"secret":"q4_Hn5qRdxnVT_qh3ztv5w__","sig":"c9d29ca857bacec48b952e7d2826a3ca"}&fbb=rb28f24e5
+            2) http://www.facebook.com/connect/login_success.html?perms=publish_stream&selected_profiles=100001006647973&session={"session_key":"2.iHXi5fLKlHktva2R71xSAw__.3600.1289228400-100001006647973","uid":"100001006647973","expires":1289228400,"secret":"q4_Hn5qRdxnVT_qh3ztv5w__","access_token":"286811277465|2.iHXi5fLKlHktva2R71xSAw__.3600.1289228400-100001006647973|LVTHGW82A98SGvv6Fl43DlCrFT0","sig":"8edd8d611047bcd162abbe9983b25a56"}
+     */
+
+    const QString urlString = url.toString();
+    if (!urlString.contains(URL_SESSION_PARAMETER_BEGIN)) {
+        // login page url doesn't contain session
+        /// @todo INVOKE DIALOG ALSO WHEN STOPPED TO PERMISSION PAGE
+        /// @todo case: set cookie, remove situare app, re-login, 1 extra allow page before permissions, redirect from extra page when denying?
+        m_mainWindow->buildLoginDialog(m_browser);
+    } else if (urlString.startsWith(FB_LOGIN_SUCCESS_URL)) {
+        // login succeeded, permissions granted/declined
+        const QString session = parseSession(url);
+        qDebug() << __PRETTY_FUNCTION__ << "login finished, parsed session:" << session;
+        if (!session.isEmpty()) {
+            destroyLogin();
+            m_loggedIn = true;
+            emit loggedIn(session, urlString.contains(WALL_POST_PERMISSION));
+        }
+    }
+    else {
+        qCritical() << __PRETTY_FUNCTION__ << "new url was not recognised, url:" << urlString;
+    }
+}