Skip to content
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

[Issue #3448] Create API endpoint for POST /users/:userID/save-searches #3472

Open
wants to merge 18 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 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
45 changes: 44 additions & 1 deletion api/src/api/users/user_routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,19 @@
UserSavedOpportunitiesResponseSchema,
UserSaveOpportunityRequestSchema,
UserSaveOpportunityResponseSchema,
UserSaveSearchRequestSchema,
UserSaveSearchResponseSchema,
UserTokenLogoutResponseSchema,
UserTokenRefreshResponseSchema,
)
from src.auth.api_jwt_auth import api_jwt_auth, refresh_token_expiration
from src.auth.auth_utils import with_login_redirect_error_handler
from src.auth.login_gov_jwt_auth import get_final_redirect_uri, get_login_gov_redirect_uri
from src.db.models.user_models import UserSavedOpportunity, UserTokenSession
from src.db.models.user_models import (
UserSavedOpportunity,
UserTokenSession,
UserSavedSearch,
)
from src.services.users.delete_saved_opportunity import delete_saved_opportunity
from src.services.users.get_saved_opportunities import get_saved_opportunities
from src.services.users.get_user import get_user
Expand Down Expand Up @@ -231,3 +237,40 @@ def user_get_saved_opportunities(db_session: db.Session, user_id: UUID) -> respo
saved_opportunities = get_saved_opportunities(db_session, user_id)

return response.ApiResponse(message="Success", data=saved_opportunities)


@user_blueprint.post("/<uuid:user_id>/saved-searches")
@user_blueprint.input(UserSaveSearchRequestSchema, location="json")
@user_blueprint.output(UserSaveSearchResponseSchema)
@user_blueprint.doc(responses=[200, 401])
@user_blueprint.auth_required(api_jwt_auth)
@flask_db.with_db_session()
def user_save_search(
db_session: db.Session, user_id: UUID, json_data: dict
) -> response.ApiResponse:
logger.info("POST /v1/users/:user_id/saved-searches")

user_token_session: UserTokenSession = api_jwt_auth.current_user # type: ignore

# Verify the authenticated user matches the requested user_id
print(user_token_session.user_id, user_id)
mikehgrantsgov marked this conversation as resolved.
Show resolved Hide resolved
if user_token_session.user_id != user_id:
raise_flask_error(401, "Unauthorized user")

# Create the saved search record
saved_search = UserSavedSearch(
user_id=user_id, name=json_data["name"], search_query=json_data["search_query"]
)

with db_session.begin():
db_session.add(saved_search)
mikehgrantsgov marked this conversation as resolved.
Show resolved Hide resolved

logger.info(
"Saved search for user",
extra={
"user.id": str(user_id),
"saved_search.id": str(saved_search.saved_search_id),
},
)

return response.ApiResponse(message="Success")
18 changes: 18 additions & 0 deletions api/src/api/users/user_schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,3 +87,21 @@ class UserSavedOpportunitiesResponseSchema(AbstractResponseSchema):
fields.Nested(SavedOpportunityResponseV1Schema),
metadata={"description": "List of saved opportunities"},
)


class UserSaveSearchRequestSchema(Schema):
name = fields.String(
required=True,
metadata={"description": "Name of the saved search", "example": "Example search"},
)
search_query = fields.Dict(
required=True,
metadata={
"description": "The search query parameters to save",
"example": {"keywords": "search", "location": "Foo, Bar"},
},
)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we have this be the actual schema we use in the search endpoint? Just to make sure it's valid.

Also want to make sure the JSON serialization works with a full search request object for things like enums and dates.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I added something to the test using get_search_request(). Something like this you have in mind?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was thinking we would do search_query = fields.Nested(OpportunitySearchRequestV1Schema) - that way we can only take in a schema that is valid for search. Anything that isn't a valid search request should be rejected (eg. a user couldn't just pass {"some_field": "whatever"}.)

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I checked in the changes. This makes me wonder if we should also store the version of the search request schema for validation later. If, for example, we want the response to correspond to the schema that was inputted. It would be able to handle schema changes (and we could just output a dict response type validated against the stored schema version in a new db column. Otherwise we would not be able to validate response schema if this OpportunitySearchRequestV1Schema changes.



class UserSaveSearchResponseSchema(AbstractResponseSchema):
data = fields.MixinField(metadata={"example": None})
97 changes: 97 additions & 0 deletions api/tests/src/api/users/test_user_save_search_post.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
import uuid

import pytest

from src.auth.api_jwt_auth import create_jwt_for_user
from src.db.models.user_models import UserSavedSearch
from tests.src.db.models.factories import UserFactory


@pytest.fixture
def user(enable_factory_create, db_session):
user = UserFactory.create()
db_session.commit()
return user


@pytest.fixture
def user_auth_token(user, db_session):
token, _ = create_jwt_for_user(user, db_session)
return token


@pytest.fixture(autouse=True)
def clear_saved_searches(db_session):
db_session.query(UserSavedSearch).delete()
db_session.commit()
yield


def test_user_save_search_post_unauthorized_user(client, db_session, user, user_auth_token):
# Try to save a search for a different user ID
different_user = UserFactory.create()

response = client.post(
f"/v1/users/{different_user.user_id}/saved-searches",
headers={"X-SGG-Token": user_auth_token},
json={"name": "Test Search", "search_query": {"keywords": "python"}},
)

assert response.status_code == 401
assert response.json["message"] == "Unauthorized user"

# Verify no search was saved
saved_searches = db_session.query(UserSavedSearch).all()
assert len(saved_searches) == 0


def test_user_save_search_post_no_auth(client, db_session, user):
# Try to save a search without authentication
response = client.post(
f"/v1/users/{user.user_id}/saved-searches",
json={"name": "Test Search", "search_query": {"keywords": "python"}},
)

assert response.status_code == 401
assert response.json["message"] == "Unable to process token"

# Verify no search was saved
saved_searches = db_session.query(UserSavedSearch).all()
assert len(saved_searches) == 0


def test_user_save_search_post_invalid_request(client, user, user_auth_token, db_session):
# Make request with missing required fields
response = client.post(
f"/v1/users/{user.user_id}/saved-searches",
headers={"X-SGG-Token": user_auth_token},
json={},
)

assert response.status_code == 422 # Validation error

# Verify no search was saved
saved_searches = db_session.query(UserSavedSearch).all()
assert len(saved_searches) == 0


def test_user_save_search_post(client, user, user_auth_token, enable_factory_create, db_session):
# Test data
search_name = "Test Search"
search_query = {"keywords": "python"}

# Make the request to save a search
response = client.post(
f"/v1/users/{user.user_id}/saved-searches",
headers={"X-SGG-Token": user_auth_token},
json={"name": search_name, "search_query": search_query},
)

assert response.status_code == 200
assert response.json["message"] == "Success"

# Verify the search was saved in the database
saved_search = db_session.query(UserSavedSearch).one()
assert saved_search.user_id == user.user_id
assert saved_search.name == search_name
assert saved_search.search_query == search_query
Loading