Flask Httpauth @basic_auth.error_handler being invoked when it is not supposed to

17 Views Asked by At

I have defined this four handlers:

basic_auth = HTTPBasicAuth()
token_auth = HTTPTokenAuth()

@basic_auth.verify_password
def verify_password(username,password_hash):
  user = db.session.scalar(sa.select(User).where(User.username == username))
  if user and bcrypt.check_password_hash(user.password_hash,password_hash):
    return user

@basic_auth.error_handler
def basic_auth_error(status):
  return {"error":"Unauthorized basic access"},status

@token_auth.verify_token
def verify_token(token):
  return User.check_token(token) if token else None

@token_auth.error_handler
def token_auth_error(status):
  return {"error":"Unauthorized token access"},status

Then, for example, I defined the function:

@bp.route("/api/user/jobs",methods = ["GET"])
@token_auth.login_required
def jobs_api():
  parser = reqparse.RequestParser()
  parser.add_argument("user_id",type = int,help = "Wrong user id. Please check that it is your user id.",required = True,location = "json")
  args = parser.parse_args()
  return jsonify([tuple(row) for row in get_current_jobs(args["user_id"])])

When I do:

curl -X GET -H "Content-Type: application/json" -d '{"user_id": 8}' http://127.0.0.1:5000/api/user/jobs

Of course it doesn't work and the @token_auth.error_handler is invoked. But, then, when I generate a token and post it:

curl -X GET -H "Authorization: Bearer 40c5c82b9f9f6b4679d7cdd08040f4d4" -H "Content-Type: application/json" -d '{"user_id": 8}' http://127.0.0.1:5000/api/user/jobs

Now, I have another function:

@bp.route("/api/convert",methods = ["POST"])
@token_auth.login_required
def convert_api():
  # Handle POST
  form = ConvertForm()
  if form.validate_on_submit():
    convert_settings_id = add_conversion_settings(form.raw_type.data,form.version.data)
    job_id = add_new_job(form.user_id.data,"convert",convert_settings_id)
    for file in form.files.data:
      add_input_file(form.user_id.data,file,job_id)
    return jsonify({"message":"Your files have been queued for upload!","status":"success"})
  return jsonify(errors=form.errors), 400

It receives information through multipart/form-data. When I do:

curl -X POST \
-H "Authorization: Bearer 40c5c82b9f9f6b4679d7cdd08040f4d4" \
-H "Content-Type: multipart/form-data" \
-F "[email protected]" \
-F "user_id=8" \
-F "raw_type=SBF" \
-F "version=3.03" \
http://127.0.0.1:5000/api/convert

not only does it not work, but @basic_auth.error_handler is thrown. I don't understand why; if anything @token_auth.error_handler should be invoked since I have defined the @token_auth.login_required decorator, but why is the @basic_auth.error_handler being invoked?

0

There are 0 best solutions below