-
Notifications
You must be signed in to change notification settings - Fork 1
feat(ui-api): collect user answer metrics and persist them #8
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
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
106c677
feat(api): add analytics endpoint for collecting answer stats
hoangsonww 9712874
Merge remote-tracking branch 'origin/feat/enhance-api' into feat/enha…
hoangsonww f334681
feat(api): add analytics endpoint for collecting answer stats
hoangsonww 4ed4918
feat(api): add analytics endpoint for collecting answer stats
hoangsonww 8620449
feat(api): add analytics endpoint for collecting answer stats
hoangsonww 21d8002
Merge branch 'main' into feat/enhance-api
hoangsonww c37d9ae
feat(api): add analytics endpoint for collecting answer stats
hoangsonww ed94594
Merge remote-tracking branch 'origin/feat/enhance-api' into feat/enha…
hoangsonww d9e366d
feat(api): add analytics endpoint for collecting answer stats
hoangsonww File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| ## SUMMARY | ||
|
|
||
| ## TEST PLAN | ||
|
|
||
| --- | ||
|
|
||
| ## Pre-merge author checklist | ||
|
|
||
| - [ ] I've clearly explained: | ||
| - [ ] What problem this PR is solving. | ||
| - [ ] How this problem was solved. | ||
| - [ ] How reviewers can test my changes. | ||
| - [ ] I've indicated what Jira issue(s) this PR is linked to. | ||
| - [ ] I've included tests I've run to ensure my changes work. | ||
| - [ ] I've added unit tests for any new code, if applicable. | ||
| - [ ] I've documented any added code. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,61 @@ | ||
| # Security | ||
|
|
||
| This document summarizes the key security controls and best practices for the AugMed App (frontend + backend). | ||
|
|
||
| ## 1. Transport Security | ||
| - **HTTPS only** | ||
| All traffic to `https://augmed1.dhep.org` is encrypted with TLS. | ||
| - **HSTS** | ||
| The backend API enforces HTTP Strict Transport Security to prevent downgrade attacks. | ||
|
|
||
| ## 2. Authentication & Authorization | ||
| - **JWT-based auth** | ||
| Users authenticate via a JSON Web Token (JWT) issued by the backend. | ||
| - **httpOnly cookies** | ||
| JWTs are stored in httpOnly cookies to mitigate XSS-based token theft. | ||
| - **Route protection** | ||
| All API endpoints under `/api/*` require a valid JWT and check user ownership. | ||
|
|
||
| ## 3. CORS | ||
| - **Restricted origin** | ||
| Backend CORS policy only allows requests from the official frontend origin (`https://augmed1.dhep.org`). | ||
| - **Preflight checks** | ||
| `OPTIONS` requests are handled and validated before allowing any state-changing method. | ||
|
|
||
| ## 4. Secrets & Config | ||
| - **Environment variables** | ||
| All secrets (database URLs, JWT signing keys, third-party API keys) are injected via environment variables—never checked into source control. | ||
| - **.env exclusions** | ||
| The repository’s `.gitignore` excludes any local `.env` or secret files. | ||
|
|
||
| ## 5. Dependency Management | ||
| - **Regular audits** | ||
| - Frontend: `npm audit` (or `yarn audit`) run on each CI build. | ||
| - Backend: `pip-audit` (or `safety`) scans Python dependencies for known vulnerabilities. | ||
| - **Pinned versions** | ||
| `package.json` and `requirements.txt` use exact version pins to ensure reproducible installs. | ||
|
|
||
| ## 6. Input Validation & Output Encoding | ||
| - **Schema validation** | ||
| Backend request bodies are validated against JSON schemas via `flask_json_schema`. | ||
| - **ORM usage** | ||
| All database access uses SQLAlchemy with parameterized queries to prevent SQL injection. | ||
| - **Escape output** | ||
| Frontend templates escape any user-provided content to avoid XSS. | ||
|
|
||
| ## 7. Content Security Policy (CSP) | ||
| - The frontend sets a strict CSP header to disallow inline scripts and only allow trusted script sources. | ||
|
|
||
| ## 8. Logging & Monitoring | ||
| - **Audit logs** | ||
| Security-related events (login, token validation failures, analytics submissions) are logged centrally. | ||
| - **Error handling** | ||
| Stack traces and internal errors are never exposed to end users; they are captured in server logs only. | ||
|
|
||
| ## 9. Database Migrations | ||
| - **Alembic migrations** | ||
| Schema changes are tracked and applied via Alembic; no manual DDL in production. | ||
|
|
||
| --- | ||
|
|
||
| > For any security concerns, please contact the DHEP Lab’s security team at `[email protected]`. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,52 @@ | ||
| from flask import Blueprint, request, jsonify | ||
| from src import db | ||
| from src.analytics.service.analytics_service import AnalyticsService | ||
| from src.analytics.repository.analytics_repository import AnalyticsRepository | ||
| from src.user.repository.display_config_repository import DisplayConfigRepository | ||
| from src.common.model.ApiResponse import ApiResponse | ||
| from src.user.utils.auth_utils import jwt_validation_required | ||
| from src.common.exception.BusinessException import BusinessException, BusinessExceptionEnum | ||
| from datetime import datetime, timezone | ||
|
|
||
| # Give the blueprint its full prefix; no strict_slashes here | ||
| analytics_blueprint = Blueprint( | ||
| "analytics", | ||
| __name__, | ||
| url_prefix="/api/analytics", | ||
| ) | ||
|
|
||
| @analytics_blueprint.route("/", methods=["POST"], strict_slashes=False) | ||
| @jwt_validation_required() | ||
| def record(): # pragma: no cover | ||
| payload = request.get_json() or {} | ||
| case_config_id = payload.get("caseConfigId") | ||
| case_open_str = payload.get("caseOpenTime") | ||
| answer_open_str = payload.get("answerOpenTime") | ||
| answer_submit_str = payload.get("answerSubmitTime") | ||
|
|
||
| if not all([case_config_id, case_open_str, answer_open_str, answer_submit_str]): | ||
| ex = BusinessException( | ||
| BusinessExceptionEnum.RenderTemplateError, | ||
hoangsonww marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| "Missing analytics metrics fields" | ||
| ) | ||
| return jsonify(ApiResponse.error(ex)), 400 | ||
|
|
||
| fmt = "%Y-%m-%dT%H:%M:%S.%fZ" | ||
| try: | ||
| case_open = datetime.strptime(case_open_str, fmt).replace(tzinfo=timezone.utc) | ||
| answer_open = datetime.strptime(answer_open_str, fmt).replace(tzinfo=timezone.utc) | ||
| answer_submit = datetime.strptime(answer_submit_str, fmt).replace(tzinfo=timezone.utc) | ||
| except ValueError: | ||
| ex = BusinessException( | ||
| BusinessExceptionEnum.RenderTemplateError, | ||
| "Bad timestamp format for analytics" | ||
| ) | ||
| return jsonify(ApiResponse.error(ex)), 400 | ||
|
|
||
| analytics = AnalyticsService( | ||
| analytics_repository=AnalyticsRepository(db.session), | ||
| display_config_repository=DisplayConfigRepository(db.session), | ||
| ).record_metrics(case_config_id, case_open, answer_open, answer_submit) | ||
|
|
||
| db.session.commit() | ||
| return jsonify(ApiResponse.success({"id": analytics.id})), 200 | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,35 @@ | ||
| from datetime import datetime, timezone | ||
| from sqlalchemy import Column, Integer, String, DateTime, Float | ||
| from src import db | ||
|
|
||
| class Analytics(db.Model): | ||
| __tablename__ = "analytics" | ||
|
|
||
| id = Column(Integer, primary_key=True, autoincrement=True) | ||
| user_email = Column(String(128), nullable=False) | ||
| case_config_id = Column(String, nullable=False) | ||
hoangsonww marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| case_id = Column(Integer, nullable=False) | ||
|
|
||
| # these three fields will also accept and store tz-aware UTC datetimes | ||
| case_open_time = Column(DateTime(timezone=True), nullable=False) | ||
| answer_open_time = Column(DateTime(timezone=True), nullable=False) | ||
| answer_submit_time= Column(DateTime(timezone=True), nullable=False) | ||
|
|
||
| to_answer_open_secs = Column(Float, nullable=False) | ||
| to_submit_secs = Column(Float, nullable=False) | ||
| total_duration_secs = Column(Float, nullable=False) | ||
|
|
||
| created_timestamp = Column( | ||
| DateTime(timezone=True), | ||
| default=lambda: datetime.now(timezone.utc) | ||
| ) | ||
| modified_timestamp = Column( | ||
| DateTime(timezone=True), | ||
| default=lambda: datetime.now(timezone.utc), | ||
| onupdate=lambda: datetime.now(timezone.utc) | ||
| ) | ||
|
|
||
| __table_args__ = ( | ||
| # ensure only one analytics row per case_config_id per user | ||
| db.UniqueConstraint("user_email", "case_config_id"), | ||
hoangsonww marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| ) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,10 @@ | ||
| from src.analytics.model.analytics import Analytics | ||
|
|
||
| class AnalyticsRepository: | ||
| def __init__(self, session): # pragma: no cover | ||
| self.session = session | ||
|
|
||
| def add(self, analytics: Analytics) -> Analytics: # pragma: no cover | ||
| self.session.add(analytics) | ||
| self.session.flush() | ||
| return analytics |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,42 @@ | ||
| from datetime import datetime | ||
| from src.analytics.model.analytics import Analytics | ||
| from src.analytics.repository.analytics_repository import AnalyticsRepository | ||
| from src.common.exception.BusinessException import BusinessException, BusinessExceptionEnum | ||
| from src.user.utils.auth_utils import get_user_email_from_jwt | ||
| from src.user.repository.display_config_repository import DisplayConfigRepository | ||
|
|
||
| class AnalyticsService: | ||
| def __init__( | ||
| self, | ||
| analytics_repository: AnalyticsRepository, | ||
| display_config_repository: DisplayConfigRepository, | ||
| ): # pragma: no cover | ||
| self.analytics_repo = analytics_repository | ||
| self.config_repo = display_config_repository | ||
|
|
||
| def record_metrics(self, case_config_id: str, case_open: datetime, | ||
| answer_open: datetime, answer_submit: datetime) -> Analytics: # pragma: no cover | ||
|
|
||
| # verify user owns this case_config | ||
| config = self.config_repo.get_configuration_by_id(case_config_id) | ||
| user_email = get_user_email_from_jwt() | ||
| if not config or config.user_email != user_email: | ||
| raise BusinessException(BusinessExceptionEnum.NoAccessToCaseReview) | ||
|
|
||
| # durations in seconds | ||
| to_answer_open = (answer_open - case_open).total_seconds() | ||
| to_submit = (answer_submit - answer_open).total_seconds() | ||
| total = (answer_submit - case_open).total_seconds() | ||
|
|
||
| analytics = Analytics( | ||
| user_email=user_email, | ||
| case_config_id=case_config_id, | ||
| case_id=config.case_id, | ||
| case_open_time=case_open, | ||
| answer_open_time=answer_open, | ||
| answer_submit_time=answer_submit, | ||
| to_answer_open_secs=to_answer_open, | ||
| to_submit_secs=to_submit, | ||
| total_duration_secs=total, | ||
| ) | ||
| return self.analytics_repo.add(analytics) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
47 changes: 47 additions & 0 deletions
47
src/migrations/versions/cc1f971840fc_create_analytics_table.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,47 @@ | ||
| """create analytics table | ||
| Revision ID: cc1f971840fc | ||
| Revises: 02d25e5adcad | ||
| Create Date: 2025-06-13 16:17:19.503474 | ||
| """ | ||
| from alembic import op | ||
| import sqlalchemy as sa | ||
|
|
||
| # revision identifiers, used by Alembic. | ||
| revision = 'cc1f971840fc' | ||
| down_revision = '02d25e5adcad' | ||
| branch_labels = None | ||
| depends_on = None | ||
|
|
||
| def upgrade(): | ||
| op.create_table( | ||
| 'analytics', | ||
| sa.Column('id', sa.Integer, primary_key=True, autoincrement=True), | ||
| sa.Column('user_email', sa.String(128), nullable=False), | ||
| sa.Column('case_config_id', sa.String, nullable=False), | ||
| sa.Column('case_id', sa.Integer, nullable=False), | ||
| sa.Column('case_open_time', sa.DateTime(timezone=True), nullable=False), | ||
| sa.Column('answer_open_time', sa.DateTime(timezone=True), nullable=False), | ||
| sa.Column('answer_submit_time', sa.DateTime(timezone=True), nullable=False), | ||
| sa.Column('to_answer_open_secs', sa.Float, nullable=False), | ||
| sa.Column('to_submit_secs', sa.Float, nullable=False), | ||
| sa.Column('total_duration_secs', sa.Float, nullable=False), | ||
| sa.Column( | ||
| 'created_timestamp', | ||
| sa.DateTime(timezone=True), | ||
| nullable=False, | ||
| server_default=sa.text('CURRENT_TIMESTAMP') | ||
| ), | ||
| sa.Column( | ||
| 'modified_timestamp', | ||
| sa.DateTime(timezone=True), | ||
| nullable=False, | ||
| server_default=sa.text('CURRENT_TIMESTAMP') | ||
hoangsonww marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| ), | ||
| sa.UniqueConstraint('user_email', 'case_config_id', name='uq_analytics_user_case') | ||
hoangsonww marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| ) | ||
|
|
||
|
|
||
| def downgrade(): | ||
| op.drop_table('analytics') | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.