Reputation: 588
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:
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
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