0

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!"'})

1 Answer 1

1

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

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

Comments

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.