0

I'm building a python flask app implementing user log in , after user log in succefully, it will redirect to userHome.html

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Python Flask Bucket List App</title>
    <link href="http://getbootstrap.com/dist/css/bootstrap.min.css" rel="stylesheet">
 
    <link href="http://getbootstrap.com/examples/jumbotron-narrow/jumbotron-narrow.css" rel="stylesheet">
    <link href="../static/css/signup.css" rel="stylesheet">
</head>
<body>
    <div class="container">
        <div class="header">
            <nav>
                <ul class="nav nav-pills pull-right">
                    <li role="presentation" class="active"><a href="/logout">Logout</a>
                    </li>
                </ul>
            </nav>
            <h3 class="text-muted">Python Flask App</h3>
        </div>
 
        <div class="jumbotron">
            <h1>Welcome Home !!</h1>   
        </div> 
        <footer class="footer">
            <p>&copy; Company 2015</p>
        </footer>  
    </div>
</body>
</html>

and the python code to perform return render_template('userHome.html') in validateLogin :

@app.route('/validateLogin',methods=['POST'])
 def validateLogin():
 cursor = None
 try:
      _username = request.form['inputName']
      _password = request.form['inputPassword']

     # connect to mysql

      conn = mysql.connect()
      cursor = conn.cursor() 
      cursor.callproc('sp_validateLogin',(_username,_password))
      data = cursor.fetchall()

      if len(data) > 0:            
        return render_template('userHome.html')
      else:
        return render_template('error.html', error = "Wrong Username or 
        Password")         

  except Exception as e:
      return render_template('error.html',error = str(e))
  finally:
      if cursor:
          cursor.close()
          conn.close()

and the signin.js :

  $(function(){
  $('#btnSignIn').click( function(){

    $.ajax({
        url: '/validateLogin',
        data: $('form').serialize(),
        type: "POST",
        success: function(response){
            console.log(response);
        },
        error: function(error){
            console.log(error);
        }
     });
  });
});

and finally the signin.html:

!DOCTYPE html>
<html lang="en">
  <head>
    <title>Sign In</title>


    <link href="http://getbootstrap.com/dist/css/bootstrap.min.css" rel="stylesheet">

    <link href="http://getbootstrap.com/examples/jumbotron-narrow/jumbotron-narrow.css" rel="stylesheet">
    <link href="../static/signup.css" rel="stylesheet">
    <script src="/static/js/jquery-3.1.1.js"></script>
    <!--<script src="/static/js/jquery-3.1.1.min.map"></script>-->
    <script src="/static/js/signin.js"></script>

  </head>

  <body>

    <div class="container">
      <div class="header">
        <nav>
          <ul class="nav nav-pills pull-right">
            <li role="presentation" ><a href="main">Home</a></li>
            <li role="presentation" class="active"><a href="#">Sign In</a></li>
            <li role="presentation"><a href="showSignUp">Sign Up</a></li>

          </ul>
        </nav>
        <h2 class="text-muted">Release Control System</h2>
      </div>

      <div class="jumbotron">
        <h1>Log In</h1>
        <form class="form-signin">
        <label for="inputName" class="sr-only">Name</label>
        <input type="name" name="inputName" id="inputName" class="form-control" placeholder="Name" required autofocus>
        <!--<label for="inputEmail" class="sr-only">Email address</label>
        <input type="email" name="inputEmail" id="inputEmail" class="form-control" placeholder="Email address" required autofocus>-->
        <label for="inputPassword" class="sr-only">Password</label>
        <input type="password" name="inputPassword" id="inputPassword" class="form-control" placeholder="Password" required>

        <button id="btnSignIn" class="btn btn-lg btn-primary btn-block" type="button">Sign in</button>
      </form>
      </div>



      <footer class="footer">
        <p>Copyright 2017 Foxconn CABG &copy; All Rights Reserved.</p> 
      </footer>

    </div>
  </body>
</html>

but when I log in successfully it does not direct to the userHome.html page, it showed all html entities instead. Meaning the templates are working but the browser is treating wrongly.

I've tried many tricks like:

    headers = {'Content-Type': 'text/html'}
    return make_response(render_template('userHome.html'),200,headers)

but it still returns html entities, not html page. This has confused me for days, thanks in advance.

6
  • How you enter user credentials? I mean username, and password input. Commented Feb 23, 2017 at 6:11
  • Yes, I,ve entered the username, and password input and clicked the sign-in button. Commented Feb 23, 2017 at 6:13
  • Yes but how you render that page? Can you share that code too? Commented Feb 23, 2017 at 6:24
  • do you mean the code in validateLogin()? Or you want all code of the app.py? Commented Feb 23, 2017 at 6:33
  • No the html code of your login page which you have input elements for username and password Commented Feb 23, 2017 at 6:34

1 Answer 1

1

Since I don't know how to send a redirect request to ajax and execute it. I will simply share the way I do things.

# Python Code
@app.route('/login')
def login():
    # check if user is not logged in then render the login form
    if user_not_logged_in():
        return render_template('login_form.html')
    # if user logged in, then redirect to userHome
    else:
      return redirect(url_for('userHome'))

from flask import jsonify
@app.route('/validateLogin', methods=['POST'])
def validateLogin():
    # do some stuff and check for validation
    if stuff_goes_well:
        return jsonify({'data': 'success'})
    else:
        return jsonify({'data': 'failure'})

@app.route('/userHome')
def userHome():
    # check if user is logged in 
    if logged_in_user_session_exists():
        return render_template('userHome.html')
    else:
        # user is not logged in so redirect him to the login page
        return redirect(url_for('login'))

# jQuery code
$.ajax({
    url: "/validateLogin",
    type: "POST",
    dataType: "json",
    data: data_here,
    success: function(response){
        if(response.data == 'success'){
           # success was sent so the user logged in successfully, redirect to user home
            window.location.replace('/userHome');
        }else{
            # there was an error in the logging in
            alert('there was an error!');
        }
    }
});

To sum it up in a few words: simply send your data with ajax to Python. then let Python handle verification and the analysis of the data. then if all goes well, tell jQuery " hey it's all cool here " ( which is represented by the 'success' string we send ). if something was wrong then we tell jQuery that we had a problem hence the 'failure' string we send. then in jQuery we act upon the string that was sent. if it was success, then we redirect the user to the desired URL ( which is /userHome in this case ). if failure was sent then we say there was an error.

Please notice that these python checks are important so the user just doesn't type "/userHome" in the URL and be able to just view the page while he is not logged in.

I hope you find this useful.

Sign up to request clarification or add additional context in comments.

7 Comments

Thanks, Yes I've tried redirect as well but still returns html entity,
Ohh I think I get it now. You login with Ajax I haven't noticed that. You can't send a redirect request to ajax ( at least I don't know how ). But what I always do is I take care of the session and validation and then send a unique success message to ajax then I redirect using jQuery itself ( or js actually ) using window.location.replace(new_url). If that doesn't make sense tell me and I will post an example code.
Okay I will edit the current example code in my answer
thanks and I am wondering what's data_here in the jQuery code?
So far I only see {"data":"success"} and {"data":"failure"} in my console after clicking the button, the redirect still not work.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.