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

Add Authentication API #616

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open

Add Authentication API #616

wants to merge 5 commits into from

Conversation

cmdumar
Copy link

@cmdumar cmdumar commented Jan 24, 2025

This PR introduces authentication to the application using the Devise gem and JWT for token-based authentication. The changes include adding necessary gems, setting up Devise, creating authentication endpoints, and modifying controllers and routes.

Authentication Setup

  • Added devise and jwt gems to the Gemfile.
  • Created a new Api::AuthenticationController to handle user login and JWT generation.
  • Updated ApplicationController to use :null_session for CSRF protection when the request header contains a specific token.
  • Added Devise configuration in config/initializers/devise.rb.
  • Added Devise translations in config/locales/devise.en.yml.

User Model and Migration

  • Updated User model to include Devise modules and a method to generate JWT tokens.
  • Created a migration to add Devise fields to the users table.
  • Updated db/schema.rb to reflect the new migration.

Routes

  • Updated routes.rb to include Devise routes and an API endpoint for login.

This change is Reviewable

Summary by CodeRabbit

Release Notes

  • New Features

    • Added user authentication system with login and signup functionality.
    • Implemented JWT-based authentication for secure user sessions.
  • Security Improvements

    • Enhanced CSRF protection with null session handling.
    • Added robust user authentication and account management features.
  • Infrastructure

    • Integrated Devise gem for comprehensive user management.
    • Added routes for user authentication and API login.
  • Localization

    • Added English translations for authentication-related messages.

Copy link

coderabbitai bot commented Jan 24, 2025

Walkthrough

This pull request introduces a user authentication system utilizing the Devise and JWT gems. It includes the addition of new gem dependencies, the creation of an authentication controller for user login and signup, configuration of Devise, establishment of a user model with associated database migrations, and routing setup for user authentication endpoints. The changes facilitate user registration, login, and session management through JWT token generation.

Changes

File Change Summary
Gemfile Added devise and jwt gem dependencies
app/controllers/api/authentication_controller.rb New controller for handling user authentication with JWT token generation
app/controllers/application_controller.rb Updated CSRF protection to use :null_session
app/models/user.rb New User model with Devise authentication and JWT token generation method
config/initializers/devise.rb Comprehensive Devise configuration setup
config/locales/devise.en.yml Added English translations for Devise authentication messages
config/routes.rb Added Devise routes and API login endpoint
db/migrate/20250124081805_devise_create_users.rb Migration for creating users table with Devise fields
db/schema.rb Updated schema with new users table
test/factories/users.rb Added empty user factory for testing
test/models/user_test.rb Created basic user model test class

Possibly related PRs

  • Fix/no commit hash on the deployed project #611: This PR is unrelated to the main PR as it focuses on Dockerfile modifications for tracking commit hashes, which does not connect to the user authentication changes introduced in the main PR.

Poem

🐰 In the garden of code, new gems bloom,
Devise and JWT, dispelling the gloom.
Users can sign up, and log in with ease,
Tokens in hand, like a warm summer breeze.
With every new feature, our system grows bright,
A rabbit's delight, in the code's gentle light! 🌟


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4be8a55 and 8c8b1a6.

📒 Files selected for processing (7)
  • Gemfile (1 hunks)
  • app/controllers/api/authentication_controller.rb (1 hunks)
  • app/models/user.rb (1 hunks)
  • config/initializers/devise.rb (1 hunks)
  • config/routes.rb (1 hunks)
  • test/factories/users.rb (1 hunks)
  • test/models/user_test.rb (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (7)
  • app/models/user.rb
  • test/models/user_test.rb
  • config/routes.rb
  • Gemfile
  • config/initializers/devise.rb
  • test/factories/users.rb
  • app/controllers/api/authentication_controller.rb

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • 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 gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @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 using 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 generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

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 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 for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

Hi 👋 To deploy a review app, please comment /deploy-review-app

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Nitpick comments (7)
app/models/user.rb (1)

1-1: Add frozen string literal comment for consistency.
Rubocop flags missing # frozen_string_literal: true. Aligning with this convention will help reduce string object allocations and maintain consistency.

+# frozen_string_literal: true
 class User < ApplicationRecord
🧰 Tools
🪛 rubocop (1.69.1)

[convention] 1-1: Missing frozen string literal comment.

(Style/FrozenStringLiteralComment)

🪛 GitHub Actions: Lint CI

[warning] 1-10: Missing frozen string literal comment and multiple trailing whitespace issues.

app/controllers/api/authentication_controller.rb (1)

1-1: Refine class definition style and file-level comment.
Rubocop suggests a nested class definition instead of the compact form and adding # frozen_string_literal: true. These are style conventions, but adopting them can improve code consistency.

+# frozen_string_literal: true
-module Api
-  class AuthenticationController < ApplicationController
-    ...
-  end
+class Api::AuthenticationController < ApplicationController
   ...
 end
🧰 Tools
🪛 rubocop (1.69.1)

[convention] 1-1: Missing frozen string literal comment.

(Style/FrozenStringLiteralComment)


[convention] 1-1: Use nested module/class definitions instead of compact style.

(Style/ClassAndModuleChildren)

🪛 GitHub Actions: Lint CI

[warning] 1-1: Missing frozen string literal comment and incorrect module/class definition style.

config/routes.rb (1)

12-14: Adopt consistent string quoting style.
Rubocop suggests using double quotes for strings like "login". This is a minor style preference, but consistency can make your codebase more uniform and reduce lint warnings.

 namespace :api do
-  post 'login', to: 'authentication#create'
+  post "login", to: "authentication#create"
 end
🧰 Tools
🪛 rubocop (1.69.1)

[convention] 13-13: Prefer double-quoted strings unless you need single quotes to avoid extra backslashes for escaping.

(Style/StringLiterals)


[convention] 13-13: Prefer double-quoted strings unless you need single quotes to avoid extra backslashes for escaping.

(Style/StringLiterals)

db/migrate/20250124081805_devise_create_users.rb (2)

35-36: Remove the extra blank line.

A blank line is detected at lines 35-36. Consider removing it to comply with RuboCop's layout convention and maintain a cleaner migration file.

35-
36-
🧰 Tools
🪛 rubocop (1.69.1)

[convention] 35-36: Extra blank line detected.

(Layout/EmptyLines)


18-23: Consider removing or uncommenting the unused Devise features.

The commented-out sections for Trackable, Confirmable, and Lockable can create confusion if they aren’t intended for future use. Removing them or explicitly enabling them helps keep migrations concise.

Also applies to: 24-33

config/initializers/devise.rb (1)

129-129: Remove or wrap pepper value to avoid unnecessary exposure and fix line length.

The commented pepper value is overly long and may create a false impression of a real secret. If unused, remove it; otherwise, store it securely in an environment variable.

-  # config.pepper = '8f277f0b4e8090a67c44746c589cd5edfaab345bf9a650db74a63b38cc431b1710fcf704021b401c88db3bcd98e29a71b4eecf62bec170b138442818a3d33013'
+  # config.pepper = ENV.fetch("DEVISE_PEPPER", "placeholder_value")
🧰 Tools
🪛 rubocop (1.69.1)

[convention] 129-129: Line is too long. [150/120]

(Layout/LineLength)

🪛 GitHub Actions: Lint CI

[error] 129-129: Line is too long. [150/120]

Gemfile (1)

61-61: Use double-quoted strings to comply with style guidelines.

Ruby style guidelines discourage single quotes unless needed for escaping. Use double quotes here.

- gem 'jwt'
+ gem "jwt"
🧰 Tools
🪛 rubocop (1.69.1)

[convention] 61-61: Prefer double-quoted strings unless you need single quotes to avoid extra backslashes for escaping.

(Style/StringLiterals)

🪛 GitHub Actions: Lint CI

[warning] 61-61: Style/StringLiterals: Prefer double-quoted strings unless you need single quotes to avoid extra backslashes for escaping.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 005eab7 and 8182ec4.

⛔ Files ignored due to path filters (1)
  • Gemfile.lock is excluded by !**/*.lock
📒 Files selected for processing (11)
  • Gemfile (1 hunks)
  • app/controllers/api/authentication_controller.rb (1 hunks)
  • app/controllers/application_controller.rb (1 hunks)
  • app/models/user.rb (1 hunks)
  • config/initializers/devise.rb (1 hunks)
  • config/locales/devise.en.yml (1 hunks)
  • config/routes.rb (1 hunks)
  • db/migrate/20250124081805_devise_create_users.rb (1 hunks)
  • db/schema.rb (2 hunks)
  • test/factories/users.rb (1 hunks)
  • test/models/user_test.rb (1 hunks)
🧰 Additional context used
🪛 rubocop (1.69.1)
app/models/user.rb

[convention] 1-1: Missing frozen string literal comment.

(Style/FrozenStringLiteralComment)


[convention] 7-7: Trailing whitespace detected.

(Layout/TrailingWhitespace)


[convention] 8-8: Trailing whitespace detected.

(Layout/TrailingWhitespace)


[convention] 9-9: Trailing whitespace detected.

(Layout/TrailingWhitespace)


[convention] 10-10: Trailing whitespace detected.

(Layout/TrailingWhitespace)

Gemfile

[convention] 61-61: Prefer double-quoted strings unless you need single quotes to avoid extra backslashes for escaping.

(Style/StringLiterals)

config/routes.rb

[convention] 13-13: Prefer double-quoted strings unless you need single quotes to avoid extra backslashes for escaping.

(Style/StringLiterals)


[convention] 13-13: Prefer double-quoted strings unless you need single quotes to avoid extra backslashes for escaping.

(Style/StringLiterals)

db/migrate/20250124081805_devise_create_users.rb

[convention] 35-36: Extra blank line detected.

(Layout/EmptyLines)

app/controllers/api/authentication_controller.rb

[convention] 1-1: Missing frozen string literal comment.

(Style/FrozenStringLiteralComment)


[convention] 1-1: Use nested module/class definitions instead of compact style.

(Style/ClassAndModuleChildren)


[convention] 4-4: Trailing whitespace detected.

(Layout/TrailingWhitespace)


[convention] 8-8: Trailing whitespace detected.

(Layout/TrailingWhitespace)


[convention] 9-9: Trailing whitespace detected.

(Layout/TrailingWhitespace)


[convention] 10-10: Prefer double-quoted strings unless you need single quotes to avoid extra backslashes for escaping.

(Style/StringLiterals)


[convention] 10-10: Trailing whitespace detected.

(Layout/TrailingWhitespace)


[convention] 11-11: Trailing whitespace detected.

(Layout/TrailingWhitespace)


[convention] 14-14: Prefer double-quoted strings unless you need single quotes to avoid extra backslashes for escaping.

(Style/StringLiterals)

db/schema.rb

[convention] 13-66: Block has too many lines. [45/25]

(Metrics/BlockLength)


[convention] 13-13: Use underscores(_) as thousands separator and separate every 3 digits with them.

(Style/NumericLiterals)

config/initializers/devise.rb

[convention] 17-17: Line is too long. [154/120]

(Layout/LineLength)


[convention] 27-27: Prefer double-quoted strings unless you need single quotes to avoid extra backslashes for escaping.

(Style/StringLiterals)


[convention] 39-39: Prefer double-quoted strings unless you need single quotes to avoid extra backslashes for escaping.

(Style/StringLiterals)


[convention] 129-129: Line is too long. [150/120]

(Layout/LineLength)

test/factories/users.rb

[convention] 1-1: Missing frozen string literal comment.

(Style/FrozenStringLiteralComment)


[convention] 3-3: Trailing whitespace detected.

(Layout/TrailingWhitespace)

test/models/user_test.rb

[convention] 1-1: Missing frozen string literal comment.

(Style/FrozenStringLiteralComment)

🪛 GitHub Actions: Lint CI
app/models/user.rb

[warning] 1-10: Missing frozen string literal comment and multiple trailing whitespace issues.

Gemfile

[warning] 61-61: Style/StringLiterals: Prefer double-quoted strings unless you need single quotes to avoid extra backslashes for escaping.

app/controllers/api/authentication_controller.rb

[warning] 1-1: Missing frozen string literal comment and incorrect module/class definition style.

config/initializers/devise.rb

[error] 17-17: Line is too long. [154/120]


[error] 129-129: Line is too long. [150/120]

test/factories/users.rb

[error] 2-2: Lint/EmptyBlock: Empty block detected.

🪛 Gitleaks (8.21.2)
config/initializers/devise.rb

17-17: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: test (22.x, 3.3.4)
🔇 Additional comments (6)
app/controllers/application_controller.rb (1)

6-6: Ensure API usage alignment with your security strategy.
Switching protect_from_forgery from :exception to :null_session is suitable for supporting API clients. However, confirm that this relaxation of CSRF protection doesn't inadvertently allow undesired requests. Consider isolating API logic in a separate controller or ensuring that your request validation remains secure.

app/models/user.rb (1)

5-13: Consider adding token revocation or expiration checks.
Currently, generate_jwt sets a token that expires in 60 days. If you plan to implement logout or token invalidation, you may need a token blacklist or an alternative mechanism to handle revocation. Also, watch out for trailing whitespace that Rubocop has flagged on lines 7–10.

 def generate_jwt
-  JWT.encode(
+  token = JWT.encode(
     {
       id: id,
       exp: 60.days.from_now.to_i
     },
     Rails.application.credentials.secret_key_base
   )
+  # e.g., store token in a session table or use a revocation list if needed.
+  token
 end
✅ Verification successful

Review comment is accurate - token revocation mechanism is missing
The codebase only implements JWT token generation with expiration but lacks any token revocation or invalidation mechanism. This means tokens remain valid for 60 days even after logout or if compromised. Consider implementing one of these approaches:

  • Add a token blacklist table to track revoked tokens
  • Use a shorter expiration time with refresh tokens
  • Implement a Redis-based token store for quick revocation checks
🏁 Scripts executed

The following scripts were executed for the analysis:

Error: No shell scripts found


Script:

#!/bin/bash
# Search for JWT-related code and token validation
echo "=== JWT Token Validation ==="
rg -l "JWT" --type ruby

echo -e "\n=== Token Validation/Verification ==="
rg "verify|validate.*token" --type ruby

echo -e "\n=== Session/Blacklist Tables ==="
fd "db/migrate" --type f | xargs rg "create_table.*session|create_table.*token|create_table.*blacklist"

echo -e "\n=== Token Revocation Logic ==="
rg "revoke|invalidate.*token" --type ruby

echo -e "\n=== Authentication Middleware/Concerns ==="
fd "(middleware|concern)" --type f --extension rb | xargs rg "JWT|token"

Length of output: 5075

🧰 Tools
🪛 rubocop (1.69.1)

[convention] 7-7: Trailing whitespace detected.

(Layout/TrailingWhitespace)


[convention] 8-8: Trailing whitespace detected.

(Layout/TrailingWhitespace)


[convention] 9-9: Trailing whitespace detected.

(Layout/TrailingWhitespace)


[convention] 10-10: Trailing whitespace detected.

(Layout/TrailingWhitespace)

app/controllers/api/authentication_controller.rb (1)

2-15: 🛠️ Refactor suggestion

Validate inputs and provide consistent error messages.
Currently, there's a single check for user&.valid_password?(params[:password]). Consider verifying that both params[:email] and params[:password] are present and well-formed, and ensure consistent error responses for missing/invalid fields. Also watch out for trailing whitespace.

 def create
+  unless params[:email].present? && params[:password].present?
+    return render json: { error: "Email or password missing" }, status: :bad_request
+  end

   user = User.find_by(email: params[:email])
   if user&.valid_password?(params[:password])
     token = user.generate_jwt
     render json: {
       message: "Login successful",
       token: token
     }, status: :ok
   else
     render json: { error: "Invalid credentials" }, status: :unauthorized
   end
 end
✅ Verification successful

Input validation suggestion is appropriate and should be implemented

The suggested changes follow Rails best practices and improve security by validating parameters before processing. The error response format is consistent with the existing implementation, and the HTTP status codes are appropriate for the different error scenarios.

🏁 Scripts executed

The following scripts were executed for the analysis:

Error: No shell scripts found


Script:

#!/bin/bash
# Search for authentication-related controllers and API base controllers
echo "=== Authentication Controllers ==="
fd "authentication|auth" --type f --extension rb app/controllers

echo -e "\n=== API Controllers ==="
fd "api" --type f --extension rb app/controllers

echo -e "\n=== Base Controller Content ==="
fd "application_controller|base_controller|api_controller" --type f --extension rb app/controllers --exec cat {}

echo -e "\n=== Input Validation Patterns ==="
rg "params\[:.+\]\.present\?" --type ruby app/controllers

Length of output: 967

🧰 Tools
🪛 rubocop (1.69.1)

[convention] 4-4: Trailing whitespace detected.

(Layout/TrailingWhitespace)


[convention] 8-8: Trailing whitespace detected.

(Layout/TrailingWhitespace)


[convention] 9-9: Trailing whitespace detected.

(Layout/TrailingWhitespace)


[convention] 10-10: Prefer double-quoted strings unless you need single quotes to avoid extra backslashes for escaping.

(Style/StringLiterals)


[convention] 10-10: Trailing whitespace detected.

(Layout/TrailingWhitespace)


[convention] 11-11: Trailing whitespace detected.

(Layout/TrailingWhitespace)


[convention] 14-14: Prefer double-quoted strings unless you need single quotes to avoid extra backslashes for escaping.

(Style/StringLiterals)

config/routes.rb (1)

4-4: Add Devise route constraints if needed.
devise_for :users is straightforward, but ensure it's scoped according to your application design (e.g., if you need separate API or admin routes).

db/schema.rb (1)

52-62: Schema updates look correct.

All changes match the Devise migration, and the indexes for email and reset_password_token are properly set as unique. No further changes needed.

config/locales/devise.en.yml (1)

1-65: LGTM! Comprehensive Devise translations setup.

The translations file includes all necessary keys and follows Devise's recommended structure. The messages are clear, user-friendly, and maintain security by not revealing sensitive information in error messages.

config/initializers/devise.rb Outdated Show resolved Hide resolved
Comment on lines 1 to 5
FactoryBot.define do
factory :user do

end
end
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add required attributes to the user factory.

The empty factory will cause test failures. Since this PR implements Devise authentication, the factory should include essential attributes.

Apply this diff to add the necessary attributes:

+# frozen_string_literal: true
+
 FactoryBot.define do
   factory :user do
-    
+    sequence(:email) { |n| "user#{n}@example.com" }
+    password { 'password123' }
+    password_confirmation { 'password123' }
+    confirmed_at { Time.current } # If using confirmable module
   end
 end
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
FactoryBot.define do
factory :user do
end
end
# frozen_string_literal: true
FactoryBot.define do
factory :user do
sequence(:email) { |n| "user#{n}@example.com" }
password { 'password123' }
password_confirmation { 'password123' }
confirmed_at { Time.current } # If using confirmable module
end
end
🧰 Tools
🪛 rubocop (1.69.1)

[convention] 1-1: Missing frozen string literal comment.

(Style/FrozenStringLiteralComment)


[convention] 3-3: Trailing whitespace detected.

(Layout/TrailingWhitespace)

🪛 GitHub Actions: Lint CI

[error] 2-2: Lint/EmptyBlock: Empty block detected.

Comment on lines +1 to +7
require "test_helper"

class UserTest < ActiveSupport::TestCase
# test "the truth" do
# assert true
# end
end
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Implement essential User model tests.

The test file only contains a placeholder. Since this PR implements authentication, we need comprehensive test coverage for the User model.

Apply this diff to add essential test cases:

+# frozen_string_literal: true
+
 require "test_helper"

 class UserTest < ActiveSupport::TestCase
-  # test "the truth" do
-  #   assert true
-  # end
+  test "should not save user without email" do
+    user = build(:user, email: nil)
+    assert_not user.save, "Saved user without email"
+  end
+
+  test "should not save user with invalid email format" do
+    user = build(:user, email: "invalid_email")
+    assert_not user.save, "Saved user with invalid email"
+  end
+
+  test "should not save user with duplicate email" do
+    create(:user, email: "[email protected]")
+    user = build(:user, email: "[email protected]")
+    assert_not user.save, "Saved user with duplicate email"
+  end
+
+  test "should not save user with password shorter than minimum length" do
+    user = build(:user, password: "short", password_confirmation: "short")
+    assert_not user.save, "Saved user with short password"
+  end
+
+  test "should save valid user" do
+    user = build(:user)
+    assert user.save, "Could not save valid user"
+  end
 end

Committable suggestion skipped: line range outside the PR's diff.

🧰 Tools
🪛 rubocop (1.69.1)

[convention] 1-1: Missing frozen string literal comment.

(Style/FrozenStringLiteralComment)

@cmdumar cmdumar requested a review from Judahmeek January 24, 2025 09:01
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Nitpick comments (3)
config/routes.rb (2)

12-15: Consider adding API versioning.

The API routes should be versioned to ensure backward compatibility and easier future updates. Consider nesting them under a version namespace.

 namespace :api do
+  namespace :v1 do
     post 'signup', to: 'authentication#signup'
     post 'login', to: 'authentication#create'
+  end
 end

12-15: Add rate limiting for authentication endpoints.

Authentication endpoints should be rate-limited to prevent brute force attacks and DoS attempts.

Consider using the rack-attack gem to implement rate limiting:

# config/initializers/rack_attack.rb
class Rack::Attack
  throttle('auth/ip', limit: 5, period: 60.seconds) do |req|
    req.ip if req.path.start_with?('/api/') && ['login', 'signup'].any? { |path| req.path.include?(path) }
  end
end
app/controllers/api/authentication_controller.rb (1)

36-38: Enhance parameter sanitization.

Consider adding additional permitted parameters that might be needed for user management.

   def user_params
-    params.require(:user).permit(:email, :password, :password_confirmation)
+    params.require(:user).permit(
+      :email, 
+      :password, 
+      :password_confirmation,
+      :first_name,
+      :last_name
+    ).transform_values(&:strip)
   end
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8182ec4 and c53d18d.

📒 Files selected for processing (2)
  • app/controllers/api/authentication_controller.rb (1 hunks)
  • config/routes.rb (1 hunks)
🧰 Additional context used
🪛 GitHub Actions: Lint CI
app/controllers/api/authentication_controller.rb

[error] 1-1: Missing frozen string literal comment and incorrect module/class definition style

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: test (22.x, 3.3.4)
🔇 Additional comments (1)
app/controllers/api/authentication_controller.rb (1)

1-39: Verify CSRF protection configuration.

Ensure CSRF protection is properly configured for API endpoints.

✅ Verification successful

CSRF protection is properly configured

The application uses protect_from_forgery with: :null_session which is the recommended configuration for API endpoints. This setup ensures proper CSRF protection while allowing API authentication to work correctly.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if CSRF protection is properly configured
rg -l "protect_from_forgery|null_session" app/controllers/

Length of output: 102


Script:

#!/bin/bash
# Check the content of ApplicationController
cat app/controllers/application_controller.rb

Length of output: 369

🧰 Tools
🪛 GitHub Actions: Lint CI

[error] 1-1: Missing frozen string literal comment and incorrect module/class definition style

app/controllers/api/authentication_controller.rb Outdated Show resolved Hide resolved
app/controllers/api/authentication_controller.rb Outdated Show resolved Hide resolved
app/controllers/api/authentication_controller.rb Outdated Show resolved Hide resolved
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (1)
app/controllers/api/authentication_controller.rb (1)

5-21: Enhance security with rate limiting and logging.

The login endpoint needs additional security measures:

  1. Implement rate limiting for failed login attempts
  2. Add logging for authentication failures
  3. Add request throttling to prevent brute force attacks

Consider using the rack-attack gem for request throttling:

# config/initializers/rack_attack.rb
class Rack::Attack
  throttle('login/ip', limit: 5, period: 60.seconds) do |req|
    req.ip if req.path == '/api/login' && req.post?
  end
end

And add logging for authentication failures:

       else
+        Rails.logger.warn("Failed login attempt for email: #{params[:email]} from IP: #{request.remote_ip}")
         render json: { error: 'Invalid credentials' }, status: :unauthorized
       end
🧰 Tools
🪛 GitHub Actions: Lint CI

[warning] 15-15: Useless assignment to variable 'e' in JWT::EncodeError rescue block.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c53d18d and 4be8a55.

📒 Files selected for processing (1)
  • app/controllers/api/authentication_controller.rb (1 hunks)
🧰 Additional context used
🪛 GitHub Actions: Lint CI
app/controllers/api/authentication_controller.rb

[warning] 15-15: Useless assignment to variable 'e' in JWT::EncodeError rescue block.


[warning] 39-39: Useless assignment to variable 'e' in JWT::EncodeError rescue block.

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: test (22.x, 3.3.4)
🔇 Additional comments (3)
app/controllers/api/authentication_controller.rb (3)

1-4: LGTM! Proper module structure implemented.

The code follows Ruby best practices with proper module nesting and includes the frozen string literal comment.


51-53: LGTM! Proper strong parameters implementation.

The code follows Rails best practices for parameter sanitization.


27-28: 🛠️ Refactor suggestion

Strengthen password requirements.

The current password length requirement of 6 characters is too weak. Consider:

  1. Increasing minimum length to 8 characters
  2. Adding complexity requirements (uppercase, lowercase, numbers, special chars)
-      return render json: { error: 'Password must be at least 6 characters' }, status: :unprocessable_entity if 
-      params.dig(:user, :password)&.length.to_i < 6
+      password = params.dig(:user, :password)
+      return render json: { 
+        error: 'Password must be at least 8 characters and include uppercase, lowercase, number and special character'
+      }, status: :unprocessable_entity unless password_meets_requirements?(password)

# Add this private method:
+    def password_meets_requirements?(password)
+      return false unless password&.length.to_i >= 8
+      return false unless password =~ /[A-Z]/  # uppercase
+      return false unless password =~ /[a-z]/  # lowercase
+      return false unless password =~ /[0-9]/  # number
+      return false unless password =~ /[^A-Za-z0-9]/ # special char
+      true
+    end

Likely invalid or redundant comment.

app/controllers/api/authentication_controller.rb Outdated Show resolved Hide resolved
app/controllers/api/authentication_controller.rb Outdated Show resolved Hide resolved
@cmdumar
Copy link
Author

cmdumar commented Jan 24, 2025

API Test Commands:

Sign up:

curl -X POST http://localhost:3000/api/signup \
     -H "Content-Type: application/json" \
     -d '{"user": {"email":"[email protected]", "password":"password123", "password_confirmation":"password123"}}'

Login:

curl -X POST http://localhost:3000/api/login \
     -H "Content-Type: application/json" \
     -d '{"email":"[email protected]", "password":"password123"}'

@Judahmeek
Copy link
Contributor

/deploy-review-app

Copy link

github-actions bot commented Jan 27, 2025

🏗️ Building Docker image...

📝 View Build Logs

🎮 Control Plane Console

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants