Home > Enterprise >  Python flask return javascript variable and redirect page
Python flask return javascript variable and redirect page

Time:03-31

I'm using a login script to enable additional authentication on my web application. The authentication script is writing in JavaScript and embedded in python with flask.

The login script, authenticates the user and, on success outputs and ID. I want to use the ID that is returned to the javascript function in my python backend. Additional i want to redirect the user to the root page if the authentication was successful.

i searched this forum and googled on how to do this with javascript or jqeury. So far i did manage to send the ID to the backend with a POST request. Don't know if this is best practice, feels kinda of hacky.

Also when i redirect the request i see the GET request in my python console but the page isn't redirecting in my browser. I think this is because of javascript or jquery.

main.py

from flask import Flask, request, render_template, redirect, url_for

app = Flask(__name__, template_folder='/templates', static_folder='/static')

@app.route("/login", methods=['GET', 'POST'])
def login():
    print(request.data)
    if request.method == 'POST':
        response = request.get_json()
        print(response['userwid'])
        return redirect('/')
    else:
        return render_template('login.html')

@app.route("/", methods=['GET', 'POST'])
def loggedin():
    print('User is logged in')
    return render_template('index.html')

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug = True)

login.html

<!-- login.html -->

<!DOCTYPE html>
<html>
  <head>
    <title>Login</title>
    <script src="https://cdn.jsdelivr.net/npm/web3@latest/dist/web3.min.js"></script>
    <script src="https://unpkg.com/moralis/dist/moralis.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  </head>

  <body>
     
    <button id="btn-login">Login</button>
    <button id="btn-logout">Logout</button>
    <script type="text/javascript" src="/static/main.js"></script>
  </body>
</html>

main.js

// main.js

const serverUrl = "REPLACED-THIS-PART";
const appId = "REPLACED-THIS-PART";
Moralis.start({ serverUrl, appId });

/** Add from here down */
async function login() {
  let user = Moralis.User.current();
  if (!user) {
   try {
      user = await Moralis.authenticate({ signingMessage: "Authenticating" })
      console.log(user)
      console.log(user.get('useracc'))
      userwid= {'useracc': user.get('useracc')}

      $.ajax({
        type: "POST",
        url: "/login",
        data: JSON.stringify(userwid),
        contentType: "application/json",
        dataType: 'json',
      });
   } catch(error) {
     console.log(error)
   }
  }
}


async function logOut() {
  await Moralis.User.logOut();
  console.log("logged out");
}

document.getElementById("btn-login").onclick = login;
document.getElementById("btn-logout").onclick = logOut;

CodePudding user response:

Technically, you could, after successful login, just navigate to a route like /login/userid?id=12345 with 12345 being the user id.

On your flask backend, you take the id with id = request.args.to_dict().get("id") and return a redirect with return redirect("/"). (Info about redirecting with flask: https://pythonbasics.org/flask-redirect-and-errors/)

I don't know, wether that's best practise, but that's what i'd do.

  • Related