Multiple user credentials with array reload page - javascript

I am attempting to test 4 usernames and password by using an array. The first username and password are successful, checked by fetching the "Howdy, (username)" in wordpress. My issue:
Once it runs the loop, it fails to reload the page where the username and password can be inputted; how can I re-load the page to continue to test the next usernames/passwords?:
CasperError: Cannot get informations from #log: element not found.
The element is not found, because it is attempting to find it in the now "logged in" page.
var casper = require('casper').create()
casper.userAgent('Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)');
casper.start('http://somesite.com')
casper.viewport(1024, 768).then(function() {
// new view port is now effective
});
//Usernames
var userNames = ['username1','username2','username3','username4'];
var userNamesIndex = 0;
//Passwords
var passWords = ['password1','password2','password3','password4'];
var passWordsIndex = 0;
function login () {
casper.then(function () {
this.sendKeys('#log', userNames[userNamesIndex]);
userNamesIndex++;
if (userNamesIndex >= userNames.length) {
userNamesIndex = 0;
}
this.sendKeys('#pwd', passWords[passWordsIndex]);
passWordsIndex++;
if (passWordsIndex >= passWords.length) {
passWordsIndex = 0;
}
console.log(userNames[userNamesIndex] + " account has been typed in.");
this.click('#wpmem_login > form > fieldset > div.button_div > input.buttons');
console.log("Log In button has been clicked!")
});
casper.wait(5000, function () {
this.echo(this.getTitle());
this.echo(this.fetchText('#wp-admin-bar-my-account > a'));
casper.capture('pic.png');
});
};
setInterval(login,2000);
casper.run();

There are functions for that. You can use casper.open, casper.thenOpen or casper.back to achieve that.
Also, you should not use setInterval or setTimeout to do some scheduling, because CasperJS is asynchronous on its own, but those functions are only useful when you want to execute a synchronous function later. CasperJS works by scheduling steps which you break by using setInterval or setTimeout. For another case where this breaks, see How do I remove the stack overflow from this casperjs code (phantomjs / javascript using setTimeout)?
Change login to use username and password directly and change the implementation accordingly (you don't need the counters):
function login (username, password) { /* your adjusted implementation */ }
After you logged into the page, you need to log out before using the next credentials. CasperJS uses cookies which are not cleared when using thenOpen.
So the script would look like this:
casper.start(); // empty page
userNames.forEach(function(username, index){
casper.thenOpen(url); // open the start page
login(username, passWords[index]); // schedule the steps
// you can also move the following steps inside the login function
casper.then(function(){
// do something
});
casper.then(function(){
// click logout button
});
});
casper.run(); // begin the execution
Here is the gist with the complete code.
If you want to track the successful and unsuccessful logins, you need a global variable:
var glob = {success: [], fail: []}; // before start for readability
In login you can then write into the variable:
casper.wait(5000, function () {
// use some indicator that the login worked, here the logout button
if (this.exists(logoutButtonSelector)) {
glob.success.push(username);
} else {
glob.fail.push(username);
}
this.echo(this.getTitle());
this.echo(this.fetchText('#wp-admin-bar-my-account > a'));
casper.capture('pic.png');
});
You can then print it like this:
casper.run(function(){
this.echo("success: " + glob.success.length + ", fail: " + glob.fail.length);
this.echo(JSON.stringify(glob));
});

Related

Need to clear session and logout user after 30 sec or after close browser

code is in MVC and also every request are using ajax call so no change in url.
using below code i ll able to perform firt opration that logout user if user inactive of 30 sec. but not able to perform action when user logout.
<script>
$(function () {
$("body").on('click keypress', function () {
ResetThisSession();
});
});
var timeInSecondsAfterSessionOut = 30; // to change the session time out, change this value. Must be in seconds.
var secondTick = 0;
function ResetThisSession() {
secondTick = 0;
}
function StartThisSessionTimer() {
secondTick++;
console.log(secondTick);
if (secondTick > timeInSecondsAfterSessionOut) {
clearTimeout(tick);
window.location = '/Account/LogOff/0';
}
tick = setTimeout("StartThisSessionTimer()", 1000);
}
StartThisSessionTimer();
</script>
alse i tried the unload or beforeunload method of script but result not proper as expect.
need to logout user if user not perform any action on 30 sec or if user close browser.
thanks in advance.
as i see the var tick is local, and is defined in every tick, so the timeout is called every second:
function StartThisSessionTimer() {
secondTick++;
console.log(secondTick);
if (secondTick > timeInSecondsAfterSessionOut) {
clearTimeout(tick);
window.location = '/Account/LogOff/0';
}
tick = setTimeout("StartThisSessionTimer()", 1000);
}
Try to separate the initializiaton of the timeout, outside of the same scope of repeater of timeout.
tell us if is useful.
Tks

Troubleshoot PhantomJS code to sign in to Instagram

I've written this PhantomJS script to automate signing in to Instagram. It can successfully fill in the form fields and press the submit button, but it always gets redirected back to the logon screen with the following message:
Your username or password was incorrect.
I am 100% positive that the credentials are correct, and I tried it with multiple Instagram accounts.
I'm running the script on a Mac from terminal:
$ phantomjs --ssl-protocol=any --cookies-file=cookies.txt script.js username password
Note the --ssl-protocol=any option. Without it PhantomJS can't even open the login page because of HTTPS. See this question.
Here's the code. I based it off this tutorial, and updated the code to account for the recent changes in the source code of Instagram's login page.
var system = require('system');
var username = system.args[1];
var password = system.args[2];
var page = require('webpage').create();
page.open('https://instagram.com/accounts/login/',
function (status) {
if (status === "success") {
page.evaluate(function (uid, pwd) {
var username_field = document.getElementById('lfFieldInputUsername');
username_field.value = uid;
var password_field = document.getElementById('lfFieldInputPassword');
password_field.value = pwd;
}, username, password);
var point = page.evaluate(function () {
var element = document.getElementsByTagName('button')[0];
var rect = element.getBoundingClientRect();
return {
x: rect.left + Math.floor(rect.width / 2),
y: rect.top + Math.floor(rect.height / 2)
};
});
page.render('before-submit.png');
page.sendEvent('click', point.x, point.y);
}
setTimeout(function () {
var error = page.evaluate(function () {
var element = document.getElementById('errorAlert');
var error_message = false;
if (element !== null) {
error_message = element.innerText.trim();
}
return error_message;
});
page.render('after-submit.png');
if (!error) {
console.log('Login Successful: ' + page.url);
} else {
console.log('Login Failed: ' + error);
}
phantom.exit(0);
}, 5000);
}
);
And here's what I've tried so far:
Setting cookies. Besides adding the --cookies-file=cookies.txt command line option, I've also tried phantom.addCookie in the code. Didn't seem to make any difference.
Explicitly sending auth headers. See this question.
Changing the timezone. Not sure if this makes sense. See this question.
Apparently PhantomJS has some issues with SSL. Should I just give up using it for this purpose?
I think that problem with Instagram login is ReactJs. When You set value of text field, React doesn't change state. It means that login and password sending empty when you submit form.
I didn't try, but I think you should fill text inputs with keypress event, because internal component (React) state only changing when inputs text changing. Setting value in you way will not trigger change event.

re-execute javascript after log-in

I have a series of buttons that execute different functions when clicked. The function checks whether the user is logged in, and if so proceeds, if not it displays an overlay with ability to log in/create account.
What I want to do is re-execute the button click after log-in, without the user having to reclick it.
I have it working at the moment, but I'm pretty sure that what I'm doing isn't best practice, so looking for advice on how I can improve...
Here's what I'm doing: setting a global variable "pending_request" that stores the function to be re-run and in the success part of the log-in ajax request calling "eval(pending_request)"
Example of one of the buttons:
jQuery('#maybe_button').click(function() {
pending_request = "jQuery('#maybe_button').click()"
var loggedin = get_login_status();
if (loggedin == true) {
rec_status("maybe");
}
});
.
success: function(data) {
if(data === "User not found"){
alert("Email or Password incorrect, please try again");
}else{
document.getElementById('loginscreen').style.display = 'none';
document.getElementById('locationover').style.display = 'none';
eval(pending_request);
pending_request = "";
}
}
Register a function to handle the click and then invoke that func directly without eval().
jQuery('#maybe_button').on('click', myFunction)
This executes myFunction when the button is clicked. Now you can "re-run" the function code every time you need it with myFunction().
And btw since you are using jQuery you can do $('#loginscreen').hide() where $ is an alias for jQuery that's auto defined.
EDIT
Please, take a look at the following code:
var pressedButton = null;
$('button1').on('click', function() {
if (!isLoggedIn()) {
pressedButton = $(this);
return;
}
// ...
});
And, in your success handler:
success: function() {
// ...
if (pressedButton) pressedButton.trigger('click');
// ...
}

Logging user out after some time of inactivity

I want user to be logged out after some time inactivity. I want this php code to run automatically after some time of user inactivity. It must happen without refreshing the page.
<?php
if (isset($_SESSION['user_login_status'])) {
$max_time = 5; // Maximun inactive time(this time is set in seconds )
$current = time(); // Current time on server
if (!isset($_SESSION['Inactive']))
{ // Create session inactive;
Session::set('Inactive', time()); // Create session inactive;
} else {
$session_life = $current - $_SESSION['Inactive'] ;
if ($session_life > $max_time )
{
Session::destroy(); // This is a function that destroys all sessions and logging out the user
header('location: index.php'); // Redirects to some kinda page
} else {
$_SESSION['Inactive'] = time();
}
}
}
?>
This php code is working and user is logged out after 5 seconds when I refresh the page. But I need this code to be runned after those 5 seconds of inactivity and it should redirect to another page. I have tried some ajax code but it didn't worked.
Any suggestions how can I Run that php code after some time?
A lot of misspelled words. Sorry for that.
Modify the code according to your needs. What this code would do is that if the user refreshes the page within 5 second, the timer will reset and start the count again. If user does not refresh/reload the page within 5 seconds, ajax call will be made to your controller action to log the user off. Return a new url to the ajax call to automatically redirect user to a new page. [FYI, I do not like automatic logoffs, specially such short ones. Of course, most Web servers have session timeouts. I would rather go with those timeouts.]
// add these functions at the bottom of the output html page within <script> tags
// YOU SHOULD CALL setLogoutTimer FUNCTION ON MOUSEMOVE OR SOME USER ACTIVITY EVENT.
// otherwise user will be logged out even when the user is doing something on the page
setLogoutTimer();
function setLogoutTimer() {
var myTimeout;
if (window.sessionStorage) {
myTimeout = sessionStorage.timeoutVar;
if (myTimeout) {
clearTimeout(myTimeout);
}
}
myTimeout = setTimeout(function () { logoutNow(); }, 5000); //adjust the time.
if (window.sessionStorage) {
sessionStorage.timeoutVar = myTimeout;
}
}
function logoutNow() {
if (window.sessionStorage) {
sessionStorage.timeoutVar = null;
}
//MAKE AN AJAX CALL HERE THAT WILL CALL YOUR FUNCTION IN
// CONTROLLER AND RETURN A URL TO ANOTHER PAGE
$.ajax({
url: 'YOUR CONTROLLER ACTION URL',
cache: false,
async:false,
type: 'POST',
success: function (msg) {
window.location.href=msg; //msg is the url of another page returned by the controller
}
});
}

submit search query if conditions are met

How would I go about integrating these two functions together so that when submitting the search form, it will first check the http get response, then depending on whether there was an error or not, either submit the form, or display an error message?
All that I've tried has either made the form not work at all, or not take into account the 'http.get function'.
var http = require("http");
var url = 'http://examplepage.com/';
search.submit(function (event) { // submit search query function
if (searchBox.val().length < 2) {
searchBox.focus();
event.preventDefault();
}
});
http.get(url, function (res) {
res.resume();
// successful - so submit search query
}).on('error', function () {
// unsuccessful - display error message
});
You should probably subscribe on click event for you button that triggers search, the go check the url and inside success handler do
Sample code of Click handler
http.get(url, function (res) {
// successful
if (searchBox.val().length < 2) {
$('your form selector').submit();
}
}).on('error', function () {
// unsuccessful - display error message
});

Categories