Question

I am trying to authenticate users in a web application using ajax call to Python server(Flask), which in turn calls the main server.I am able to pass the credentials to the Flask server and do the authentication.But after the authentication,it should pass back a success message to the client,so that I can redirect/show the message on the web page accordingly.But, it is not giving back the message.Instead, it is giving a broken pipe error,after the authentication.I have written the following code Client code :

1)Javascript:

function login()
{
var user=document.getElementById("username").value;
var pass=document.getElementById("password").value;
//alert(JSON.stringify({username:user,password:pass}));
//var contentType = "application/x-www-form-urlencoded";
var ajax=$.ajax({
    type: "POST",
    //crossDomain: true,
    data: JSON.stringify({username:user,password:pass}),
    contentType:"application/x-www-form-urlencoded",
    dataType: "json",
    url: "http://0.0.0.0:8081"
    //async:true
}).done(function(data){


        //   alert(data);
    });
ajax.fail(function(data){


    //alert(data);
});

}

2)HTML:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<!--link rel="stylesheet" type="text/css" href="login.css"-->
<script type="text/javascript" src="login_auth.js" ></script>

</head>
<body>
<!-- Begin Page Content -->
<div id="container">
<form>

    <input type="text" id="username" name="username" value="sayan" >
    <input type="password" id="password" name="password" value="3BxTPu+y4YA">
    <div id="lower">
        <input type="checkbox" id="checkbox" name="checkbox"><label class="check" for="checkbox">Keep me logged
        in</label>
        <input type="submit" value="Login" onclick="login()">
    </div>
    <!--/ lower-->
</form>
</div><!--/ container-->
<!-- End Page Content -->
</body>
</html>

3)Flask Server code:

app = Flask(__name__)
@app.route('/', methods=['POST','GET','OPTIONS'])
@crossdomain(origin='*')
def login():

    data= request.get_json(force=True);
    br=mechanize.Browser()
    br.open('https://weaveprod.ucdp.utah.edu/geoserver/web/?wicket:bookmarkablePage=:org.geoserver.web.GeoServerLoginPage')
    br.select_form(nr=0) 
    username=data['username'];
    password=data['password'];
    br['username']= username
    br['password']= password

    response= br.submit()
    mainpage=response.read()
    val=mainpage.find('Invalid username/password combination')

    if val==-1:
            success = True
    else:
        success=False

    print success

    return jsonify(text=success);


if __name__ == "__main__":
    app.run(host="0.0.0.0", port=8081, debug=True,threaded=True)

Issues:

1) If I make the request through the Mozilla Browser, instead of Chrome,I get a GET request instead of POST and no authentication happens.

2)Though I make a POST request,I see the username and password in the url on the address bar.

Kindly help me out...I am toiling over it for 2 days now.

Thanks, Sayan

Was it helpful?

Solution

The javascript code should be included at the last (or delay the execution with $(document).ready). The code was trying to get the elements with document.getElementById("username").value before even the form fields were rendered. Apart from that, on clicking the submit button, the form gets normally submitted refreshing the page and rendering the ajax call previously useless. Also, the page refresh can interrupt the ajax call made previously, causing the broken pipe error that you see in the logs.

Here's a slightly better approach. Let's bind to the form submit event directly. Before that add id="loginForm" to the form so that we can fetch it directly with jQuery and also remove onclick attribute from submit button.

Now the javascript part.

$(document).ready(function() {
    // bind the form submit event to our function
    $("#loginForm").bind('submit', function(e) {
        // prevent page refresh
        e.preventDefault();
        // post the data
        var ajax=$.ajax({
            type: "POST",
            data: $("#loginForm").serialize(),
            url: "http://localhost:8081/"
        }).done(function(data){
            console.log('done!')
        });
        ajax.fail(function(data){
            console.log('error!');
        });
    });
});

On the server end, get the form field data like request.form.get('username') and request.form.get('password').

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top