Log in to Facebook with phantomjs - 302 issues? - redirect

I'm trying to write a phantomjs script to log in to my facebook account and take a screenshot.
Here's my code:
var page = require('webpage').create();
var system = require('system');
var stepIndex = 0;
var loadInProgress = false;
email = system.args[1];
password = system.args[2];
page.onLoadStarted = function() {
loadInProgress = true;
console.log("load started");
};
page.onLoadFinished = function() {
loadInProgress = false;
console.log("load finished");
};
var steps = [
function() {
page.open("http://www.facebook.com/login.php", function(status) {
page.evaluate(function(email, password) {
document.querySelector("input[name='email']").value = email;
document.querySelector("input[name='pass']").value = password;
document.querySelector("#login_form").submit();
console.log("Login submitted!");
}, email, password);
page.render('output.png');
});
},
function() {
console.log(document.documentElement.innerHTML);
},
function() {
phantom.exit();
}
]
setInterval(function() {
if (!loadInProgress && typeof steps[stepIndex] == "function") {
console.log("step " + (stepIndex + 1));
steps[stepIndex]();
stepIndex++;
}
if (typeof steps[stepIndex] != "function") {
console.log("test complete!");
phantom.exit();
}
}, 10000);
(Inspired by this answer, but note that I've upped the interval to 10s)
Called like so:
./phantomjs test.js <email> <password>
With output (filtering out the selfxss warnings from Facebook):
step 1
load started
load finished
Login submitted!
load started
load finished
step 2
<head></head><body></body>
step 3
test
complete!
(Note that the html output in step two is empty)
This answer suggests that there are problems with phantomjs' SSL options, but running with --ssl-protocol=any has no effect.
This appears to be a similar problem, but for caspar, not phantomjs (and on Windows, not Mac) - I've tried using --ignore-ssl-errors=yes, but that also had no effect.
I guessed that this might be a redirection problem (and, indeed, when I replicate this on Chrome, the response from clicking "Submit" was a 302 Found with location https://www.facebook.com/checkpoint/?next), but according to this documentation I can set a page.onNavigationRequested handler - when I do so in my script, it doesn't get called.
I think this issue is related, but it looks as if there's no fix there.

Related

How we do Exception handling in protractor-cucumber and do a email notification

I am using Protractor-Cucumber framework with protractor 5.2.2 and cucumber 3.2. I have a requirement of posting in no.of locations. So I have written a script in a loop for it. But it randomly fails before completing the loop. So when the script ends abnormally, is there like an exception handling section that gets control before exiting.The script can be fail due to any of the reasons like web driver issue,NoSuchElementError,ElementIsNotIntractable,ElementIsNotVisible etc.So whatever be the issue I have to handle that, and if it fails, I have to do an email notification. I have tried try catch, as given below, but it does not work for me.
When(/^I login$/, function () {
try{
element(by.css(".signin")).click();
var count=post_details.length ;
for (var i=0; i<count; i++){
post();
}
}
catch(e){
console.log("failed");
}
});
How we can do this in protractor-cucumber.Thanks in advance
For the exception problem you can try this. ignoreUncaughtException
For the email part create a hooks.js file. Here you can setup the After() function, to check your scenario fails or not. Cucumber Docs.
Example:
After(function (scenario) {
if (scenario.result.status === Status.FAILED)
{
failed = true;
const attach = this.attach;
//creates a screenshot for the report
return browser.takeScreenshot().then(function(png) {
return attach(new Buffer(png, "base64"), "image/png");
});
}
});
Then you can use nodemailer to send messages. Nodemailer
In your AfterAll() function you can handle the send part.
Example:
AfterAll(function(callback){
console.log("AfterAll");
if (failed)
{
var transporter = nodemailer.createTransport(
{
host: 'host.com',
port: xx,
secure: false,
//proxy: 'http://10.10.10.6:1098',
auth: {
user: userMail,
pass: pw
}
});
var mailOptions = {
from: 'xx', // sender address (who sends)
to: xxxxxx#mail.com',
subject: 'your subject', // Subject line
text: 'Your test failed....', // plaintext body
/*attachments: [
{
filename: 'report.html',
path: htmlReport,
}]*/
};
transporter.sendMail(mailOptions, function(error, info)
{
if(error)
{
return console.log(error);
}
console.log('Email sent: ' + info.response);
console.log(info);
});
} else {
//do your stuff
}
setTimeout(callback, 2000);
});

protractor promises - querying an API using "request"

I am trying to use protractor to call an api - it will return some JSON to me and I want to assert against it. I thought I had this working, until I tried to take it further and realised I hadn't got it right, but having a bit of a time trying to work out why.
I have placed some console.logs in and expected the sequence to be 1,2,3 however it appears to be 3 (test finished) then 2 and 1. So I suspect a promise issue.
code below:
'use strict';
var request = require('request');
var path = require('path');
var info;
//var fname = null;
var fname = 'joe';
describe("Sample test", function() {
var request = require('request');
var options = {
method: 'GET',
url: 'URL here',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: '{ "pay_load": [] }'
};
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
info = JSON.parse(body);
console.log('in the callback now');
//console.log('body :' + body);
//var count = Object.keys(info).length;
//console.log('body len:' + count);
//console.log('info :' + info);
fname = info.firstname;
console.log('firstname1 : ' + info.firstname);
console.log('firstname2 : ' + fname);
} else {
console.log('there was some error');
}
}
it("proves the API is alive - firstname is null", function() {
request(options, callback);
//expect(fname).toBe(null);
console.log('firstname3 : ' + fname);
//expect(fname).toBe(null);
//var common = new Common();
//common.checkForAPI();
});
So in my head I thought I would see "in the callback", then "firstname1", "firstname2" and finally "firstname3"
No, firstname3 will always get printed first, the way you have it. The reason for it as that all http requests in nodejs are async, so while your request is processing (or in flight), firstname3 will be printed. Then console.logs in your request callback.
Edit1 - Addressing the comment
Simple example which would print firstname1,2,3 in sequence (tested)
var request = function(cb) {
//basically call your request stuff and then when you are done call cb
console.log('firstname 1');
console.log('firstname 2');
cb();
};
request(function() {
console.log('firstname 3');
});
This prints
firstname 1
firstname 2
firstname 3
Or you can use a third party library called async and use async.tryEach to run tasks in series.
async.tryEach([
function getDataFromFirstWebsite(callback) {
// Try getting the data from the first website
callback(err, data);
},
function getDataFromSecondWebsite(callback) {
// First website failed,
// Try getting the data from the backup website
callback(err, data);
}
],
// optional callback
function(err, results) {
Now do something with the data.
});

How to redirect to url within same context

I have /logout action, that should redirect to /login. /login renders template, where I read flash message from context. This works, but url in browser is still remains "/logout":
router.get("/logout").handler((ctx) => {
if (ctx.user()!=null) {
ctx.clearUser()
//flash message
ctx.put("msg", "Logout succeed")
}
ctx.reroute("/login")
})
What I want, but url should be "/login":
Better to use(?):
ctx.response.putHeader("location", "/login").setStatusCode(302).end()
But there is different context. So I haven't flash message.
How to redirect to /login within same context?
Upd.
Question related to this issue
In order to work with flash messages you should add a cookie to the redirect with the content:
// this makes the message available to the client
ctx
.addCookie(Cookie.cookie("flashMessage", "Logout succeed"));
// configure where to redirect
ctx.response()
.putHeader("location", "/login");
// perform the redirect
ctx.end(302);
Then on the client side you need a bit of JavaScript to read the message and
perform the display as you wish. Since there is no simple way to read cookies on the browser if you're using jQuery with the cookie plugin you can do something like:
$.fn.flashMessage = function (options) {
var target = this;
options = $.extend({}, options, { timeout: 3000 });
if (!options.message) {
options.message = getFlashMessageFromCookie();
deleteFlashMessageCookie();
}
if (options.message) {
if (typeof options.message === "string") {
target.html("<span>" + options.message + "</span>");
} else {
target.empty().append(options.message);
}
}
if (target.children().length === 0) return;
target.fadeIn().one("click", function () {
$(this).fadeOut();
});
if (options.timeout > 0) {
setTimeout(function () { target.fadeOut(); }, options.timeout);
}
return this;
function getFlashMessageFromCookie() {
return $.cookie("FlashMessage");
}
function deleteFlashMessageCookie() {
$.cookie("FlashMessage", null, { path: '/' });
}
};
And add a placeholder in your HTML like:
<div id="flash-message"></div>
And trigger it like:
$(function() {
$("#flash-message").flashMessage();
});

401 when calling WLAuthorizationManager.login("scope")

I have implemented the new MFP 8 Beta security concept. The positive case, with valid credentials is working fine and the processSuccess method that I have defined is executed.
Unfortunately, the negative case doesn’t work.
After calling the WLAuthorizationManager.login("scope"), I am getting a 401 in the console:
2016-05-20 13:48:41.965 Inspector[98311:1660747] [DEBUG] [WL_AFHTTPSessionManagerWrapper_PACKAGE] -[WLAFHTTPSessionManagerWrapper start] in WLAFHTTPSessionManagerWrapper.m:376 :: Starting the request with URL http://172.20.10.4:9080/mfp/api/preauth/v1/preauthorize
2016-05-20 13:48:41.983 Inspector[98311:1655477] [DEBUG] [WL_AFHTTPSessionManagerWrapper_PACKAGE] -[WLAFHTTPSessionManagerWrapper requestFailed:responseObject:error:] in WLAFHTTPSessionManagerWrapper.m:419 :: Request Failed
2016-05-20 13:48:41.984 Inspector[98311:1655477] [DEBUG] [WL_AFHTTPSessionManagerWrapper_PACKAGE] -[WLAFHTTPSessionManagerWrapper requestFailed:responseObject:error:] in WLAFHTTPSessionManagerWrapper.m:422 :: Response Status Code : 401
2016-05-20 13:48:41.984 Inspector[98311:1655477] [DEBUG] [WL_AFHTTPSessionManagerWrapper_PACKAGE] -[WLAFHTTPSessionManagerWrapper requestFailed:responseObject:error:] in WLAFHTTPSessionManagerWrapper.m:424 :: Response Error : Request failed: unauthorized (401)
Here is my implementation:
WLAuthorizationManager.login("UserLogin",{
'username':$scope.username,
'password':$scope.password
}).then( function () {
console.log(">> WLAuthorizationManager.login - onSuccess");
$scope.getInspectorDetails().then(
function(){
$scope.loginInProgress = false;
$state.go("inspectionList");
}
);
},
function (response) {
console.log(">> WLAuthorizationManager.login - onFailure: " + JSON.stringify(response));
$scope.loginInProgress = false;
if (!$scope.loginError){
$scope.loginError = "Could not connect to server. Please try again later.";
}
$scope.$apply();
});
}
And the Challenge handler:
$scope.registerChallengeHandler = function(){
console.log(">> in $scope.registerChllangeHandler ... ");
$scope.userLoginChallengeHandler = WL.Client.createWLChallengeHandler($scope.securityCheckName);
$scope.userLoginChallengeHandler.securityCheckName = $scope.securityCheckName;
$scope.userLoginChallengeHandler.handleChallenge = function(challenge) {
console.log(">> in UserLoginChallengeHandler - userLoginChallengeHandler.handleChallenge ...");
// When a session has expired, this will be our entry point into automatically logging back in
// (since the next server call the user tries to make will end up being flagged as a 'custom response'
// which will trigger the challenge hander. Thus, we need to turn on the progress spinner...
$scope.$apply(function(){
$scope.loginInProgress = true;
});
//show the login ...
$scope.user = { username: "", password: ""};
$scope.currentPath = $location.path();
console.log(">> $location.path(): " + $location.path());
if (!$state.is("login")){
$state.go("login");
}
$scope.isChallenged = true;
var statusMsg = "Remaining Attempts: " + challenge.remainingAttempts;
if (challenge.errorMsg !== null){
statusMsg = statusMsg + "<br/>" + challenge.errorMsg;
$timeout(function(){
//want to show only when submit user/pass not when token expired ...
if($scope.currentPath == "/"){
$scope.loginError = statusMsg;
}
}, 300);
}
console.log(">>> statusMsg : " + statusMsg);
};
$scope.userLoginChallengeHandler.processSuccess = function(data) {
console.log(">> in UserLoginChallengeHandler - userLoginChallengeHandler.processSuccess ...");
$scope.isChallenged = false;
$timeout(function(){
$scope.user = { username: "", password: ""};
}, 200);
$state.transitionTo("inspectionList");
};
$scope.userLoginChallengeHandler.handleFailure = function(error) {
console.log(">> in UserLoginChallengeHandler - userLoginChallengeHandler.handleFailure ...");
console.log(">> handleFailure: " + error.failure);
$scope.isChallenged = false;
if (error.failure !== null){
alert(error.failure);
} else {
alert("Failed to login.");
}
};
}
I would have expected that the handleFailure Method is called, but in the debugger I saw that it is not being executed. After the call of WLAuthorizationManager it just stops, so even the WLAuthorizationManager.login – onFailure is not called.
Edit:
Captured the traffic with Wireshark: https://ibm.box.com/s/7mtwsgea06i4bpdbdz0wvyhy3wpma58r
When using WLAuthorizationManager.login() with wrong credentials, the normal flow is that the challenge handler's handleChallenge will be called, to allow the user to try again.
In some cases, the security check might send a failure, such as "maximum attempt reached". In this case, the challenge handler's handleFailure is called.
WLAuthorizationManager.login() has its own failure scenarios. For example, let's say your server is down, there is no network, the security check does not exist, etc. In those cases, since there is no challenge involved, the login's failure will be called. That's when your then promise will come in handy.

Facebook login not responding to FB.login response

I am working on a android phonegap application with facebook integration.
FB.login(function(response) function has a response handler it is being called when
user click on fb button, but its not getting into the function response
or alert('test') every time. it gets into this script only when i hit
around 5 or 6 times. wat i need is to fetch the access token the very first time i logged into facebook. i have gone through a lot of links regarding this but
cant find an exact solution for this...
FB login callback function not responding if user is already logged in facebook
Even this question seems to be same but i cant figure it out my solution.
this is the code am working :
<div id="data">Hello Facebooktesters, loading ...</div>
<button onclick="login()">Login</button>
<button onclick="me()">Me</button>
<button onclick="logout()">Logout</button>
<button onclick="Post()">facebookWallPost</button>
<script type="text/javascript">
document.addEventListener('deviceready', function() {
try {
alert('Device is ready! Make sure you set your app_id below this alert.');
FB.init({
appId : "xxxxxxxxxxxxxxx",
nativeInterface : CDV.FB,
useCachedDialogs : false
});
document.getElementById('data').innerHTML = "FB init executed";
} catch (e) {
alert(e);
}
}, false);
function me() {
FB.api('/me/friends', {
fields : 'id, name, picture'
}, function(response) {
if (response.error) {
alert(JSON.stringify(response.error));
} else {
var data = document.getElementById('data');
fdata = response.data;
console.log("fdata: " + fdata);
response.data.forEach(function(item) {
var d = document.createElement('div');
d.innerHTML = "<img src="+item.picture+"/>" + item.name;
data.appendChild(d);
});
}
var friends = response.data;
console.log(friends.length);
for ( var k = 0; k < friends.length && k < 200; k++) {
var friend = friends[k];
var index = 1;
friendIDs[k] = friend.id;
//friendsInfo[k] = friend;
}
console.log("friendId's: " + friendIDs);
});
}
function login() {
FB.login(function(response) {
alert('test');
if (response.authResponse) {
alert('logged in');
var access_token = FB.getAuthResponse()['accessToken'];
alert(access_token);
window.location = "test.html"
} else {
alert('not logged in');
}
}, {
scope : "email"
});
}
function logout() {
alert('test');
FB.logout(function(response) {
alert('logged out');
//window.location.reload();
});
}
function Post(ele) {
var domain = 'http://192.168.0.46:8082/';
console.log('Debug 1');
var params = {
method: 'feed',
name: 'test - test',
link: domain+'test/test/showproddetails.action?product.productId=1',
picture: 'http://www.careersolutions.com/test.png',
caption: 'test',
description: 'test'
};
console.log(params);
FB.ui(params, function(obj) { console.log(obj);});
}
</script>
Thank you,
raj
You are missing semicolon in this line :
window.location = "test.html"
This question was posted a while ago but I would like to point out something. FB.login function opens a popup dialog asking if the user would like to log in to your app using Facebook. It is generally recommended that it be run after clicking a button as most browsers would block popup dialogs when a page loads. If the user had previously authorized your app then the popup dialog redirects back to your app and closes the dialog box (assuming your app is a website).
If what you intended to do was to check whether a user is logged in to your app upon page load, then it's recommended that you instead use FB.getLoginStatus method like so
function checkLoginState() {
FB.getLoginStatus(function(response) {
// Check response.status to see if user is logged in
alert(response.status);
});
}
Refer to this extensive documentation on facebook