Skip to content

fix: Handle edge cases for verify_session decorator #348

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jun 14, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [unreleased]

### Changes

- Throw error when `verify_sesion` is used with a view that allows `OPTIONS` or `TRACE` requests
- Allow `verify_session` decorator to be with `@app.before_request` in Flask without returning a response


## [0.14.3] - 2023-06-7

Expand Down
2 changes: 2 additions & 0 deletions supertokens_python/recipe/session/api/implementation.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,8 @@ async def verify_session(
) -> Union[SessionContainer, None]:
method = normalise_http_method(api_options.request.method())
if method in ("options", "trace"):
if session_required:
raise Exception(f"verify_session cannot be used with {method} method")
return None
incoming_path = NormalisedURLPath(api_options.request.get_path())
refresh_token_path = api_options.config.refresh_token_path
Expand Down
5 changes: 3 additions & 2 deletions supertokens_python/recipe/session/framework/flask/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,8 +61,9 @@ def wrapped_function(*args: Any, **kwargs: Any):
baseRequest.set_session_as_none()
else:
baseRequest.set_session(session)
response = make_response(f(*args, **kwargs))
return response

response = f(*args, **kwargs)
return make_response(response) if response is not None else None

return cast(_T, wrapped_function)

Expand Down
81 changes: 81 additions & 0 deletions tests/Flask/test_flask.py
Original file line number Diff line number Diff line change
Expand Up @@ -683,3 +683,84 @@ async def test_search_with_provider_google_and_phone_one(driver_config_app: Any)
assert response.status_code == 200
data_json = json.loads(response.data)
assert len(data_json["users"]) == 0

from tests.utils import get_st_init_args

@fixture(scope="function")
def flask_app():
app = Flask(__name__)
Middleware(app)

app.testing = True

counter: Dict[str, int] = {}

@app.before_request # type: ignore
@verify_session(session_required=False)
def audit_request(): # type: ignore
nonlocal counter

user_id = None
s: SessionContainer = g.supertokens

if s:
user_id = s.get_user_id()
print(f"User {user_id} tried to accesss {request.path}")
else:
user_id = "unknown"
print(f"Unknown user tried to access {request.path}")

if request.path != "/stats":
counter[user_id] = counter.get(user_id, 0) + 1

@app.route("/stats") # type: ignore
def test_api(): # type: ignore
return jsonify(counter)

@app.route("/login") # type: ignore
def login(): # type: ignore
user_id = "userId"
s = create_new_session(request, user_id, {}, {})
return jsonify({"user": s.get_user_id()})

@app.route("/ping") # type: ignore
def ping(): # type: ignore
return jsonify({"msg": "pong"})

@app.route("/options-api", methods=["OPTIONS", "GET"]) # type: ignore
@verify_session()
def options_api(): # type: ignore
return jsonify({"msg": "Shouldn't come here"})

return app

def test_verify_session_with_before_request_with_no_response(flask_app: Any):
init(**{**get_st_init_args([session.init(get_token_transfer_method=lambda *_: "cookie")]), "framework": "flask"}) # type: ignore
start_st()

client = flask_app.test_client()

assert client.get("stats").json == {}

assert client.get("/ping").status_code == 200

assert client.get("stats").json == {"unknown": 1}

with pytest.raises(Exception) as e:
client.options("/options-api")

assert str(e.value) == "verify_session cannot be used with options method"

assert client.get("stats").json == {"unknown": 2}

assert client.get("/login").status_code == 200

assert client.get("/stats").json == {"unknown": 3}

assert client.get("/ping").status_code == 200

assert client.get("/stats").json == {"unknown": 3, "userId": 1}

assert client.get("/ping").status_code == 200

assert client.get("/stats").json == {"unknown": 3, "userId": 2}