How can I get the current user(id) in flask-jwt-extended?
Asked Answered
C

1

9

I am new to python/flask and I am working on one to many relationships. I tried some solutions but didn't work. My problem here is in the "/add_about" route I want to get the user_id that created this post and be able to see that reflected in the database.

Here is my code:

from flask import Blueprint, jsonify, request
from flask_jwt_extended import jwt_required, current_user, get_current_user, get_jwt_identity
from app import db
from models.about import About, AboutSchema
from models.users import User


about = Blueprint('about', __name__)

about_schema = AboutSchema()
abouts_schema = AboutSchema(many=True)


@about.route('/')
def hello():
    return "Oh LA LA LA LA !!!!!!"


# Get all abouts:
@about.route('/all', methods=['GET'])
def abouts():
    abouts_list = About.query.all()
    result = abouts_schema.dump(abouts_list)
    return jsonify(result)


@about.route('/add_about', methods=['POST'])
@jwt_required
def add_about():
    description = request.form['description']
    user_id = get_jwt_identity()        #I tried using "current_user" an "get_current_user"
    new_about = About(description=description, user=user_id)

    db.session.add(new_about)
    db.session.commit()
    return jsonify(message="You added a bio"), 201

Here are the db models:

from sqlalchemy import Column, Integer, String, FLOAT
from app import db, ma


database models:
class User(db.Model):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    first_name = Column(String)
    last_name = Column(String)
    email = Column(String, unique=True)
    password = Column(String)

    about = db.relationship('About', backref='user', lazy='dynamic')


class About(db.Model):
    __tablename__ = 'abouts'
    about_id = Column(Integer, primary_key=True)
    description = Column(String(1000))

    user_id = db.Column(db.Integer, db.ForeignKey('users.id'))


class UserSchema(ma.Schema):
    class Meta:
        fields = ('id', 'first_name', 'last_name', 'email', 'password')


class AboutSchema(ma.Schema):
    class Meta:
        fields = ('about_id', 'description')

Here are the user routes:

from flask import Blueprint, jsonify, request
from app import db
# from models.users import User, UserSchema
from models.users import User, UserSchema
from flask_jwt_extended import JWTManager, jwt_required, create_access_token


users = Blueprint('user', __name__)


user_schema = UserSchema()
users_schema = UserSchema(many=True)


@users.route('/register', methods=['POST'])
def register():
    email = request.form['email']
    test = User.query.filter_by(email=email).first()
    if test:
        return jsonify(messgae="that email already exists")
    else:
        first_name = request.form['first_name']
        last_name = request.form['last_name']
        password = request.form['password']
        user = User(first_name=first_name, last_name=last_name, email=email, password=password)
        db.session.add(user)
        db.session.commit()
        return jsonify(messgae="User created successfully"), 201


@users.route('/login', methods=['POST'])
def login():
    if request.is_json:
        email = request.json['email']
        password = request.json['password']
    else:
        email = request.form['email']
        password = request.form['password']

    test = User.query.filter_by(email=email, password=password).first()
    if test:
        access_token = create_access_token(identity=email)
        return jsonify(message="Login succeeded!", access_token=access_token), 200
    else:
        return jsonify(message="Bad email or password"), 401

here is a screenshot from my db admin: enter image description here

Catina answered 9/4, 2020 at 7:27 Comment(2)
Please refer to this link : pythonhosted.org/Flask-JWTWoald
flask-jwt-extended.readthedocs.io/en/stable/…Roddie
A
13

When you register your jwt token on login, you register the token with the users email.

user route

test = User.query.filter_by(email=email, password=password).first()
    if test:
        access_token = create_access_token(identity=email) # identity = email
        return jsonify(message="Login succeeded!", access_token=access_token), 200
    else:
        return jsonify(message="Bad email or password"), 401

So 2 possible solutions:

  1. You can do a db lookup in the user table on email address and return the userId.
@about.route('/add_about', methods=['POST'])
@jwt_required
def add_about():
    description = request.form['description']
    user = User.query.filter_by(email=get_jwt_identity()).first() # Filter DB by token (email)
    new_about = About(description=description, user=user)
  1. Or you can register the user.id as the jwt token
access_token = create_access_token(identity=test.id)

Then user_id = get_jwt_identity() should then return the user.id from the token

Altar answered 9/4, 2020 at 8:13 Comment(1)
Thank you so much for the answer. I went with the first solution and it didn't work directly until I changed the (user = user.id) to be just( user = user) otherwise it will throw this error (AttributeError: 'int' object has no attribute '_sa_instance_state'). It would be great if you change it in your answer. I wish i could vote for your answer but i can't vote yet!Catina

© 2022 - 2024 — McMap. All rights reserved.