How to track the current user in flask-login?

Question:

I m trying to use the current user in my view from flask-login. So i tried to g object

I m assigning flask.ext.login.current_user to g object

@pot.before_request
def load_users():
   g.user = current_user.username

It works if the user is correct. But when i do sign-up or login as with wrong credentials
I get this error

AttributeError: 'AnonymousUserMixin' object has no attribute 'username'

Please enlight me where am i wrong…

Asked By: naga4ce

||

Answers:

AnonymousUserMixin has no username attribute. You need to overwrite the object and call the mixin. Have a look at LoginManager.anonymous_user which is an object which is used when no user is logged in.

You also need to get the user from somewhere. There is no point in storing the username in g as you could just use current_user.username.

If you wanted to get the username you would need too

if current_user.is_authenticated():
    g.user = current_user.username

This would require that the user object has a property called username. There are lots of ways to customize Flask-Logins use

I suggest re-reading the docs and taking a look at the source code:

https://github.com/maxcountryman/flask-login/blob/master/flask_login.py

Joe

Answered By: Joe Doherty

Well, the error message says it all. There is no logged in user, so current_user returns an AnonymousUserMixin. AnonymousUserMixin implements the interface described here: http://flask-login.readthedocs.org/en/latest/#your-user-class (which does not include a username property). Try something like this:

@pot.before_request
def load_users():
    if current_user.is_authenticated():
        g.user = current_user.get_id() # return username in get_id()
    else:
        g.user = None # or 'some fake value', whatever

Obviously, the rest of your code has to deal with the possibility that g.user will not refer to a real user.

Answered By: pjnola

Thanks for your answer @Joe and @pjnola, as you all suggested i referred flask-login docs

I found that we can customize the anonymous user class, so i customized for my requirement,

Anonymous class

#!/usr/bin/python
#flask-login anonymous user class
from flask.ext.login import AnonymousUserMixin
class Anonymous(AnonymousUserMixin):
  def __init__(self):
    self.username = 'Guest'

Then added this class to anonymous_user

login_manager.anonymous_user = Anonymous

From this it was able to fetch the username if it was anonymous request.

Answered By: naga4ce

For finding if there is a loggin session we can do the following: (I have gone through all solutions and noted that when I use the below statements it is failing.)

if current_user.is_authenticated():
    g.user = current_user.username

The correct way is:

if current_user.is_authenticated:
    g.user = current_user.username

And then it works fine.

Answered By: nimodka