Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the point of the "is_authenticated" method used in Flask-Login?

I'm working through the Flask Mega-Tutorial right now and I've come across this bit of code:

class User(db.Model):
    id = db.Column(db.Integer, primary_key = True)
    nickname = db.Column(db.String(64), unique = True)
    email = db.Column(db.String(120), unique = True)
    role = db.Column(db.SmallInteger, default = ROLE_USER)
    posts = db.relationship('Post', backref = 'author', lazy = 'dynamic')

    def is_authenticated(self):
        return True

    def is_active(self):
        return True

    def is_anonymous(self):
        return False

    def get_id(self):
        return unicode(self.id)

    def __repr__(self):
        return '<User %r>' % (self.nickname)

is_authenticated, is_active, and is_anonymous seem quite strange to me - when would they ever return anything other than their predefined value?

Could somebody explain to me why Flask-Login makes me use these seemingly useless methods?

like image 878
user1787531 Avatar asked Oct 23 '13 03:10

user1787531


People also ask

Which of the following can be used to login a user in Flask?

Flask-Login can manage user sessions. Start by adding the UserMixin to your User model. The UserMixin will add Flask-Login attributes to the model so that Flask-Login will be able to work with it. With Flask-Login setup, use the /login route.

How do I access current users in Flask?

In your login function just store the value like: first import the session from flask. Then use like this. then use it like {{ session['username'] }} in your template. Is this recommended for flask security because it takes care of all of the user login management.


1 Answers

First of all, is_anonymous() and is_authenticated() are each other's inverse. You could define one as the negation of the other, if you want.

You can use these two methods to determine if a user is logged in.

When nobody is logged in Flask-Login's current_user is set to an AnonymousUser object. This object responds to is_authenticated() and is_active() with False and to is_anonymous() with True.

The is_active() method has another important use. Instead of always returning True like I proposed in the tutorial, you can make it return False for banned or deactivated users and those users will not be allowed to login.

like image 186
Miguel Avatar answered Sep 28 '22 07:09

Miguel