manoelhc / test-actions

Test actions
MIT License
1 stars 2 forks source link

chore(auth): Implement authentication system with login and password reset #134

Open manoelhc opened 1 month ago

manoelhc commented 1 month ago

Description


Changes walkthrough πŸ“

Relevant files
Enhancement
6 files
app.py
Integrate authentication router into the application         

src/app.py - Added `auth` router to the FastAPI application.
+2/-1     
auth.py
Add password management utilities                                               

src/helpers/auth.py - Implemented password hashing and token generation functions.
+27/-0   
jwt.py
Implement JWT token handling                                                         

src/helpers/jwt.py - Added functions to encode and decode JWT tokens.
+10/-0   
auth.py
Define authentication model and validation                             

src/models/auth.py
  • Created Auth model for user authentication.
  • Added password validation logic.
  • +64/-0   
    auth.py
    Add authentication endpoints                                                         

    src/routers/auth.py - Implemented `/auth/login` and `/auth/password` endpoints.
    +105/-0 
    user.py
    Enhance user creation with authentication                               

    src/routers/user.py - Updated user creation to include authentication logic.
    +40/-5   
    Configuration changes
    2 files
    config.py
    Update configuration for authentication                                   

    src/config.py
  • Added PASSWORD_SALT and TEST_USERNAME, TEST_USEREMAIL environment
    variables.
  • +3/-1     
    .env.local
    Correct database URL in environment configuration               

    .env.local - Fixed `DATABASE_URL` variable.
    +1/-1     
    Tests
    2 files
    test_auth.py
    Implement tests for authentication features                           

    src/test/test_auth.py - Added tests for authentication endpoints.
    +199/-0 
    test_users.py
    Enhance user tests with email checks                                         

    src/test/test_users.py - Updated user tests to include email validation.
    +149/-25

    Summary by Sourcery

    Implement user login and password reset functionalities, enhance user creation with email validation, and update Docker run commands. Add corresponding tests for new features and enhance existing user tests.

    New Features:

    Enhancements:

    Build:

    Tests:

    Summary by CodeRabbit

    sourcery-ai[bot] commented 1 month ago

    Reviewer's Guide by Sourcery

    This pull request introduces a new feature for user login with username and password. It includes significant changes to the user model to add email validation, updates to existing tests, and the addition of new tests for authentication. New routers and helper functions for handling authentication and JWT tokens are also included.

    File-Level Changes

    Files Changes
    src/test/test_users.py
    src/test/test_auth.py
    Updated user tests to include email validation and added new tests for authentication.
    src/routers/user.py
    src/routers/auth.py
    Updated user router to handle email and added new auth router for login and password reset.
    src/models/user.py
    src/models/auth.py
    Updated user model to include email and added new auth model for authentication.
    src/helpers/auth.py
    src/helpers/user.py
    src/helpers/jwt.py
    Added helper functions for authentication, user validation, and JWT token handling.

    Tips - Trigger a new Sourcery review by commenting `@sourcery-ai review` on the pull request. - Continue your discussion with Sourcery by replying directly to review comments. - You can change your review settings at any time by accessing your [dashboard](https://app.sourcery.ai): - Enable or disable the Sourcery-generated pull request summary or reviewer's guide; - Change the review language; - You can always [contact us](mailto:support@sourcery.ai) if you have any questions or feedback.
    coderabbitai[bot] commented 1 month ago

    Walkthrough

    The recent changes enhance the FastAPI application by improving database connectivity, authentication features, and user management processes. Notable modifications include the addition of email validation, robust password handling mechanisms, and refined user creation logic. Several new helper functions and models support these features, alongside updates to existing environment configurations and testing frameworks. Overall, these updates contribute to a more secure and flexible application architecture.

    Changes

    Files Change Summary
    .env.local Renamed DATABASE_UR to DATABASE_URL and updated its value for file-based SQLite database.
    .github/workflows/.../snorkell-auto-documentation.yml Minor formatting changes to branch_name parameter.
    .whitesource Added a newline at the end of the file for coding standards.
    Dockerfile Reordered COPY commands and added a new COPY for manocorp package.
    justfile Updated environment variables and volume mappings for improved configuration.
    requirements-dev.txt Reordered dependencies, moving pytest-asyncio above pytest.
    requirements.txt Added blake3==0.4.1 and email-validator==2.2.0 dependencies.
    src/app.py Added import for auth router, expanding API's routing capabilities.
    src/config.py Introduced new environment variables for authentication and testing.
    src/helpers/auth.py New file for password management functions including hashing and token generation.
    src/helpers/jwt.py New file for JWT encoding and decoding functionalities.
    src/helpers/user.py New file for user validation functions including username and email checks.
    src/migrations/__init__.py Enhanced seed_db function to dynamically create users and link with authentication records.
    src/models/auth.py Introduced several authentication-related models using SQLModel.
    src/models/user.py Updated UserCreate and User classes to include email validation and improved username handling.
    src/routers/auth.py New endpoints for password resets and user login, enhancing authentication features.
    src/routers/user.py Modified create_user function to improve user creation flow and link with authentication.
    src/test/test_auth.py Comprehensive tests for authentication flow, covering password resets and logins.
    src/test/test_users.py Updated user creation tests to include email validation and expanded checks for invalid usernames.

    Sequence Diagram(s)

    sequenceDiagram
        participant User
        participant AuthService
        participant Database
    
        User->>AuthService: Request login
        AuthService->>Database: Verify credentials
        Database-->>AuthService: Return user data
        AuthService-->>User: Return JWT token
    sequenceDiagram
        participant User
        participant AuthService
        participant Database
    
        User->>AuthService: Request password reset
        AuthService->>Database: Verify user and token
        Database-->>AuthService: Confirmation of user
        AuthService-->>User: Confirm password reset

    Tips ### Chat There are 3 ways to chat with [CodeRabbit](https://coderabbit.ai): - Review comments: Directly reply to a review comment made by CodeRabbit. Example: - `I pushed a fix in commit .` - `Generate unit testing code for this file.` - `Open a follow-up GitHub issue for this discussion.` - Files and specific lines of code (under the "Files changed" tab): Tag `@coderabbitai` in a new review comment at the desired location with your query. Examples: - `@coderabbitai generate unit testing code for this file.` - `@coderabbitai modularize this function.` - PR comments: Tag `@coderabbitai` in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples: - `@coderabbitai generate interesting stats about this repository and render them as a table.` - `@coderabbitai show all the console.log statements in this repository.` - `@coderabbitai read src/utils.ts and generate unit testing code.` - `@coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.` - `@coderabbitai help me debug CodeRabbit configuration file.` Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. ### CodeRabbit Commands (invoked as PR comments) - `@coderabbitai pause` to pause the reviews on a PR. - `@coderabbitai resume` to resume the paused reviews. - `@coderabbitai review` to trigger an incremental review. This is useful when automatic reviews are disabled for the repository. - `@coderabbitai full review` to do a full review from scratch and review all the files again. - `@coderabbitai summary` to regenerate the summary of the PR. - `@coderabbitai resolve` resolve all the CodeRabbit review comments. - `@coderabbitai configuration` to show the current CodeRabbit configuration for the repository. - `@coderabbitai help` to get help. Additionally, you can add `@coderabbitai ignore` anywhere in the PR description to prevent this PR from being reviewed. ### CodeRabbit Configuration File (`.coderabbit.yaml`) - You can programmatically configure CodeRabbit by adding a `.coderabbit.yaml` file to the root of your repository. - Please see the [configuration documentation](https://docs.coderabbit.ai/guides/configure-coderabbit) for more information. - If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: `# yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json` ### Documentation and Community - Visit our [Documentation](https://coderabbit.ai/docs) for detailed information on how to use CodeRabbit. - Join our [Discord Community](https://discord.com/invite/GsXnASn26c) to get help, request features, and share feedback. - Follow us on [X/Twitter](https://twitter.com/coderabbitai) for updates and announcements.
    github-actions[bot] commented 1 month ago

    Tag v0.38.0-pr134 (branch: HEAD, SHA: 056ae28) Added.

    penify-dev[bot] commented 1 month ago

    PR Review πŸ”

    ⏱️ Estimated effort to review [1-5] 4, because the PR introduces a significant amount of new functionality, including authentication, password management, and JWT handling, which requires careful review of both the implementation and the associated tests.
    πŸ§ͺ Relevant tests Yes
    ⚑ Possible issues Possible Bug: The password reset functionality should ensure that the reset token is unique and securely generated to prevent unauthorized access.
    Possible Bug: The password hashing function should be reviewed to ensure it meets security standards and is resistant to attacks.
    πŸ”’ Security concerns - Sensitive information exposure: Ensure that sensitive information such as passwords and tokens are not logged or exposed in error messages.
    penify-dev[bot] commented 1 month ago

    PR Code Suggestions ✨

    CategorySuggestion                                                                                                                                    Score
    Testing
    Expand the invalid username tests to cover more edge cases ___ **Ensure that the test cases for invalid usernames and emails cover all edge cases to
    improve robustness.** [src/test/test_users.py [60-82]](https://github.com/manoelhc/test-actions/pull/134/files#diff-697871d06d13be1b42d4b3c9a6e51cb9fc0c9098fc0b632f33585ba6ca28887bR60-R82) ```diff -response = client.post( - "/user", - json={"username": "t", "email": config.TEST_USEREMAIL}, -) -assert response.status_code == 422 +for username in ["t", "ttt&", "ttt,asd", "ttt-test", "tt*"]: + response = client.post( + "/user", + json={"username": username, "email": config.TEST_USEREMAIL}, + ) + assert response.status_code == 422 ```
    Suggestion importance[1-10]: 9 Why: Expanding the test cases for invalid usernames and emails is crucial for ensuring the robustness of the application, making this a significant improvement.
    9
    Performance
    Refactor user creation tests to reduce redundancy ___ **Consider using a loop or a helper function to reduce code duplication when creating
    multiple users in tests.** [src/test/test_users.py [153-168]](https://github.com/manoelhc/test-actions/pull/134/files#diff-697871d06d13be1b42d4b3c9a6e51cb9fc0c9098fc0b632f33585ba6ca28887bR153-R168) ```diff -response = client.post( - "/user", - json={"username": "test_duplicate_user", "email": "test.duplicate.user.first@gmail.com"}, -) -assert response.status_code == 200 -response = client.post( - "/user", - json={"username": "test_duplicate_user", "email": "test.duplicate.user.second@gmail.com"}, -) +for i in range(2): + response = client.post( + "/user", + json={"username": "test_duplicate_user", "email": f"test.duplicate.user.{i+1}@gmail.com"}, + ) + assert response.status_code == (200 if i == 0 else 400) ```
    Suggestion importance[1-10]: 8 Why: This suggestion effectively addresses code duplication, which is important for maintainability and readability, making it a valuable improvement.
    8
    Security
    Use a different method to generate the password to ensure security ___ **The password and reset_token fields in the Auth instance should be generated securely and
    not reused for both fields.** [src/routers/user.py [76-77]](https://github.com/manoelhc/test-actions/pull/134/files#diff-838fdfe65292cfb0194482f911a9d79a5717cc137be8fa29511c2f46db33ea9dR76-R77) ```diff reset_token=auth.get_password_token(), -password=auth.get_password_token(), +password=auth.password_generator(), ```
    Suggestion importance[1-10]: 8 Why: This suggestion addresses a security concern by recommending different methods for generating the `password` and `reset_token`, which is crucial for maintaining secure authentication practices.
    8
    Maintainability
    Modify the username in the test to ensure uniqueness ___ **Ensure that the username used in the test case is unique to avoid potential conflicts with
    existing users in the database.** [src/test/test_users.py [42]](https://github.com/manoelhc/test-actions/pull/134/files#diff-697871d06d13be1b42d4b3c9a6e51cb9fc0c9098fc0b632f33585ba6ca28887bR42-R42) ```diff -json={"username": "T3sT_create_user", "email": "manoelhc@gmail.com"}, +json={"username": "unique_T3sT_create_user", "email": "manoelhc@gmail.com"}, ```
    Suggestion importance[1-10]: 7 Why: While ensuring unique usernames is a good practice, the suggestion does not address a critical issue in the code and is more of a style improvement.
    7
    Eliminate commented-out code to enhance code readability ___ **Remove commented-out code to improve code clarity and maintainability.** [src/test/test_users.py [18]](https://github.com/manoelhc/test-actions/pull/134/files#diff-697871d06d13be1b42d4b3c9a6e51cb9fc0c9098fc0b632f33585ba6ca28887bR18-R18) ```diff -# seed_db() +# (remove this line) ```
    Suggestion importance[1-10]: 6 Why: Removing commented-out code can enhance readability, but this suggestion does not address any functional issues in the code.
    6
    Modify the validate_user function to return a boolean for better clarity on validation results ___ **The validate_user function should return a boolean indicating the validity of the username
    instead of returning the username itself.** [src/helpers/user.py [15]](https://github.com/manoelhc/test-actions/pull/134/files#diff-bbcd4294c1d78354348b46b260f840c043ddcbe771773b0e82deca160cd86248R15-R15) ```diff -return username +return True ```
    Suggestion importance[1-10]: 4 Why: While the suggestion aims to improve clarity, the current implementation is designed to return the validated username, which is useful for further processing. Changing it to return a boolean may reduce its utility.
    4
    Best practice
    Change the default datetime to use UTC to prevent timezone-related issues ___ **The created_at and updated_at fields should use datetime.utcnow() instead of
    datetime.now() to avoid timezone issues.** [src/models/auth.py [24-25]](https://github.com/manoelhc/test-actions/pull/134/files#diff-a40b54e0c1cd083a4e232c0850019984b534f46abb9f26773595149e610b9b49R24-R25) ```diff -created_at: datetime = Field(default=datetime.now()) -updated_at: datetime | None = Field(default=datetime.now(), nullable=True) +created_at: datetime = Field(default=datetime.utcnow()) +updated_at: datetime | None = Field(default=datetime.utcnow(), nullable=True) ```
    Suggestion importance[1-10]: 7 Why: This suggestion improves best practices by recommending the use of UTC for timestamps, which is important for avoiding timezone-related issues, although it is not a critical bug.
    7
    Possible bug
    Validate the new_user variable before using it to create a User instance ___ **Ensure that the new_user variable is validated before being used to create a User instance
    to avoid potential runtime errors.** [src/routers/user.py [47]](https://github.com/manoelhc/test-actions/pull/134/files#diff-838fdfe65292cfb0194482f911a9d79a5717cc137be8fa29511c2f46db33ea9dR47-R47) ```diff -new_user = UserCreate.model_validate(new_user) +new_user = UserCreate.model_validate(new_user) if new_user else raise ValueError("Invalid user data") ```
    Suggestion importance[1-10]: 3 Why: The suggestion to validate `new_user` is relevant, but the proposed change is incorrect as it uses `raise` in a conditional expression, which is not valid syntax in Python.
    3
    deepsource-io[bot] commented 1 month ago

    Here's the code health analysis summary for commits 01f42a8..923cde5. View details on DeepSource β†—.

    Analysis Summary

    AnalyzerStatusSummaryLink
    DeepSource Python LogoPython❌ Failure
    ❗ 37 occurences introduced
    View Check β†—
    DeepSource Test coverage LogoTest coverage⚠️ Artifact not reportedTimed out: Artifact was never reportedView Check β†—

    πŸ’‘ If you’re a repository administrator, you can configure the quality gates from the settings.
    github-actions[bot] commented 1 month ago

    Qodana Community for Python

    38 new problems were found

    Inspection name Severity Problems
    Unsatisfied package requirements πŸ”Ά Warning 7
    Unsatisfied package requirements ◽️ Notice 23
    PEP 8 coding style violation ◽️ Notice 4
    Problematic nesting of decorators ◽️ Notice 2
    Using equality operators to compare with None ◽️ Notice 1
    Unused local symbols ◽️ Notice 1

    πŸ’‘ Qodana analysis was run in the pull request mode: only the changed files were checked ☁️ View the detailed Qodana report

    Contact Qodana team Contact us at [qodana-support@jetbrains.com](mailto:qodana-support@jetbrains.com) - Or via our issue tracker: https://jb.gg/qodana-issue - Or share your feedback: https://jb.gg/qodana-discussions
    socket-security[bot] commented 1 month ago

    New dependencies detected. Learn more about Socket for GitHub β†—οΈŽ

    Package New capabilities Transitives Size Publisher
    pypi/blake3@0.4.1 None 0 5.24 MB oconnor663
    pypi/email-validator@2.2.0 environment, eval, filesystem 0 205 kB Joshua.Tauberer

    View full reportβ†—οΈŽ