1

My User Model looks like this

class UserModel(Document):
    first_name = StringField(required=True, max_length=50)
    last_name = StringField(required=True, max_length=50)
    username = StringField(required=True)
    password = StringField(required=True, min_length=6)

def to_json(self):
    return {
            "id": str(self.pk),
            "first_name": self.first_name,
            "last_name": self.last_name,
            "username": self.username,
            "password": self.password
        }

My authentication methods look like this

def authenticate(username, password):
    user = UserModel.objects.get(username=username)
    if user and checkpw(password.encode('utf-8'), user.password.encode('utf-8')):
    return user.to_json()

def identity(payload):
    user_id = payload['identity']
    u = UserModel.objects.get(pk=user_id)
    return u.to_json


jwt = JWT(app, authenticate, identity)  # /auth endpoint

I created the to_json() method hoping to solve this issue and to serialize the primary key which will appear in a normal query like this

"_id" : ObjectId("5aa9613d4fe35c23fca4d601")
instead of nicely like this~
"id": "5aa9613d4fe35c23fca4d601"

The error I get is:

  "/home/joe/PyRest/FlaskMongo-venv/lib/python3.6/site-packages/flask_jwt/__init__.py", line 53, in _default_jwt_payload_handler
    identity = getattr(identity, 'id') or identity['id']
AttributeError: 'dict' object has no attribute 'id'`
0

1 Answer 1

2

This is a common complaint for Flask-JWT. At a glance it looks like it has 7 open merge requests to fix it: https://github.com/mattupstate/flask-jwt/pulls?utf8=%E2%9C%93&q=is%3Apr+is%3Aopen+id

Unfortunately flask-jwt has been abandoned for a long time now. Perhaps check out flask-jwt-extended or flask-jwt-simple as alternatives that are still actively maintained (and IMO better designed, but I am the author so I am of course biased) ;)

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! I was actually considering switching before reading this.
declare id as a column name in you UserModel class

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.