Maylor
Maylor

Reputation: 588

Flask-restful - During handling of the above exception, another exception occurred

As part a Flask-restful API I have a login Resource:

class LoginApi(Resource):
    def post(self):
        try:
            body = request.get_json()
            user = User.objects.get(email=body.get('email'))
            authorized = user.check_password(body.get('password'))
            if not authorized:
                raise UnauthorizedError
            expires = datetime.timedelta(days=7)
            access_token = create_access_token(identity=str(user.id), expires_delta=expires)
            return {'token': access_token}, 200
        except DoesNotExist:
            raise UnauthorizedError
        except Exception as e:
            raise InternalServerError

There are 4 scenarios for login route:

  1. Email and Password are correct
  2. Email does not exist in the database - in this case the UnauthorizedError is raised correctly.
  3. Email exists but password is incorrect - in this case I have an issue (described below)
  4. Some other Error - InternalServerError is raised correctly.

So for number 3 - instead of getting an UnauthorizedError, I am getting an InternalServerError.

The if not authorized: statement is working correctly (If i put a print in there I can see it work). However for some reason I am getting the following when trying to raise the error:

During handling of the above exception, another exception occurred:

I came across this PEP article which seems to suggest changing to raise UnauthorizedError from None but the issue persists. Does anyone know how I can implement this successfully? Ideally I would like the same error to be raised from scenarios 2 and 3, otherwise there is a potential for someone to know whether or not an email exists in the database, from the errors they get back.

Upvotes: 1

Views: 332

Answers (1)

Wheel
Wheel

Reputation: 28

The if statement is raising UnAuthorized, but that happens in the excepts, you have to raise DoesNotExist to make it so that UnAuthorized can be raised in the except.

Upvotes: 1

Related Questions