USA.
*/
-#include <QtGui>
+#include "parser.h"
+
#include <QtDebug>
#include <QDateTime>
+#include <QSettings>
+#include <QStringList>
+#include <QVariantMap>
#ifdef Q_WS_MAEMO_5
#include <QMaemo5InformationBox>
#endif // Q_WS_MAEMO_5
-#include "facebookauthentication.h"
+#include "common.h"
+#include "error.h"
#include "facebookcommon.h"
-FacebookAuthentication::FacebookAuthentication(QWidget *parent)
- : QMainWindow(parent)
+#include "facebookauthentication.h"
+
+const QString REDIRECT_URI = "http://www.facebook.com/connect/login_success.html";
+
+FacebookAuthentication::FacebookAuthentication(QObject *parent)
+ : QObject(parent),
+ m_freshLogin(false)
{
qDebug() << __PRETTY_FUNCTION__;
- m_refresh = false;
- m_email.clear();
- m_password.clear();
- m_loginAttempts = 0;
-
- m_loginDialog = new LoginDialog(this);
+}
- m_webView = new QWebView;
- m_mainlayout = new QHBoxLayout;
+void FacebookAuthentication::clearAccountInformation(bool keepUsername)
+{
+ qDebug() << __PRETTY_FUNCTION__;
- m_facebookLoginPage = formLoginPage(FACEBOOK_LOGINBASE, SITUARE_PUBLIC_FACEBOOKAPI_KEY,
- INTERVAL1, SITUARE_LOGIN_SUCCESS, INTERVAL2,
- SITUARE_LOGIN_FAILURE, FACEBOOK_LOGIN_ENDING);
+ m_loginCredentials.clearCredentials();
+ QSettings settings(DIRECTORY_NAME, FILE_NAME);
- connect(m_webView, SIGNAL(urlChanged(const QUrl &)),
- this, SLOT(updateCredentials(const QUrl &)));
- connect(m_webView, SIGNAL(loadFinished(bool)),
- this, SLOT(loadDone(bool)));
+ if(!keepUsername) {
+ settings.remove(USERNAME);
+ settings.remove(SETTINGS_AUTOMATIC_UPDATE_ENABLED);
+ settings.remove(SETTINGS_AUTOMATIC_UPDATE_INTERVAL);
+ }
- connect(m_loginDialog, SIGNAL(loginDialogDone(QString,QString)),
- this, SLOT(loginDialogDone(QString,QString)));
+ settings.remove(COOKIES);
+ settings.remove(USER_UNSEND_MESSAGE);
+ settings.remove(USER_UNSEND_MESSAGE_PUBLISH);
+}
- connect(this, SIGNAL(loginFailure()),
- this, SLOT(loginFailed()));
+void FacebookAuthentication::loadFinished(bool ok)
+{
+ qWarning() << __PRETTY_FUNCTION__ << ok;
- readCredentials(m_loginCredentials);
+ ///< @todo show browsed window if url != redirect url
}
-FacebookAuthentication::~FacebookAuthentication()
+const QString FacebookAuthentication::loadUsername()
{
qDebug() << __PRETTY_FUNCTION__;
- if(m_webView) {
- delete m_webView;
- m_webView = 0;
- }
- if(m_mainlayout) {
- delete m_mainlayout;
- m_mainlayout = 0;
- }
- if(m_loginDialog) {
- delete m_loginDialog;
- m_loginDialog = 0;
- }
+ QSettings settings(DIRECTORY_NAME, FILE_NAME);
+ return settings.value(USERNAME, EMPTY).toString();
}
-void FacebookAuthentication::loginDialogDone(const QString &email, const QString &password)
+FacebookCredentials FacebookAuthentication::loginCredentials() const
{
qDebug() << __PRETTY_FUNCTION__;
-
- m_email.append(email);
- m_password.append(password);
+ return m_loginCredentials;
}
-void FacebookAuthentication::start()
+QString FacebookAuthentication::parseAccessToken(const QUrl &url)
{
- qDebug() << __PRETTY_FUNCTION__;
- if (!verifyCredentials(m_loginCredentials)){
- if(m_loginDialog->exec() != QDialog::Accepted) {
- // if login dialog was canceled we need to stop processing webview
- // stop and disconnect m_webView;
- m_webView->stop();
- disconnect(m_webView, SIGNAL(loadFinished(bool)),
- this, SLOT(loadDone(bool)));
- disconnect(m_webView, SIGNAL(urlChanged(const QUrl &)),
- this, SLOT(updateCredentials(const QUrl &)));
-
- emit quitSituare();
- }
- m_webView->setZoomFactor(FACEBOOK_LOGINPAGE_FONT_SIZE);
- m_webView->load(m_facebookLoginPage);
- this->toggleProgressIndicator(true);
- m_refresh = true;
- setCentralWidget(m_webView);
- m_webView->hide();
- this->show();
- }
+ qWarning() << __PRETTY_FUNCTION__;
+
+ const QString ACCESS_TOKEN_PARAMETER("#access_token=");
+ const QString EXPIRATION_PARAMETER("&expires_in=");
+
+ QString urlString = url.toString();
+
+ int begin = urlString.indexOf(ACCESS_TOKEN_PARAMETER) + ACCESS_TOKEN_PARAMETER.length();
+ int end = urlString.indexOf(EXPIRATION_PARAMETER);
+
+ if ((begin > -1) && (end > begin))
+ return urlString.mid(begin, end - begin);
else
- emit credentialsReady(m_loginCredentials);
+ return QString();
}
-void FacebookAuthentication::loadDone(bool done)
+void FacebookAuthentication::saveUsername(const QString &username)
{
qDebug() << __PRETTY_FUNCTION__;
- // for the first time the login page is opened, we need to refresh it to get cookies working
- if(m_refresh) {
- m_webView->load(m_facebookLoginPage);
- m_refresh = false;
- }
-
- if (done)
- {
- this->toggleProgressIndicator(false);
- QWebFrame* frame = m_webView->page()->currentFrame();
- if (frame!=NULL)
- {
- // set email box
- QWebElementCollection emailCollection = frame->findAllElements("input[name=email]");
-
- foreach (QWebElement element, emailCollection) {
- element.setAttribute("value", m_email.toAscii());
- }
- // set password box
- QWebElementCollection passwordCollection = frame->findAllElements("input[name=pass]");
- foreach (QWebElement element, passwordCollection) {
- element.setAttribute("value", m_password.toAscii());
- }
- // find connect button
- QWebElementCollection buttonCollection = frame->findAllElements("input[name=login]");
- foreach (QWebElement element, buttonCollection)
- {
- QPoint pos(element.geometry().center());
-
- // send a mouse click event to the web page
- QMouseEvent event0(QEvent::MouseButtonPress, pos, Qt::LeftButton, Qt::LeftButton, Qt::NoModifier);
- QApplication::sendEvent(m_webView->page(), &event0);
- QMouseEvent event1(QEvent::MouseButtonRelease, pos, Qt::LeftButton, Qt::LeftButton, Qt::NoModifier);
- QApplication::sendEvent(m_webView->page(), &event1);
- }
- }
- }
+ QSettings settings(DIRECTORY_NAME, FILE_NAME);
+ settings.setValue(USERNAME, username);
}
-void FacebookAuthentication::loginFailed()
+void FacebookAuthentication::start()
{
qDebug() << __PRETTY_FUNCTION__;
- m_email.clear();
- m_password.clear();
-
-#ifdef Q_WS_MAEMO_5
- QMaemo5InformationBox::information(this, tr("Invalid E-mail address or password"),
- QMaemo5InformationBox::NoTimeout);
-
-#endif // Q_WS_MAEMO_5
-
- if(m_loginDialog->exec() != QDialog::Accepted) {
- // if login dialog was canceled we need to stop processing webview
- // stop and disconnect m_webView;
- m_webView->stop();
- disconnect(m_webView, SIGNAL(loadFinished(bool)),
- this, SLOT(loadDone(bool)));
- disconnect(m_webView, SIGNAL(urlChanged(const QUrl &)),
- this, SLOT(updateCredentials(const QUrl &)));
+ QSettings settings(DIRECTORY_NAME, FILE_NAME);
- emit quitSituare();
+ QStringList cookies = settings.value(COOKIES).toStringList();
+ if(!cookies.isEmpty()) {
+ emit loginUsingCookies();
}
else {
- // re-load login page for webview
- this->toggleProgressIndicator(true);
- m_webView->setZoomFactor(FACEBOOK_LOGINPAGE_FONT_SIZE);
- m_webView->load(m_facebookLoginPage);
+ m_freshLogin = true;
+ emit newLoginRequest();
}
}
bool FacebookAuthentication::updateCredentials(const QUrl &url)
-{
- qDebug() << __PRETTY_FUNCTION__;
+{
+ qDebug() << __PRETTY_FUNCTION__ << url.toString();
- bool foundSessionKey = FALSE;
- bool foundUserID = FALSE;
- bool foundExpires = FALSE;
- bool foundSessionSecret = FALSE;
- bool foundSig = FALSE;
+ bool found = false;
- if (url.isValid()){
- qDebug() << "url is valid" << endl;
+ if (url.isValid()) {
+ qDebug() << "url is valid";
QString callbackUrl = url.toString();
- QString urlEdit(callbackUrl);
- qDebug() << "callbackUrl: " << endl << callbackUrl.toAscii() << endl;
-
- if ( callbackUrl.indexOf(LOGIN_SUCCESS_REPLY) == 0 ){
- qDebug() << "login success" << endl;
-
- disconnect(m_webView, SIGNAL(loadFinished(bool)),
- this, SLOT(loadDone(bool)));
- disconnect(m_webView, SIGNAL(urlChanged(const QUrl &)),
- this, SLOT(updateCredentials(const QUrl &)));
-
- // let's find out session key
- int indexOfCredential = callbackUrl.indexOf(SESSION_KEY);
-
- if (indexOfCredential != -1){
- foundSessionKey = TRUE;
-
- indexOfCredential += 14; //lenght of SESSION_KEY
- urlEdit.remove(0,indexOfCredential);
- indexOfCredential = urlEdit.indexOf(USER_ID);
- urlEdit.remove(indexOfCredential, urlEdit.length());
- urlEdit.remove("\",\"");
-
- qDebug() << "Session Key" << endl << urlEdit.toAscii() << endl;
- m_loginCredentials.setSessionKey(urlEdit);
- }
-
- // let's find out uid
- urlEdit = callbackUrl;
- indexOfCredential = callbackUrl.indexOf(USER_ID);
-
- if (indexOfCredential != -1){
- foundUserID = TRUE;
-
- indexOfCredential += 5; //length of USER_ID:
- urlEdit.remove(0,indexOfCredential);
- indexOfCredential = urlEdit.indexOf(EXPIRES);
- urlEdit.remove(indexOfCredential, urlEdit.length());
- urlEdit.remove(",\"");
-
- qDebug() << "userID" << endl << urlEdit.toAscii() << endl;
- m_loginCredentials.setUserID(urlEdit);
- }
-
- // let's find out expires
- urlEdit = callbackUrl;
- indexOfCredential = callbackUrl.indexOf(EXPIRES);
-
- if (indexOfCredential != -1){
- foundExpires = TRUE;
-
- indexOfCredential += 9; //length of EXPIRES
- urlEdit.remove(0,indexOfCredential);
- indexOfCredential = urlEdit.indexOf(SESSION_SECRET);
- urlEdit.remove(indexOfCredential, urlEdit.length());
- urlEdit.remove(",\"");
-
- qDebug() << "Expires" << endl << urlEdit.toAscii() << endl;
- m_loginCredentials.setExpires(urlEdit);
- }
-
- // let's find out sessionsecret
- urlEdit = callbackUrl;
- indexOfCredential = callbackUrl.indexOf(SESSION_SECRET);
-
- if (indexOfCredential != -1){
- foundSessionSecret = TRUE;
-
- indexOfCredential += 9; //" length of SESSION_SECRET
- urlEdit.remove(0,indexOfCredential);
- indexOfCredential = urlEdit.indexOf(SIGNATURE);
- urlEdit.remove(indexOfCredential, urlEdit.length());
- urlEdit.remove("\",\"");
-
- qDebug() << "Session Secret" << endl << urlEdit.toAscii() << endl;
- m_loginCredentials.setSessionSecret(urlEdit);
- }
-
- // let's find out sig
- urlEdit = callbackUrl;
- indexOfCredential = callbackUrl.indexOf(SIGNATURE);
-
- if (indexOfCredential != -1){
- foundSig = TRUE;
-
- indexOfCredential += 6; //" length of SIGNATURE
- urlEdit.remove(0,indexOfCredential);
- urlEdit.remove("\"}");
-
- qDebug() << "Signature" << endl << urlEdit.toAscii() << endl;
- m_loginCredentials.setSig(urlEdit);
+ qDebug() << "callbackUrl: " << callbackUrl.toAscii();
+
+ if (callbackUrl.indexOf(LOGIN_SUCCESS_REPLY) == 0) {
+ qDebug() << "login success";
+
+ // let's find out session credentials
+ if(callbackUrl.contains(SESSION_KEY)) {
+
+ QJson::Parser parser;
+ bool ok;
+
+ // split string into string part and json part
+ QStringList list = url.toString().split("=");
+
+ for(int i=0;i<list.count();i++) {
+ // if string starts with json item
+ if(list.at(i).startsWith("{")) {
+ QByteArray jsonString = list.at(i).toAscii();
+ QVariantMap result = parser.parse (jsonString, &ok).toMap();
+
+ if (!ok) {
+ emit error(ErrorContext::SITUARE, SituareError::INVALID_JSON);
+ found = false;
+ } else {
+ qDebug() << "Session Key" << result[SESSION_KEY].toString();
+ m_loginCredentials.setSessionKey(result[SESSION_KEY].toString());
+
+ // // commeted out until qjson parser can handle 64-bit integers
+ // qDebug() << "userID" << result[USER_ID].toString();
+ // m_loginCredentials.setUserID(result[USER_ID].toString().toAscii());
+
+ // dirty fix, get user id from session_key
+ QStringList list = result[SESSION_KEY].toString().split("-");
+ m_loginCredentials.setUserID(list.at(1));
+ qDebug() << m_loginCredentials.userID();
+
+ qDebug() << "Expires" << result[EXPIRES].toString();
+ m_loginCredentials.setExpires(result[EXPIRES].toString());
+
+ qDebug() << "Session Secret" << result[SESSION_SECRET].toString();
+ m_loginCredentials.setSessionSecret(result[SESSION_SECRET].toString());
+
+ qDebug() << "Signature" << result[SIGNATURE].toString();
+ m_loginCredentials.setSig(result[SIGNATURE].toString());
+
+ found = true;
+ m_freshLogin = false;
+ emit saveCookiesRequest();
+ emit credentialsReady(m_loginCredentials);
+ }
+ }
+ }
}
-
- m_webView->hide();
- writeCredentials(m_loginCredentials);
- emit credentialsReady(m_loginCredentials);
- }
-
- else if ( callbackUrl.indexOf(LOGIN_FAILURE_REPLY) == 0){
- qWarning() << "login failure" << endl;
+ } else if ( callbackUrl.indexOf(LOGIN_FAILURE_REPLY) == 0) {
+ qDebug() << "login failure";
qDebug() << callbackUrl;
- ++m_loginAttempts;
- /* emit loginFailure for every second login attemps, since webview loads login
- error page (loadingDone() signal is emitted) and we need to avoid that because
- at this point we don't have new login parameters */
- if(m_loginAttempts % 2) {
- emit loginFailure();
+ clearAccountInformation(true);
+ if(m_freshLogin) {
+ emit error(ErrorContext::SITUARE, SituareError::LOGIN_FAILED);
+ } else {
+ m_freshLogin = true;
+ emit error(ErrorContext::SITUARE, SituareError::SESSION_EXPIRED);
}
- }
-
- else if ( callbackUrl.indexOf(LOGIN_PAGE) == 0){
+ } else if(callbackUrl.indexOf(LOGIN_PAGE) == 0) {
qDebug() << "correct loginPage";
- }
-
- else {
+ } else {
qDebug() << "totally wrong webPage";
// we should not get a wrong page at this point
- emit loginFailure();
+ emit error(ErrorContext::SITUARE, SituareError::LOGIN_FAILED);
}
- }
-
- else {
+ } else {
qDebug() << " Loading of page failed invalid URL" << endl;
// we should not get a wrong page at this point
- emit loginFailure();
- return FALSE;
+ emit error(ErrorContext::SITUARE, SituareError::LOGIN_FAILED);
}
-
- return (foundSessionKey && foundUserID && foundExpires && foundSessionSecret && foundSig);
+ return found;
}
-void FacebookAuthentication::writeCredentials(const FacebookCredentials &credentials)
+void FacebookAuthentication::urlChanged(const QUrl &url)
{
- qDebug() << __PRETTY_FUNCTION__;
- QSettings settings(DIRECTORY_NAME, FILE_NAME);
-
- settings.setValue("Session Key", credentials.sessionKey());
- settings.setValue("User ID", credentials.userID());
- settings.setValue("Expires", credentials.expires());
- settings.setValue("Session Secret", credentials.sessionSecret());
- settings.setValue("Sig", credentials.sig());
-}
+ qWarning() << __PRETTY_FUNCTION__ << url.toString();
-void FacebookAuthentication::readCredentials(FacebookCredentials &credentialsFromFile)
-{
- qDebug() << __PRETTY_FUNCTION__;
-
- QSettings settings(DIRECTORY_NAME, FILE_NAME);
-
- 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());
+ // if login succeeded
+ if (url.toString().startsWith(REDIRECT_URI)) {
+ ///< @todo hide browser dialog
+ qWarning() << __PRETTY_FUNCTION__ << "access_token:" << parseAccessToken(url);
+ }
}
-
- FacebookCredentials FacebookAuthentication::loginCredentials() const
- {
- qDebug() << __PRETTY_FUNCTION__;
- return m_loginCredentials;
- }
-
- bool FacebookAuthentication::verifyCredentials(const FacebookCredentials &credentials) const
- {
- qDebug() << __PRETTY_FUNCTION__;
-
- // if expires value is 0, then credentials are valid forever
- if(credentials.expires() == "0") {
- return true;
- }
- else {
- QString expires = credentials.expires();
- QDateTime expireTime;
- expireTime.setTime_t(expires.toInt());
- QString expiresString = expireTime.toString("dd.MM.yyyy hh:mm:ss");
- qDebug() << expiresString.toAscii();
-
- QDateTime currentTime;
- currentTime = QDateTime::currentDateTime();
- QString currentTimeString = currentTime.toString("dd.MM.yyyy hh:mm:ss");
- qDebug() << currentTimeString.toAscii();
-
- return currentTime < expireTime;
- }
- }
-
- QString FacebookAuthentication::formLoginPage(const QString & part1, const QString & part2,
- const QString & part3, const QString & part4,
- const QString & part5, const QString & part6,
- const QString & part7) const
- {
- QString loginPage;
- loginPage.append(part1);
- loginPage.append(part2);
- loginPage.append(part3);
- loginPage.append(part4);
- loginPage.append(part5);
- loginPage.append(part5);
- loginPage.append(part6);
- loginPage.append(part7);
-
- return loginPage;
- }
-
- void FacebookAuthentication::toggleProgressIndicator(bool value)
- {
- qDebug() << __PRETTY_FUNCTION__;
- #ifdef Q_WS_MAEMO_5
- setAttribute(Qt::WA_Maemo5ShowProgressIndicator, value);
- #else
- Q_UNUSED(value);
- #endif // Q_WS_MAEMO_5
- }