example/TwitterAuthApp/src/baseDialog.cpp
changeset 26 83d6a149c755
equal deleted inserted replaced
25:a180113055cb 26:83d6a149c755
       
     1 /**
       
     2 * Copyright (c) 2010 Sasken Communication Technologies Ltd.
       
     3 * All rights reserved.
       
     4 * This component and the accompanying materials are made available
       
     5 * under the terms of the "{License}"
       
     6 * which accompanies  this distribution, and is available
       
     7 * at the URL "{LicenseUrl}".
       
     8 *
       
     9 * Initial Contributors:
       
    10 * Narasimhulu Kavadapu, Sasken Communication Technologies Ltd - Initial contribution
       
    11 *
       
    12 * Contributors:
       
    13 * Siddhartha Chandra, Sasken Communication Technologies Ltd
       
    14 * Description:
       
    15 * Base class of All dialogs
       
    16 */
       
    17 
       
    18 #include <QNetworkCookie>
       
    19 #include <QNetworkRequest>
       
    20 #include <QNetworkReply>
       
    21 #include <QWebFrame>
       
    22 #include <QFile>
       
    23 #include <QDesktopServices>
       
    24 #include <QResizeEvent>
       
    25 #include <QDebug>
       
    26 #include <qmessagebox.h>
       
    27 #include <QNetworkAccessManager>
       
    28 #include <QPropertyAnimation>
       
    29 #include <qnetworkproxy.h>
       
    30 #include <qdesktopwidget.h>
       
    31 #include <qapplication.h>
       
    32 //#include <qboxlayout.h>
       
    33 #include "baseDialog.h"
       
    34 #include "sessionSP.h"
       
    35 #include "errorCodes.h"
       
    36 #include "keys.h"
       
    37 #include <QSslConfiguration>
       
    38 
       
    39 static const QString kDefaultTitle = "Connect to Facebook";
       
    40 static const QString kStringBoundary = "3i2ndDfv2rTHiSisAbouNdArYfORhtTPEefj3q2f";
       
    41 
       
    42 static QNetworkAccessManager namanager;
       
    43 
       
    44 /////////////////////////////////////////////////////////////////////////////////////////////////////////////
       
    45 
       
    46 FBDialog::FBDialog() : iSession(FBSession::session()), /*iWebView ( this  ),*/ iIgnorePageLoadCompleteEvent( false )
       
    47 {
       
    48     createControls();
       
    49 }
       
    50 
       
    51 FBDialog::FBDialog(FBSession* aSession) : iSession ( aSession ), /*iWebView ( this  ) ,*/ iIgnorePageLoadCompleteEvent ( false )
       
    52 {
       
    53     createControls();
       
    54 }
       
    55 void FBDialog::createControls()
       
    56 {
       
    57 	iWebView = new QWebView(this);
       
    58     iWebView->page()->setNetworkAccessManager(&namanager);
       
    59 
       
    60     iWebView->page()->setLinkDelegationPolicy(QWebPage::DelegateAllLinks);
       
    61     
       
    62     layout = new QVBoxLayout(this);
       
    63     
       
    64     
       
    65     progressbar = new QProgressBar(this);
       
    66     
       
    67     layout->addWidget(iWebView);
       
    68     //layout->addWidget(progressbar);
       
    69     
       
    70     setLayout(layout);
       
    71     
       
    72     progressbar->setOrientation(Qt::Horizontal);
       
    73     
       
    74 
       
    75     connect( iWebView->page(), SIGNAL(linkClicked(const QUrl &)),
       
    76                     this, SLOT(linkClicked(const QUrl &)));
       
    77 
       
    78     connect ( iWebView->page(), SIGNAL(loadFinished(bool)), this, SLOT(loadFinished(bool)));
       
    79 
       
    80     connect ( iWebView->page(), SIGNAL(loadStarted()), this, SLOT ( loadStarted()));
       
    81     
       
    82     connect ( iWebView->page(), SIGNAL(loadProgress(int)), this, SLOT ( loadProgress(int)));
       
    83     
       
    84     connect (iWebView->page()->networkAccessManager(),SIGNAL( authenticationRequired( QNetworkReply*, QAuthenticator*)),this,SLOT( slotAuthenticationRequired( QNetworkReply*, QAuthenticator*)));
       
    85     connect (iWebView->page()->networkAccessManager(),SIGNAL( sslErrors( QNetworkReply*,QList<QSslError>&)),this,SLOT( slotsslErrors( QNetworkReply*,QList<QSslError>&)) );
       
    86     connect (iWebView->page()->networkAccessManager(),SIGNAL( proxyAuthenticationRequired(QNetworkProxy&, QAuthenticator*)),this,SLOT( slotproxyAuthenticationRequired(QNetworkProxy&, QAuthenticator*)) );
       
    87    // connect ()
       
    88     
       
    89 }
       
    90 QString FBDialog::generateURL( const QString& aUrl, const QHash<QString, QString>& aParams) const
       
    91 {
       
    92 	qDebug()<<"Inside FBDialog::generateURL()";
       
    93     QString url ( aUrl );
       
    94 
       
    95     QStringList pairs;
       
    96     QHashIterator<QString, QString> i(aParams);
       
    97 
       
    98     while (i.hasNext()) {
       
    99         i.next();
       
   100 
       
   101         QUrl url (i.value());
       
   102         QString pair = i.key() + "=" + url.toEncoded();
       
   103         pairs << pair.toUtf8();
       
   104     }
       
   105 
       
   106     if (pairs.count())
       
   107     {
       
   108         url = url + "?" + pairs.join("&");
       
   109     }
       
   110 
       
   111     return url;
       
   112 
       
   113 }
       
   114 
       
   115 QByteArray FBDialog::generatePostBody (const QHash<QString, QString>& aParams) const
       
   116 {
       
   117 	qDebug()<<"Inside FBDialog::generatePostBody()";
       
   118     QByteArray body;
       
   119 
       
   120     if (!aParams.count())
       
   121         return body;
       
   122 
       
   123 
       
   124     QString endLine = "\r\n--" + kStringBoundary + "\r\n", kStringBoundary;
       
   125 
       
   126     QString tmp = "--" + kStringBoundary + "\r\n";
       
   127     body.append(tmp.toUtf8());
       
   128 
       
   129 
       
   130     QHashIterator<QString, QString> i(aParams);
       
   131     while (i.hasNext()) {
       
   132         i.next();
       
   133 
       
   134         tmp = "Content-Disposition: form-data; name=\"" + i.key().toUtf8() + "\"\r\n\r\n" ;
       
   135         body.append(tmp.toUtf8());
       
   136         body.append(i.value().toUtf8());
       
   137         body.append(endLine.toUtf8());
       
   138     }
       
   139 
       
   140     return body;
       
   141 }
       
   142 
       
   143 void FBDialog::postDismissCleanup()
       
   144 {
       
   145     //accept();
       
   146     // could also be reject()?
       
   147 }
       
   148 
       
   149 void FBDialog::dismiss (bool /*aAnimated*/) {
       
   150 	qDebug()<<"Inside FBDialog::dismiss()";
       
   151     dialogWillDisappear();
       
   152     iLoadingUrl.clear();
       
   153 
       
   154     //todo: do some animations if aAnimated == true !
       
   155     postDismissCleanup();
       
   156 }
       
   157 
       
   158 
       
   159 void FBDialog::dismissWithSuccess( bool aSuccess, bool aAnimated)
       
   160 {
       
   161 	qDebug()<<"Inside FBDialog::dismissWithSuccess()";
       
   162   if (aSuccess) {
       
   163         emit dialogDidSucceed();
       
   164   } else {
       
   165         emit dialogDidCancel();
       
   166   }
       
   167 
       
   168   dismiss(aAnimated);
       
   169 }
       
   170 
       
   171 void FBDialog::dismissWithError (const FBError& aError, bool aAnimated)
       
   172 {
       
   173 	qDebug()<<"Inside FBDialog::dismissWithError()";
       
   174 	qDebug()<<"aError"<<aError.description();
       
   175   emit dialogDidFailWithError( aError );
       
   176   dismiss(aAnimated);
       
   177 }
       
   178 void FBDialog::slotAuthenticationRequired( QNetworkReply* reply, QAuthenticator* authenticator )
       
   179 	{
       
   180 		Q_UNUSED(reply)
       
   181 		Q_UNUSED(authenticator)
       
   182 		QMessageBox msgbox;
       
   183 		QString msg ("Error!Authentication Required");
       
   184 		msgbox.setText(msg);
       
   185 	}
       
   186 void FBDialog::slotsslErrors( QNetworkReply* reply, const QList<QSslError>& errors  )
       
   187 	{
       
   188 		Q_UNUSED(reply)
       
   189 		Q_UNUSED(errors)
       
   190 		QMessageBox msgbox;
       
   191 		QString msg ("Error!SSL Error");
       
   192 		msgbox.setText(msg);
       
   193 	}
       
   194 void FBDialog::slotproxyAuthenticationRequired( const QNetworkProxy& proxy, QAuthenticator* authenticator  )
       
   195 	{
       
   196 		Q_UNUSED(proxy)
       
   197 		Q_UNUSED(authenticator)
       
   198 		QMessageBox msgbox;
       
   199 		QString msg ("Error!Proxy Authenticatio Required");
       
   200 		msgbox.setText(msg);
       
   201 	}
       
   202 void FBDialog::cancel()
       
   203 {}
       
   204 
       
   205 void FBDialog::load() {
       
   206 	qDebug()<<"Inside FBDialog::load()";
       
   207 }
       
   208 
       
   209 void FBDialog::show()
       
   210 {
       
   211 	qDebug()<<"Inside FBDialog::show()";
       
   212     load();
       
   213     showMaximized();
       
   214     dialogWillAppear();
       
   215 
       
   216 }
       
   217 
       
   218 void FBDialog::loadURL(const QString& aUrl, QNetworkAccessManager::Operation aMethod, const QHash<QString, QString>& aGetParams, const QHash<QString, QString>&  aPostParams)
       
   219 {   
       
   220 	Q_UNUSED(aMethod)
       
   221 	Q_UNUSED(aGetParams)
       
   222 	Q_UNUSED(aPostParams)
       
   223 	qDebug()<<"Inside FBDialog::loadURL()";
       
   224     //proxysettings();
       
   225     iIgnorePageLoadCompleteEvent = false;
       
   226 
       
   227     QNetworkCookieJar* cookieJar = iWebView->page()->networkAccessManager()->cookieJar();
       
   228     QByteArray body;
       
   229 
       
   230     iLoadingUrl = aUrl;// generateURL(aUrl, aPostParams);/*aUrl;*////*"http://www.google.com/";
       
   231 
       
   232     // This "test cookie" is required by login.php, or it complains that you need to enable JavaScript
       
   233      QNetworkCookie testCookie ("test_cookie", "1");
       
   234      testCookie.setDomain ( "www.linkedin.com" );
       
   235      testCookie.setPath ( "/" );
       
   236 
       
   237     QList<QNetworkCookie> cookieList;
       
   238     cookieList.append(testCookie);
       
   239 
       
   240     cookieJar->setCookiesFromUrl ( cookieList, QUrl(iLoadingUrl) );
       
   241 
       
   242     QUrl url (iLoadingUrl);
       
   243     QNetworkRequest request(url);
       
   244 
       
   245     QSslConfiguration config( QSslConfiguration::defaultConfiguration() );
       
   246 
       
   247 	request.setSslConfiguration( config );
       
   248    /* QString Authorization = "OAuth oauth_nonce=\"" + iSession->stroauth_nonce + "\", oauth_signature_method=\"HMAC-SHA1\", oauth_timestamp=\"" + iSession->stroauth_timestamp + "\", oauth_consumer_key=\"" + kConsumerKey + "\", oauth_signature=\"" + iSession->stroauth_signature + "\", oauth_version=\"1.0\"";
       
   249     qDebug()<<"Authorization: "<<Authorization;
       
   250     QByteArray auth = Authorization.toUtf8();
       
   251     qDebug()<<"auth:"<<auth;
       
   252     //static const char temp[] = "OAuth oauth_nonce="oqwgSYFUD87MHmJJDv7bQqOF2EPnVus7Wkqj5duNByU", oauth_callback="http%3A%2F%2Flocalhost%2Foauth_callback", oauth_signature_method="HMAC-SHA1", oauth_timestamp="1259178158", oauth_consumer_key="ABCDEFGHIJKLMNOPQRSTUVWXYZ", oauth_signature="TLQXuUzM7omwDbtXimn6bLDvfF8=", oauth_version="1.0";
       
   253     if (aMethod == QNetworkAccessManager::PostOperation)
       
   254     {
       
   255 		qDebug()<<"inside : if loop";
       
   256         const QString contentType = "multipart/form-data; boundary=" + kStringBoundary;
       
   257         request.setRawHeader("Authorization",auth);
       
   258         request.setHeader (QNetworkRequest::ContentTypeHeader, contentType);     
       
   259         body = generatePostBody (aPostParams);
       
   260     }
       
   261     bool val = request.hasRawHeader("Authorization");
       
   262     qDebug()<<"Value:"<<val;*/
       
   263     proxysettings();
       
   264     
       
   265     qDebug()<< "Check URL : " << iLoadingUrl;
       
   266 
       
   267     //iWebView->load( request, aMethod, body);
       
   268     iWebView->load(iLoadingUrl);
       
   269     
       
   270 }
       
   271 void FBDialog::proxysettings()
       
   272 {
       
   273 #ifdef EMULATORTESTING
       
   274 	qDebug()<<"proxysettings";
       
   275 	
       
   276 	// Reading the keys, CSM Stubbed - START
       
   277 	QFile file("c:\\data\\DoNotShare.txt");
       
   278 	if (!file.open(QIODevice::ReadOnly))
       
   279 		{
       
   280 		qDebug()<<"File to read the windows username and password could not be opened, returning!!!";
       
   281 		return;
       
   282 		}
       
   283 	
       
   284 	QByteArray arr = file.readAll();
       
   285 	QList<QByteArray> list = arr.split(' ');
       
   286 	file.close();
       
   287 	
       
   288 	QString username(list[0]);
       
   289 	QString password(list[1]);
       
   290 	
       
   291     QString httpProxy = "10.1.0.214";//ipwproxy.sasken.com
       
   292     QString httpPort = "3128";
       
   293 
       
   294     QString httpUser =username;/* This could be taken thru an QDialog implmentation to remove the Hard coding */
       
   295     QString httpPass =password;/* This could be taken thru an QDialog implmentation to remove the Hard coding */
       
   296 
       
   297     /*==Classes used from Network Module==*/
       
   298     QNetworkProxy proxy;
       
   299 
       
   300     proxy.setType(QNetworkProxy::HttpProxy);
       
   301     proxy.setHostName(httpProxy);
       
   302     proxy.setPort(httpPort.toInt());
       
   303     proxy.setUser(httpUser);
       
   304     proxy.setPassword(httpPass);
       
   305 
       
   306     QNetworkProxy::setApplicationProxy(proxy);
       
   307 #endif
       
   308 }
       
   309 void FBDialog::dialogWillAppear() {}
       
   310 
       
   311 void FBDialog::dialogWillDisappear() {}
       
   312 
       
   313 void FBDialog::dialogDidSucceed (const QUrl& /*aUrl*/) {
       
   314   dismissWithSuccess(true,true);
       
   315 }
       
   316 
       
   317 /////////////////////////////////////////////////////////////////////////////////////////////////////////////
       
   318 void FBDialog::linkClicked ( const QUrl & url )
       
   319  {
       
   320 
       
   321         qDebug() << "Loading the url: " <<  url;
       
   322         
       
   323         proxysettings();
       
   324 			
       
   325         iWebView->load(url);
       
   326 }
       
   327 
       
   328 void FBDialog::loadStarted()
       
   329 {
       
   330     qDebug() << "Load started: " << iWebView->url();
       
   331     layout->addWidget(progressbar);
       
   332     progressbar->setVisible(true);
       
   333 }
       
   334 void FBDialog::loadProgress(int progress)
       
   335 {
       
   336 	progressbar->setValue(progress);
       
   337 }
       
   338 void FBDialog::GetSessionKey(const QUrl& aUrl)
       
   339 {
       
   340 	Q_UNUSED(aUrl)
       
   341 }
       
   342 void FBDialog::FetchKeyFromUrl(const QUrl& aUrl)
       
   343 {
       
   344 	Q_UNUSED(aUrl)
       
   345 }
       
   346 void FBDialog::loadFinished ( bool ok )
       
   347 {
       
   348     qDebug() << "Load " << (ok ? "" : "un") << "successfull for: " << iWebView->url();
       
   349     progressbar->setVisible(false);
       
   350     layout->removeWidget(progressbar);
       
   351     if (ok)
       
   352     {
       
   353 		QString PAth = iWebView->url().toString();
       
   354 		PAth = PAth.mid(0,PAth.indexOf("?"));
       
   355 		
       
   356 		qDebug() << "Path is : " << PAth;
       
   357 		if(iWebView->url().toString() == kBase)
       
   358 			{
       
   359 				QString myhtml  = iWebView->page()->currentFrame()->toHtml();
       
   360 				QString myhtml2  = iWebView->page()->currentFrame()->toPlainText();
       
   361 				
       
   362 				//qDebug()<<"myhtml"<<myhtml;
       
   363 				//qDebug()<<"myhtml2"<<myhtml2;
       
   364 				int val = myhtml.indexOf("<div id=\"oauth_pin\">",0);
       
   365 				//int val2 = myhtml2.indexOf("Simply return to SMF Framework and enter the following PIN to complete the process.",0);
       
   366 				QString newval = myhtml.mid(val + 20,20);
       
   367 				//QString newval2 = myhtml2.mid(val2 + 83,10);
       
   368 				qDebug()<<"newval"<<newval;
       
   369 				//qDebug()<<"newval"<<newval2;
       
   370 				QStringList list = newval.split("<");
       
   371 				iSession->stroauth_verifier = list[0];
       
   372 				qDebug()<<"iSession->stroauth_verifier"<<iSession->stroauth_verifier;
       
   373 				iWebView->close();
       
   374 				GetAccessToken();
       
   375 				
       
   376 			}
       
   377 		/*if(kBase.compare(PAth) == 0){
       
   378 		
       
   379 			QByteArray URL = iWebView->url().encodedQuery();
       
   380 			qDebug() << "Encoded Query is : " << URL;
       
   381 			
       
   382 			if(URL.contains("auth_token"))
       
   383 				{
       
   384 					qDebug() << "URL contains auth token";
       
   385 					iWebView->setHidden(true);
       
   386 					QMessageBox msgbox;
       
   387 					QString msg ("Logged in Success!!!Complete the Authorization?");
       
   388 					msgbox.setText(msg);
       
   389 					if(msgbox.exec() == QMessageBox::Ok){
       
   390 						GetSessionKey(iWebView->url());
       
   391 					}else{
       
   392 						
       
   393 					}
       
   394 				}
       
   395 			else if(URL.contains("session_key") && URL.contains("uid"))
       
   396 				{
       
   397 					FetchKeyFromUrl(iWebView->url());
       
   398 				}
       
   399 			else
       
   400 				{
       
   401 					qDebug() << "URL doesnt have auth_token field";
       
   402 					iWebView->setHidden(true);
       
   403 					QMessageBox msgbox;
       
   404 					QString msg ("Permissions Success!!!continue login?");
       
   405 					msgbox.setText(msg);
       
   406 					if(msgbox.exec() == QMessageBox::Ok){
       
   407 						iWebView->setHidden(false);
       
   408 						load();
       
   409 					}else{
       
   410 						
       
   411 					}
       
   412 				}
       
   413 		}*/
       
   414     }
       
   415     else
       
   416     {
       
   417         if (iIgnorePageLoadCompleteEvent)
       
   418             return;
       
   419 
       
   420         FBError err;
       
   421         dismissWithError(err, true);
       
   422     }
       
   423 }
       
   424 void FBDialog::GetAccessToken() {
       
   425 	qDebug()<<"Inside FBDialog::GetAccessToken()";
       
   426 }