How to determine post request inputs using javascript - javascript

I am trying to login to a website using python but not having much success. Whenever I post my credentials, I get a 200 response but I'm redirected to the login screen. I think this is because the website's login is using javascript that requires more than just a username and password in the post command, but I'm not sure how to parse it to fix my login code.
This is my python code:
s = requests.session()
login_url = "example.com"
result = s.get(login_url)
payload = {
"user_login": "xx",
"user_pass": "xx"
}
print(payload)
postresult = s.post(
login_url,
data = payload,
allow_redirects=True
)
Here's what the input form looks like:
<div id="loginForm">
<ul>
<li>
<label>Email:</label>
<input class="txt" type="email" name="user_login" tabindex="1" value="">
</li>
<li>
<label>Password:</label>
<input class="txt" type="password" name="user_pass" tabindex="2">
</li>
<li class="submit">
<a id="a-fgt" class="sub" href="#" tabindex="4">Forgot Password</a>
<input type="submit" id="logSubmit" value="Login" tabindex="3" />
<div id="rightBlock">
<span id="respMsg"></span>
</div>
</li>
</ul>
</div>
And here's part of the javascript code that's executing:
function init_login(){
var form = document.forms.loginForm;
$submit(form,login_request);
$listen($('a-fgt'),'click',function(){buildForgotPassword(false);},false);
var lgn = getCookie('login');
if(lgn){form.user_login.value = lgn;}
form[wordCount(form.user_login.value)?'user_pass':'user_login'].focus();
formVal = new FormValidator(form);
}
/*---\\\ LOGIN FUNCTIONS ///---*/
function login_request(form){
form = validateForm(form, 'user_pass');
$post("/JSMX/admin_login.cfc?method=login",login_response,form);
}

Related

Problems with scripts in a SPA

This is the script I am using to create a spa.
const route = (event) => {
event = event || window.event;
event.preventDefault();
window.history.pushState({}, "", event.target.href);
handleLocation();
};
const routes = {
404: "./pages/404.html",
"/": "./pages/index.html",
"/vehicles": "./pages/vehicles.html",
"/services": "./pages/services.html",
"/contact": "./pages/contact.html",
"/financing": "./pages/financing.html",
"/locations": "./pages/locations.html",
};
const handleLocation = async () => {
const path = window.location.pathname;
const route = routes[path] || routes[404];
const html = await fetch(route).then((data) => data.text());
document.getElementById("main-page").innerHTML = html;
};
window.onpopstate = handleLocation;
window.route = route;
handleLocation();
<a href="/financing" onclick="route()" class="mainServices-section">
<div class="main-title">
<h2>Financing</h2>
</div>
<img src="../image/financing-image-colored.svg" alt="">
</a>
It worked correctly for me. But in a section of the web, I need a contact form, which through javascript open the Email app and pre complete the corresponding fields.
<section class="contact inset-wrapper">
<form class="form content" id="form" action="">
<h2 class="title"><strong>let's talk</strong></h2>
<h4 class="subtitle">Do not hesitate to contact us for more information about the vehicle you are interested in.</h4>
<label for="name">
<h4>Name</h4>
</label>
<input required name="name" id="name" type="text" placeholder="Juan Lucas López">
<label for="email">
<h4>Email</h4>
</label>
<input required name="email" id="email" type="email" placeholder="Email">
<label for="message">
<h4>Message</h4>
</label>
<textarea required name="message" placeholder="Message" id="message" cols="30" rows="10"></textarea>
<button class="form-button" type="submit">Send Message</button>
<a id="sendMail" href="mailto:mauriciolaratro#gmail.com" ></a>
</form>
</section>
<script>
const $form = document.querySelector('#form')
const $buttonMailto = document.querySelector('#sendMail')
$form.addEventListener('submit', handleSubmit)
function handleSubmit(event) {
event.preventDefault()
const form = new FormData(this)
$buttonMailto.setAttribute('href', `mailto:mauriciolaratro#gmail.com?subjet=${form.get('name')} ${form.get('email')}&body=${form.get('message')}`)
$buttonMailto.click()
}
</script>
This is the code I use to make the form, which works perfectly, when I use it in another project, however, the previous script interferes with this somehow and I do not know how to fix it (Again I clarify that I am new to js).
What happens is that instead of redirecting to the Email app, it tries to redirect the web to a non-existent link.
I would appreciate any contribution, to be able to solve this in the simplest way, I am trying to make this project, without consuming external API, I know that there are simpler and more efficient ways to make the form functional, but the idea is to do everything with vanilla code and without API

Can't simulate a log in button click or form submit in Swift WKWebview

Problem: I can't get the webview form to submit so the app code can log into a public website.
Context: I can get the username/email and password injected into respective form fields but am unable to 'click the button' or 'submit the form' via the app code. As you can see I've tried every permutation of click and submit by element ID and class name. There are similar posts but are dated several years old and based on what I can tell the technique required to tap the login button/submit the form has changed.
Button ID and/or form names I've tried:
login
loginForm
2a. This one seems to refresh the page such that after the
refresh the password disappears so I know its interacting with the
page somehow, but not actually clicking the 'Sign In' button
tab-login
userForm ebform
Public website url: https://www.rakuten.com/signUp.do?login=yes
My Code:
import UIKit
import WebKit
class ViewController: UIViewController {
#IBOutlet weak var emailTF: UITextField!
#IBOutlet weak var passwordTF: UITextField!
let webView = WKWebView()
var counter = 0
override func viewDidLoad() {
super.viewDidLoad()
let url = URL(string: "https://www.rakuten.com/signUp.do?login=yes")!
let request = URLRequest(url: url)
webView.frame = CGRect(x: 0, y: 300, width: 350, height: 550)
webView.load(request)
view.addSubview(webView)
}
#IBAction func onSignInTapped() {
switch counter {
case 0:
webView.evaluateJavaScript("document.getElementById('username').value='\(emailTF.text!)'", completionHandler: nil)
webView.evaluateJavaScript("document.getElementById('password').value='\(passwordTF.text!)'", completionHandler: nil)
case 1:
webView.evaluateJavaScript("document.getElementClassName('loginForm')[0].click();", completionHandler: nil)
webView.evaluateJavaScript("document.getElementClassName('loginForm')[0].submit();", completionHandler: nil)
webView.evaluateJavaScript("document.getElementById('loginForm').submit();", completionHandler: nil)
webView.evaluateJavaScript("document.getElementById('loginForm').click();", completionHandler: nil)
default:
webView.evaluateJavaScript("document.getElementById('sign-in').submit();", completionHandler: nil)
}
counter += 1
}
}
(this is code from Kiloloco's youtube tutorial that I slightly modified - for appropriate credit)
I printed the HTML for the public website into the console and this is the result of the relevant code:
<div class="row login-tabs">
<ul class="nav nav-tabs">
<li class="active">SIGN IN</li>
<li class="">JOIN NOW</li>
</ul>
</div>
<!-- social media signup -->
<div class="login-tab-contents blk-reg">
<div class="tab-content pad-15-lr">
<div class="tab-pane active rowpad-lg" id="tab-login">
<form name="userForm" id="loginForm" class="userForm ebform" focus="email_address" target="_top" method="post">
<input type="hidden" name="skip_verify_password" value="false">
<input type="hidden" name="terms" value="on">
<input type="hidden" name="urlIdentifier" value="/signUp.do?login=yes|MobileV2">
<input type="hidden" name="type" value="general - mobile">
<input type="hidden" name="isAjax" value="true">
<input type="hidden" name="action" value="create">
<input type="hidden" name="split_entry_id" value="871">
<input type="hidden" class="eb-sec-token" id="_csrf" name="_csrf" value="t4Y74TkNFpmgisGujVuYkrXk0PPuoW8ISWmo4K8KrCnzBLgPV99eNi5JEAyhLw9MjN-mqMHX22pMao8KVsO11vpbHCeiFLJJTOhhcbwQ7opBCC_2vDQBGkZHcyEH6rE9Ow3NzfpBn6ceg7RwTa6oeQbvn2I">
<div class="row pad-20-t">
<div class="col-xs-12 pad-0-lr vald_msg">
<span class="fa-envelope fa-textfield f-18 f-gry-c mar-10-r pad-10-l pad-10-r pad-10-tb"></span>
<input type="email" name="username" id="username" class="required input-first auto-correct mar-10-b" title="Enter your Email Address" maxlength="255" tabindex="1" placeholder="Email" data-role="none" value="">
<div class="relative sipwd">
<span class="fa-lock fa-textfield f-18 f-gry-c pad-10-l pad-20-r pad-10-tb"></span>
<input type="password" name="password" id="password" class="required input-last" value="" maxlength="128" tabindex="2" placeholder="Password">
<div class="show-hide fa absolute hideshow f-12 prox-r font-dark-9 modalSpan" style="display: none;">Show</div></div>
</div>
</div> </form>
<div class="row mar-10-t">
<div class="col-xs-12 pad-0-lr">
<button name="su-button" id="login" class="button primary stretch loginSignup login-btn" title="Start Shopping" tabindex="3" data-event-signature="ec,ea" data-ec="MW Sign Up Page" data-ea="Sign In - Click">Sign In</button>
</div>
</div>
<div class="row">
<div class="col-xs-12 resetpassword_link f-grn semibold forgot-pwd-modal-link f-16">Forgot Password?</div>
</div>
In the webview view that's displayed on the app page, after the email address and password are written into the webpage, I can manually click the Sign In button and it will log in as expected.
Note: I know this is likely a very poor way of implementing a login and of course if the prototype that uses this login works out, I'd need to work to get access to an API by the public site. However for starters this is what I'm trying to see if the prototype even makes sense.
Kindly check the id you are using to get the sign-in button.
webView.evaluateJavaScript("document.getElementById('sign-in').submit();", completionHandler: nil)
In the HTML provided above, there is no button with id as sign-in. The button is provided with id as login instead.

How to send values from LocalStorage to Flask #app.route()?

Recently, i've been using Flask, but i just wanna ask how to POST data from LocalStorage of the web browser to #app.route
part of main.py
#app.route("/authenticate/post", methods=['GET', 'POST'])
def posting():
posts = request.form['post']
return render_template("testing.html", post=posts)
Here i'm making a small web-based "posting and sharing app" just like Instagram, the var posts is the Post Content submitted via textarea of html, and is working perfectly fine. All i need now is how to get the data stored on LocalStorage of a user's browser. Which is the Username of the user. How can i retrieve the Username of the user that is stored on the LocalStorage and do POST request to my #app.route()
Index.html
<div class="posting">
<h5>Write Something & Post!</h5>
<form method="POST" action = "/authenticate/post" autocomplete="off">
<textarea class="books" placeholder="Say something!" id="post" name="post" rows="4" cols="50" maxlength="200"></textarea>
<br><br>
<input id="enter" type="submit" class="books" value="Post!" onclick="getname()">
</form>
</div>
The getname() function of my main.js
function getname() {
let name = localStorage.getItem('username');
}
I'd change the submit input to a simple button:
<div class="posting">
<h5>Write Something & Post!</h5>
<form id="post-form" method="POST" action = "/authenticate/post" autocomplete="off">
<input type="hidden" name="username" id="username">
<textarea class="books" placeholder="Say something!" id="post" name="post" rows="4" cols="50" maxlength="200"></textarea>
<br><br>
<button type="button" class="books" id="enter" onclick="submitForm()">Post!</button>
</form>
</div>
Then handle the form submit in JS, while setting a hidden input in the form:
function submitForm()
{
let name = localStorage.getItem('username');
// set the value of the hidden input
document.getElementById("username").value = name;
// submit the form
document.getElementById("post-form").submit();
}
OR
You still need the hidden input, but on DOM ready event, you could set the input value:
document.addEventListener('DOMContentLoaded', function() {
let name = localStorage.getItem('username');
// set the value of the hidden input
document.getElementById("username").value = name;
})
This way you can ensure that your "username" will be posted.

No user save in database with rest restangular.all post

I have a problem to perform a rest post request for saving data in a database .
I created a form register.html and a RegisterCtrl.js controller to add the user account in the database .
The url to create a user is register : http://localhost:8100/#/register
I use the framework Ionic and AngularJS
Unfortunately, no post application works .
Can you help me.
Thank you.
Template register.html
<ion-modal-view ng-controller="RegisterCtrl">
<ion-content>
<form ng-controller="RegisterCtrl">
<div class="register listRegister">
<label class="register item item-input">
<span class="spanLogin icon-left ion-person"></span>
<input type="text" class="form-control" ng-model="user.username" placeholder="Username" />
</label>
<label class="register item item-input">
<span class="spanLogin icon-left ion-email"></span>
<input type="email" class="form-control" ng-model="user.email" placeholder="Email" />
</label>
<label class="register item item-input">
<span class="spanLogin icon-left ion-key"></span>
<input type="password" class="form-control" ng-model="user.password" placeholder="Password" />
</label>
</div>
<div class="registerButton">
<button class="validLogin button button-block button-assertive" type="submit">Registration
</button>
Back
</div>
</div>
</form>
</ion-content>
</ion-modal-view>
Controller registerCtrl.js
'use strict'
angular.module('djoro.controllers',['restangular']);
.controller('RegisterCtrl', function($scope, restangular) {
var userRegister = {
"username": user.username,
"email": user.email,
"password": user.password
};
Restangular.all('register').post(userRegister).then(
function (data) {
$scope.register = data;
});
});
Api rest by python Django
class UserRegistration(viewsets.ViewSet):
"""
Called with the URL r'^register/*$'. It allows POST requests.\n
POST requests allow to create a new user. The parameters to post are 'username','email','password'.\n
It raises an HTTP 400 error if the POST request is invalid and an HTTP 401 error if an user with the username or email specified already exists.
"""
def post(self, request):
username = request.data.get('username')
password = request.data.get('password')
email=request.data.get('email')
try :
user=register(username, email, password)
user.backend='django.contrib.auth.backends.ModelBackend'
user.save()
login(request, user)
return HttpResponseRedirect("/me/")
except AttributeError:
return Response({"detail": "User with this email or username already exists"}, status=HTTP_401_UNAUTHORIZED)

Sending HTML form via AJAX to PHP server

I'm working on phonegap, basically its like making mobileapps crossplatform by using HTML, JS and CSS. On the device i currently have the JS and the HTML (form) in same document.
What I'm trying to do is to pass email and password to my server, and then process it there through a login. I've tested the login script on the server and it works with hardcoded data. So I'm guessing somewhere when sending the data from the device its failing.. I'm fairly new to JS too.
I tried to hardcode the data in the AJAX but it doesnt seem to work. Preferebly I would like to use something like var pdata = $('#form').serialize(); or something else if its better.
Any ideas?
EDIT: Forgot to say that the PHP on the server auto submits by using JS when $_POST is set (isset)
The form
<form id="form" onsubmit="dologin()">
<div class="form-group">
<label for="email">Epost</label>
<input type="email" class="form-control" name="email" value="" placeholder="Epost">
</div>
<div class="form-group">
<label for="password">Passord</label>
<input type="password" class="form-control" name="password" value="" placeholder="Passord">
</div>
<div class="checkbox">
<label>
<input type="checkbox" name="remember_me">
Husk meg
</label>
</div>
<button type="submit" class="btn btn-primary">Logg inn</button>
</form>
The javascript
<script>
function dologin() {
//var pdata = $('#form').serialize();
//alert(pdata);
$.ajax({
type: 'POST',
data: {email:"test#test.no",password:"test"},
url: 'LINK',
success: function(data) {
alert(data);
},
error: function() {
alert("error");
}
});
return false;
};
</script>
The PHP
<form id="form" method="post">
<!-- {{ Form::label('email', 'Email Address') }} -->
<div class="form-group">
<input type="text" name="email" value="<?php if(isset($_POST["email"])) echo $_POST['email'];?>">
</div>
<div class="form-group">
<!-- {{ Form::label('password', 'Password') }} -->
<input type="text" name="password" value="<?php if(isset($_POST["password"])) echo $_POST['password'];?>">
</div>
</form>
Are you able to hit your server via through phonegap?
If no then please check your config.xml for white list urls - change access control property to
access origin = "*"
Hopeful you will be able to hit your server with data.
You can use weinre to debug your app. That way you will be able to see if the request was placed from the app or not.
http://people.apache.org/~pmuellr/weinre/docs/latest/Home.html

Categories

Resources