431c4121d3a12864d3f4eacfcfe156f3750c0705
[situare] / src / facebookservice / facebookauthentication.cpp
1 /*
2    Situare - A location system for Facebook
3    Copyright (C) 2010  Ixonos Plc. Authors:
4
5        Ville Tiensuu - ville.tiensuu@ixonos.com
6        Kaj Wallin - kaj.wallin@ixonos.com
7        Henri Lampela - henri.lampela@ixonos.com
8
9    Situare is free software; you can redistribute it and/or
10    modify it under the terms of the GNU General Public License
11    version 2 as published by the Free Software Foundation.
12
13    Situare is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with Situare; if not, write to the Free Software
20    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,
21    USA.
22 */
23
24 #include <qjson/parser.h>
25
26 #include <QtDebug>
27 #include <QDateTime>
28 #include <QNetworkReply>
29 #include <QSettings>
30 #include <QStringList>
31 #include <QVariantMap>
32 #include <QWebView>
33
34 #ifdef Q_WS_MAEMO_5
35 #include <QMaemo5InformationBox>
36 #endif // Q_WS_MAEMO_5
37
38 #include "common.h"
39 #include "../error.h"
40 #include "network/networkcookiejar.h"
41 #include "situareservice/situarecommon.h"
42 #include "ui/mainwindow.h"
43
44 #include "facebookauthentication.h"
45
46 const QString FB_LOGIN_SUCCESS_URL = "http://www.facebook.com/connect/login_success.html";
47 const QString FB_LOGIN_URL = "https://www.facebook.com/login.php";
48
49 FacebookAuthentication::FacebookAuthentication(MainWindow *mainWindow, QObject *parent)
50     : QObject(parent),
51       m_loggedIn(false),
52       m_browser(0),
53       m_mainWindow(mainWindow)
54 {
55     qDebug() << __PRETTY_FUNCTION__;
56 }
57
58 void FacebookAuthentication::browserDestroyed()
59 {
60     qWarning() << __PRETTY_FUNCTION__;
61
62     m_mainWindow->toggleProgressIndicator(false);
63     m_browser = 0;
64 }
65
66 void FacebookAuthentication::clearAccountInformation(bool clearUserInformation)
67 {
68     qWarning() << __PRETTY_FUNCTION__ << "clearUserInformation:" << clearUserInformation;
69
70     QSettings settings(SETTINGS_ORGANIZATION_NAME, SETTINGS_APPLICATION_NAME);
71
72     settings.remove(USER_UNSEND_MESSAGE);
73     settings.remove(USER_UNSEND_MESSAGE_PUBLISH);
74
75     if (clearUserInformation) {
76         NetworkCookieJar::clearCookiesSetting();
77         settings.remove(SETTINGS_AUTOMATIC_UPDATE_ENABLED);
78         settings.remove(SETTINGS_AUTOMATIC_UPDATE_INTERVAL);
79     }
80 }
81
82 void FacebookAuthentication::destroyLogin()
83 {
84     qWarning() << __PRETTY_FUNCTION__;
85
86     m_mainWindow->destroyLoginDialog();
87     m_browser->deleteLater();
88 }
89
90 bool FacebookAuthentication::isLoggedIn() const
91 {
92     qWarning() << __PRETTY_FUNCTION__;
93
94     return m_loggedIn;
95 }
96
97 void FacebookAuthentication::login()
98 {
99     qWarning() << __PRETTY_FUNCTION__;
100
101     if (!m_browser) {
102         m_browser = new QWebView(m_mainWindow);
103
104         if (m_browser) {
105             m_browser->page()->networkAccessManager()->setCookieJar(new NetworkCookieJar());
106
107             connect(m_browser, SIGNAL(urlChanged(QUrl)),
108                     this, SLOT(urlChanged(QUrl)));
109
110             connect(m_browser, SIGNAL(destroyed(QObject*)),
111                     this, SLOT(browserDestroyed()));
112
113             connect(m_browser->page()->networkAccessManager(),
114                     SIGNAL(sslErrors(QNetworkReply*, QList<QSslError>)),
115                     this, SLOT(sslErrors(QNetworkReply*, QList<QSslError>)));
116
117             connect(m_browser->page()->networkAccessManager(), SIGNAL(finished(QNetworkReply*)),
118                     this, SLOT(networkReplyHandler(QNetworkReply*)));
119         }
120     }
121
122     if (m_browser) {
123         QString url = FB_LOGIN_URL + "?";
124         url.append("api_key=" + API_KEY +"&");
125         url.append("display=touch&");
126         url.append("fbconnect=1&");
127         url.append("next=" + FB_LOGIN_SUCCESS_URL + "&");
128         url.append("return_session=1&");
129         url.append("session_version=3&");
130         url.append("v=1.0&");
131         url.append("req_perms=publish_stream");
132
133         m_browser->load(QUrl(url));
134
135         m_mainWindow->toggleProgressIndicator(true);
136     }
137 }
138
139 void FacebookAuthentication::logOut(bool clearUserInformation)
140 {
141     qWarning() << __PRETTY_FUNCTION__;
142
143     clearAccountInformation(clearUserInformation);
144     m_loggedIn = false;
145     emit loggedOut();
146 }
147
148 void FacebookAuthentication::networkReplyHandler(QNetworkReply *reply)
149 {
150     qWarning() <<__PRETTY_FUNCTION__;
151
152     if ((reply->error() != QNetworkReply::NoError)
153         && (reply->error() != QNetworkReply::OperationCanceledError)) {
154
155         qCritical() << __PRETTY_FUNCTION__ << "error:" << reply->error() << reply->errorString();
156         emit error(ErrorContext::NETWORK, reply->error());
157         destroyLogin();
158     }
159 }
160
161 QString FacebookAuthentication::parseSession(const QUrl &url)
162 {
163     qWarning() << __PRETTY_FUNCTION__;
164
165     const QString BEGIN("session={");
166     const QString END("}");
167
168     QString urlString = url.toString();
169
170     int begin = urlString.indexOf(BEGIN);
171     int end = urlString.indexOf(END, begin);
172
173     if ((begin > -1) && (end > -1))
174         return urlString.mid(begin, end - begin + 1);
175     else
176         return QString();
177 }
178
179 void FacebookAuthentication::sslErrors(QNetworkReply *reply, const QList<QSslError> &errors)
180 {
181     qWarning() << __PRETTY_FUNCTION__;
182
183     Q_UNUSED(errors);
184     reply->ignoreSslErrors();
185 }
186
187 void FacebookAuthentication::urlChanged(const QUrl &url)
188 {
189     qWarning() << __PRETTY_FUNCTION__ << url.toString();
190
191     /*
192       Redirects:
193         * Login with cookie failed:
194             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
195
196         * Login with cookie succeeded:
197             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
198             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"}
199      */
200
201     if (!url.toString().contains("session={")) {
202         // url parameter doesn't contain session data, so login with cookies failed
203         qWarning() << __PRETTY_FUNCTION__ << "working credentials required";
204         m_mainWindow->buildLoginDialog(m_browser);
205     } else if (url.toString().startsWith(FB_LOGIN_SUCCESS_URL)) {
206         // login succeeded
207         const QString session = parseSession(url);
208         qWarning() << __PRETTY_FUNCTION__ << "login finished, parsed session:" << session;
209         if (!session.isEmpty()) {
210             destroyLogin();
211             m_loggedIn = true;
212             emit loggedIn(session);
213         }
214     }
215     else {
216         qWarning() << __PRETTY_FUNCTION__ << "credentials accepted, getting the access_token";
217     }
218 }