Skip to content

Commit

Permalink
get_token: always return 200 status code
Browse files Browse the repository at this point in the history
  • Loading branch information
lafrech committed Apr 25, 2024
1 parent 578a1a2 commit 6a3c4b6
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 22 deletions.
40 changes: 19 additions & 21 deletions src/bemserver_api/extensions/smorest.py
Original file line number Diff line number Diff line change
Expand Up @@ -167,37 +167,35 @@ class GetJWTArgsSchema(Schema):


class GetJWTRespSchema(Schema):
status = ma.fields.String(validate=ma.validate.OneOf(("success", "failure")))
token = ma.fields.String()


class GetJWTErrorSchema(Schema):
error = ma.fields.String()


@auth_blp.route("/token", methods=["POST"])
@auth_blp.arguments(GetJWTArgsSchema)
@auth_blp.response(
201,
200,
GetJWTRespSchema,
example={
"token": (
"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.e30.u"
"JKHM4XyWv1bC_-rpkjK19GUy0Fgrkm_pGHi8XghjWM"
)
examples={
"success": {
"value": {
"status": "success",
"token": (
"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.e30.u"
"JKHM4XyWv1bC_-rpkjK19GUy0Fgrkm_pGHi8XghjWM"
),
},
},
"failure": {
"value": {
"status": "failure",
},
},
},
description="Token created",
)
@auth_blp.alt_response(
# No 401, here. See https://stackoverflow.com/a/67359937
200,
schema=GetJWTErrorSchema,
description="Wrong credentials",
example={"error": "Wrong username or password"},
success=True,
)
def get_token(creds):
"""Get an authentication token"""
user = auth.get_user_by_email(creds["email"])
if user is None or not user.check_password(creds["password"]):
return flask.jsonify({"error": "Wrong username or password"})
return {"token": auth.encode(user)}
return flask.jsonify({"status": "failure"})
return {"status": "success", "token": auth.encode(user)}
5 changes: 4 additions & 1 deletion tests/extensions/test_smorest.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,20 @@ def test_get_token(self, app, users):
client = app.test_client()
payload = {"email": user_1.email, "password": "@ctive"}
resp = client.post("/auth/token", json=payload)
assert resp.status_code == 201
assert resp.status_code == 200
assert resp.json["status"] == "success"
assert "token" in resp.json

# Wrong password
client = app.test_client()
payload = {"email": user_1.email, "password": "dummy"}
resp = client.post("/auth/token", json=payload)
assert resp.status_code == 200
assert resp.json == {"status": "failure"}

# Wrong email
client = app.test_client()
payload = {"email": "dummy@dummy.com", "password": "dummy"}
resp = client.post("/auth/token", json=payload)
assert resp.status_code == 200
assert resp.json == {"status": "failure"}

0 comments on commit 6a3c4b6

Please sign in to comment.