login required - csemanish12/flask_blog GitHub Wiki
It is fairly simple to add restriction to our route so that only logged in user can access those routes.
Lets create a new route for user profile and add these codes in our routes.py
@app.route("/profile")
def profile():
return render_template('profile.html')and also create a new file called profile.html
{% extends 'layout.html' %}
{% block content %}
<h1>{{ current_user.username }}</h1>
{% endblock content %}Now lets restrict users to visit this page if they are not logged in. We will import login_required from flask-login and it will handle the logic for us
we will update our profile route as follows
.
from flask_login import login_required
.
@app.route("/profile")
@login_required
def profile():
return render_template('profile.html', title_name='profile')This blocks user from visiting profile page if they are not logged in. We also need to redirect user to login page when they are not logged in and try access our protected routes
we can achieve this by configuring login_view attribute in login manager. lets open our initialization file and add these code just below the line where we have created our login_manager object
login_manager.login_view = 'login'here, 'login' is the name of method that we have defined in our login route.
Implementation can be found over this commit