user956424
user956424

Reputation: 1609

Can we use JWT with sqlalchemy in flask api as below?

Following are the code files with relevant code snippets:

init.py:

app = Flask(__name__)
cors = CORS(app, resources={r"/api/*": {"origins": "*"}})
app.config['SECRET_KEY'] = 'super-secret'

In auth.py:

def authenticate_user(login, password):
    '''
    Return dict or None after checking against db for valid user
    '''
    s = select([users]).where(users.c.email==login)
    result_set = conn.execute(s)
    if result_set.rowcount == 1:
        for r in result_set:
            print r[users.c.password], 'result_set[users.c.password]'
            if pwd_context.verify(password, r[users.c.password]):
                # There is only one unique email/password pair
                print 'matched'
                return dict(r)
            else:
                return None
    return

How to get the access_token value for the user on login? I have installed Flassk-JWT in the virtualenv and followed this doc: https://pythonhosted.org/Flask-JWT/ But please note I am not using OOPs ie. User class etc. I am using sqlalchemy core with Flask and python. To further use this token, I need to call it as a decorator for the API call is what I understand as:

@app.route('/rt/api/v1.0/list', methods=['GET'])
@jwt_required()

In views.py:

from myapp.auth import authenticate_user

@app.route('/auth', methods=['POST','GET'])
def login():
    email = request.form["email"]
    password = request.form["password"]
    if request.method == 'POST':
            result_set = authenticate_user(email, password)
            if result_set:
                session['email'] = result_set['email']
            user_dict = result_set
            if user_dict:
                session['email'] = user_dict['email']
            jwt = JWT(app, user_dict['email'], user_dict["id"])

How to exactly connect the various code files to get the access token value is what I am stuck up with.Please guide. Also Wish to exclude the login API request from the before_request callback(). All other APIs can have the before and after_request callbacks() executed.

Upvotes: 0

Views: 984

Answers (1)

user956424
user956424

Reputation: 1609

Finally found a way better implementation with the basic usage on readthedocs

Upvotes: 1

Related Questions