Issue
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/[email protected]/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
Solution
You can use your own custom decorator like in flask login module. Something similar to this,
def login_required(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if session.get('username') is None or session.get('if_logged') is None:
return redirect('/login',code=302)
return f(*args, **kwargs)
return decorated_function
Then use like this in a route which requires login,
@app.route('/', methods=['GET', 'POST'])
@login_required
def home():
#blah_blah
What this does is , whenever you call url '/' ,it calls decorated_function() present inside login_required() wrapper. So put your login logic inside deccorated_function(). Check if the user is logged in using sesion cookie(or whatever method you want), if not logged redirect to login else don't return anything.
Regarding that session.get() error, did you import session from module flask? The syntax seems correct
Answered By - Zincfan
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.