so I have a flask Application, where in the home page I am rendering a login page to sign in. After sign in they get a form to fill. I am also using the username value while they sign in later on in the form submit process. This is my relevant flask code:
@app.route('/', methods=['GET', 'POST'])
def home():
return render_template('Login_new.html')
@app.route('/login', methods=['POST'])
def logger():
if request.method == 'POST':
global user
user = request.form['username']
passwrd = request.form['password']
if (user=="admin") and (passwrd=="VendorAdmin2021"):
return redirect(url_for("admin.index"))
url = "api for authentication"
response = requests.post(url, json={"username": user,"password": passwrd}, verify=False)
#data = response.json()
print(response.status_code)
if response.status_code == 200:
return redirect(url_for("test"))
else:
flash('Wrong')
return render_template('Login_new.html')
The test url contains the actual form. Here is the Login_new.html file:
<html>
<head>
<link rel="stylesheet" href="/static/style2.css">
<title>Sign in</title>
</head>
<body>
<div class="main">
<p class="sign" align="center">Novartis</p>
<form class="form1" action="/login" method="POST" id="myForm">
<input class="un " type="text" align="center" placeholder="5-2-1 id" name="username">
<input class="pass" type="password" align="center" placeholder="Password" name="password">
<input type="submit" value="Log in" class="submit">
</div>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@10.12.5/dist/sweetalert2.all.min.js"></script>
{% with messages = get_flashed_messages() %}
{% if messages %}
<script>
var messages = {{ messages | safe }};
if (messages=="Wrong"){
swal.fire({
title:"Invalid id or password!",
text:"Please make sure you are connected to the Company Intranet",
icon:"error",
closeOnConfirm: false
});
}
</script>
{% endif %}
{% endwith %}
</body>
</html>
Everything works fine if the user follows the set procedure, but if they directly enter the test url in the browser, they bypass the login form and subsequently I can't record their username as well. Similarly for flask-admin url, if they input the admin credentials, they are redirected to admin url, but if they directly put the admin url, they can access it without any credentials. How can I prevent that?
EDIT: I tried using session to achieve the desired result, I tried to follow this https://techmonger.github.io/10/flask-simple-authentication/ . This is my code now:
if response.status_code == 200:
session["logged_in"] = True
return redirect(url_for("test"))
else:
flash('Wrong')
return render_template('Login_new.html')
And in the test url:
@app.route('/test')
def test():
if not session.get('logged_in'):
return render_template('Login_new.html')
form = vendorForm()
Now I am getting error that session has no attribute get. Please help, I have been stuck on this from way too long