0

Hello am new at using flask and I have been trying to figure out how to restrict some web pages unless logged in. I tried flask decorators I tried flask decorators but I couldn't understand it so I tried using flask principal which am able to get it running but still cannot be able to stop the access to that webpage. Code Description

from flask_principal import Permission, RoleNeed

# create permission with a single Need, in this case a RoleNeed
user_permission = Permission(RoleNeed('User'))

@app.route('/home')
def home_page():
return render_template('home.html')

@app.route('/user')
@user_permission.require()
def do_user_index():
return Response('Only if you are a user')

@app.route('/employee')
def employee_page():
user = User.query.all()
return render_template('employee.html', user=user)
def do_employee_page():
with user_permission.require():
return redirect(url_for('login_page'))
peter karanja
  • 39
  • 1
  • 1
  • 5

1 Answers1

0

You can use session:

First thing we gonna do is create a session at the moment of login:

@app.route(#route that you gonna use to login data verify)
def login():
  #login data verification

  flask.session["user data"] = #Data you want to use to identify the user

  #the next step that you wanna do

Now we gonna verify the session data in the pages, if the user are log in they gonna have their data in flask.session and if not, they not going to have the data in session.

@app.route('/user')
def do_user_index():

   if "user data" not in flask.session:
      #Redirect to the login page

   return Response('Only if you are a user')

You can consult the documentation to learn more about the how to use session. https://flask.palletsprojects.com/en/2.0.x/quickstart/#sessions