DzITC
DzITC

Reputation: 879

Python: Flask session handling with JWT token and cookies

I'm building a cloud service and there's one thing that I need to know. It's my third-day using flask and JWT, so basically I need to somehow see if the user is logged in. So what I have done for now is log in the system which generates a JWT authentication token which has user info hashed inside it. For now, after the login, I generated a token and save it in cookies and now I have one thing that the user can log in again when he's logged in, and the system generated another one JWT token. So now I need to make a session which saves the user session status like - logged in = True, and the session would automatically close when the JWT token expires, I have tried to make it, but is this a good example of doing it? And here's my code.

def token_required(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        token = None

        if 'x-access-token' in request.cookies:
            token = request.cookies['x-access-token']
        else:
            return jsonify({'message': 'Token is missing'}), 401

        try:
            data = jwt.decode(token, app.config['SECRET_KEY'])
            current_user = User.query.filter_by(public_id=data['public_id']).first()
        except jwt.DecodeError:
            print('decodeerrr')
            return jsonify({'message': 'Token is missing'}), 401

        except jwt.exceptions.ExpiredSignatureError:
            return jsonify({'message': 'Token has expired'}), 401

        return f(current_user, *args, **kwargs)
    return decorated

@app.route('/login')
def login():

    if 'x-access-token' in request.cookies:
        token = request.cookies['x-access-token']
        try:
            data = jwt.decode(token, app.config['SECRET_KEY'])
            return jsonify({'message': 'User is already logged in cant perform another login'}), 200
        except jwt.DecodeError:
            print('decodeerrr')
            return jsonify({'message': 'Token is missing'}), 401

        except jwt.exceptions.ExpiredSignatureError:
            return jsonify({'message': 'Token has expired'}), 401
    else:
        pass


    auth = request.authorization

    if not auth or not auth.username or not auth.password:
        return make_response('Could not verify', 401, {'WWW-Authenticate': 'Basic realm="Login required!"'})

    user = User.query.filter_by(username=auth.username).first()

    if not user:
        return make_response('Could not verify', 401, {'WWW-Authenticate': 'Basic realm="Login required!"'})

    if check_password_hash(user.password, auth.password):
        token = jwt.encode({'public_id': user.public_id, 'exp': datetime.datetime.now() + datetime.timedelta(minutes=30)}, app.config['SECRET_KEY'])
        print("++++++++++++++++++++++ ANOTHER LOGIN +++++++++++++++++++++++")
        resp = make_response(f'Successfully Logged in as {user.username}', 200)
        resp.set_cookie('x-access-token', token.decode('UTF-8'), expires=datetime.datetime.utcnow() + datetime.timedelta(seconds=15))
        return resp

        #return jsonify({'token': token.decode('UTF-8')})
        #resp = make_response("hello") #here you could use make_response(render_template(...)) too
        #resp.headers['x-access-token'] = token.decode('UTF-8')
        #return resp

    return make_response('Could not verify', 401, {'WWW-Authenticate': 'Basic realm="Login required!"'})

Upvotes: 0

Views: 5004

Answers (1)

Sai Kumar
Sai Kumar

Reputation: 285

I think you already set the expire argument in set cookie , so session token automatically expires at that time.

Upvotes: 1

Related Questions