admin 管理员组文章数量: 1087649
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="/[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 / . 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
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/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
Share Improve this question edited Dec 24, 2020 at 10:16 Raghav Chamadiya asked Dec 24, 2020 at 5:08 Raghav ChamadiyaRaghav Chamadiya 2403 silver badges15 bronze badges 9- This problem is well covered in the <a href="blog.miguelgrinberg./post/… Mega Tutorial</> section on login. – Dave W. Smith Commented Dec 24, 2020 at 5:32
- blog.miguelgrinberg./post/… - I went through this one already. It is using flask-login which is using User model from the SQL database for authentication. My app uses an api url to verify instead of directly from database. Thats why I wasnt able to implement that solution to my app – Raghav Chamadiya Commented Dec 24, 2020 at 5:38
- The examples show flask_login being used with a database, but that's not required. – Dave W. Smith Commented Dec 24, 2020 at 6:18
- Have you tried using session? – Anthony Commented Dec 24, 2020 at 6:31
- You need to refactor the code in your login route to a decorator and add the decorator to any route you want to do authentication. – yuxiaoy Commented Dec 24, 2020 at 7:05
1 Answer
Reset to default 8You 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
本文标签:
版权声明:本文标题:javascript - Prevent users from directly accessing url and redirect to login if not logged in Flask - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.roclinux.cn/p/1744026849a2520784.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论