user23059245
user23059245

Reputation:

How can I restrict access in fields in web aplication with Flask

I'm developing a web application with python/flask. I want to limit access to some application fields so that only admins have access.

I would like to know if there is a ready-made tool to do this or if the best way is to authenticate with a value in the database, such as admin data for each user.

When admin == True, the user has access When admin == False, the user doesn't have access

class User(UserMixin, db.Model):
    __bind_key__ = 'user_database'
    id = db.Column(db.Integer, primary_key = True)
    name = db.Column(db.String(120))
    lastname = db.Column(db.String(120))
    email = db.Column(db.String(120), unique=True, index=True)
    password_hash = db.Column(db.String(128))
    admin = db.Column(db.Boolean())

    def is_admin(user_id):
       user = User.query.filter_by(id=user_id).first()
       if user.admin = True:
           print("admin")
       else: print("Not Admin")

Can I make like this? Or its no safe?

Upvotes: 0

Views: 31

Answers (1)

Vinay Davda
Vinay Davda

Reputation: 87

One of the approach is you can do below:

One of approach in your model is you can add is_admin method and make is a property of class:

class User(UserMixin, db.Model):
    # ... same all fields

    @property
    def is_admin(self):
        return self.admin

You can use this method as a variable to check whether he's admin or not like below:

user = User.query.get(user_id)
if user.is_admin:
    # Here you can add your logic if admin
    print("Admin")
else:
    # Here you can add your logic if not admin
    print("Not Admin")

Upvotes: 0

Related Questions