Skip to content

Backend User Authentication & Registration#133

Merged
driedpampas merged 45 commits intomainfrom
feature/auth-backend-setup
Apr 1, 2026
Merged

Backend User Authentication & Registration#133
driedpampas merged 45 commits intomainfrom
feature/auth-backend-setup

Conversation

@iuliaaa20
Copy link
Copy Markdown
Contributor

@iuliaaa20 iuliaaa20 commented Mar 31, 2026

Implemented a full-stack authentication flow using JWT (JSON Web Tokens) and Spring Security.
How to test:

  1. Run docker-compose down -v && docker-compose up -d to refresh the DB schema.
  2. Use Postman to POST to /api/auth/register.
  3. Verify that the password is stored as a BCrypt hash in the users table.

Summary by CodeRabbit

  • New Features

    • User registration and login with JWT-based authentication (token issued on login).
  • Bug Fixes / UX

    • Improved validation and clearer error responses for auth flows; CORS tightened for local frontend; authentication failures return appropriate HTTP statuses.
  • Tests

    • Expanded unit and integration tests covering auth, JWT handling, and security filter behavior.
  • Chores

    • Security enabled by default, DB moved to env-driven config with host port change, legacy DB init removed, new users schema added.

driedpampas and others added 28 commits March 20, 2026 17:42
Added dependencies for REST APIs and Swagger. Created a mock endpoint at /api/routing/calculate returning fake route data for frontend integration.
- Extrase clasele DTO (RoutingRequest, RoutingResponse, RoutePoint) în fișiere separate și adăugați getteri/setteri pentru a rezolva problemele de Maintainability din SonarQube.
- Adăugat RoutingControllerTest.java pentru a crește Code Coverage-ul conform cerințelor Quality Gate-ului.
- Adăugat excepție în application.properties pentru a ignora temporar auto-configurarea bazei de date (DataSource/Hibernate). Baza de date PostGIS va fi configurată și integrată ulterior de BE 1 în task-ul dedicat.
* fix(config): update MongoDB URI property in application configuration

* feat(jacoco): add JaCoCo configuration for test coverage reporting
…ql-setup

Add Spring Boot Web dependency, global exception handler, and server port configuration
Add Spring Web, OpenAPI setup and mock RoutingController
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Mar 31, 2026

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds JWT-based authentication (controller, DTOs, service, repository, entity, security filter/config, JWT util), replaces a PostGIS DB init script with a simple users SQL, changes Docker Postgres host port, updates build/test dependencies for JWT/Security/Testcontainers/H2, updates application/test configs, and adds related unit/integration tests.

Changes

Cohort / File(s) Summary
Build & Test
build.gradle.kts
Added jjwtVersion = "0.13.0", JJWT libs (jjwt-api, jjwt-impl, jjwt-jackson), spring-boot-starter-security, Testcontainers (testcontainers, postgresql), H2, and expanded test dependencies.
Docker & DB init
docker-compose.yml, init-scripts/01-init.sql, init-scripts/users.sql
Changed host Postgres mapping to 5433:5432; deleted PostGIS init script (init-scripts/01-init.sql); added init-scripts/users.sql creating a simple users table.
Auth API & DTOs
src/main/java/com/p2ps/auth/controller/AuthController.java, src/main/java/com/p2ps/auth/dto/RegisterRequest.java, src/main/java/com/p2ps/auth/security/dto/LoginRequest.java, src/main/java/com/p2ps/auth/security/dto/AuthResponse.java
Added AuthController with POST /api/auth/register and POST /api/auth/login and request/response DTOs with validation.
Security core
src/main/java/com/p2ps/auth/security/JwtAuthFilter.java, src/main/java/com/p2ps/auth/security/JwtUtil.java, src/main/java/com/p2ps/auth/security/SecurityConfig.java
Introduced JWT filter (reads token cookie), JWT util (HS256, 24h expiry, secret length check), security beans, stateless filter chain, custom auth entry point, and CORS config.
User persistence
src/main/java/com/p2ps/auth/model/Users.java, src/main/java/com/p2ps/auth/repository/UserRepository.java
Added JPA Users entity mapped to users table and UserRepository with findByEmail and existsByEmail.
Service & exceptions
src/main/java/com/p2ps/auth/service/UserService.java, src/main/java/com/p2ps/exception/UserAlreadyExistsException.java, src/main/java/com/p2ps/exception/GlobalExceptionHandler.java
Added UserService (implements UserDetailsService) with registerUser and transactional handling; added UserAlreadyExistsException; extended global exception handler for registration, validation, and auth errors.
Application config
src/main/resources/application.properties
Switched DB config to environment-driven values (host port 5433), changed spring.jpa.hibernate.ddl-auto to validate, added jwt.secret, enabled optional .env import, and fixed CORS origin to http://localhost:5173.
Tests & test config
src/test/java/resources/application-test.properties, src/test/java/com/p2ps/P2PShoppingApplicationTests.java, src/test/java/com/p2ps/auth/...
Added H2-based test properties, updated test annotations/properties, and added tests: AuthControllerTest, UserServiceTest, JwtAuthFilterTest, JwtUtilTest (mix of integration and unit tests).

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant AuthController
    participant UserService
    participant UserRepository
    participant Database
    participant AuthenticationManager
    participant JwtUtil

    rect rgba(0, 150, 200, 0.5)
    Note over Client,AuthController: Registration
    Client->>AuthController: POST /api/auth/register (email,password,firstName,lastName)
    AuthController->>UserService: registerUser(...)
    UserService->>UserRepository: existsByEmail(email)
    UserRepository->>Database: SELECT
    alt exists
        UserService-->>AuthController: throw UserAlreadyExistsException
        AuthController-->>Client: 409
    else new
        UserService->>UserService: encode password
        UserService->>UserRepository: save(user)
        UserRepository->>Database: INSERT
        UserService-->>AuthController: success
        AuthController-->>Client: 200
    end
    end

    rect rgba(100, 200, 100, 0.5)
    Note over Client,AuthController: Login
    Client->>AuthController: POST /api/auth/login (email,password)
    AuthController->>AuthenticationManager: authenticate(token)
    AuthenticationManager->>UserService: loadUserByUsername(email)
    UserService->>UserRepository: findByEmail(email)
    UserRepository->>Database: SELECT
    AuthenticationManager-->>AuthController: Authentication
    alt valid
        AuthController->>JwtUtil: generateToken(email)
        JwtUtil-->>AuthController: token
        AuthController-->>Client: 200 (token)
    else invalid
        AuthController-->>Client: 401
    end
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~55 minutes

Possibly related PRs

Suggested reviewers

  • bmbianca
  • Bianca-Alexandru
🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 3.51% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'Backend User Authentication & Registration' accurately and clearly describes the main changes, which involve implementing a complete authentication system with JWT and Spring Security.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/auth-backend-setup

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown
Contributor

@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.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/test/java/com/p2ps/P2PShoppingApplicationTests.java (1)

8-20: ⚠️ Potential issue | 🔴 Critical

@ActiveProfiles("test") does not cover the direct main(...) startup path.

Line 8 configures the Spring Test context, but Line 20 starts a separate app instance via P2PShoppingApplication.main(...) without activating the test profile. The new process loads the default configuration (PostgreSQL at localhost:5433), causing CI failures due to connection refusal. The test profile must be explicitly passed to the launched process.

Proposed fix
     `@Test`
     void shouldStartApplicationMainWithoutThrowing() {
-        assertDoesNotThrow(() -> P2PShoppingApplication.main(new String[]{"--spring.main.web-application-type=none"}));
+        assertDoesNotThrow(() -> P2PShoppingApplication.main(new String[]{
+                "--spring.main.web-application-type=none",
+                "--spring.profiles.active=test"
+        }));
     }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/test/java/com/p2ps/P2PShoppingApplicationTests.java` around lines 8 - 20,
The test starts a separate app instance via P2PShoppingApplication.main(...)
without the test profile, causing it to load default DB config; modify the test
invocation in shouldStartApplicationMainWithoutThrowing to include the test
profile flag (e.g. add "--spring.profiles.active=test" to the argument array) so
the launched process uses the `@ActiveProfiles`("test") configuration when calling
P2PShoppingApplication.main; update the argument list passed to
P2PShoppingApplication.main(...) accordingly.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Outside diff comments:
In `@src/test/java/com/p2ps/P2PShoppingApplicationTests.java`:
- Around line 8-20: The test starts a separate app instance via
P2PShoppingApplication.main(...) without the test profile, causing it to load
default DB config; modify the test invocation in
shouldStartApplicationMainWithoutThrowing to include the test profile flag (e.g.
add "--spring.profiles.active=test" to the argument array) so the launched
process uses the `@ActiveProfiles`("test") configuration when calling
P2PShoppingApplication.main; update the argument list passed to
P2PShoppingApplication.main(...) accordingly.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 3847f2cf-4895-4dd1-887e-80afef7a630d

📥 Commits

Reviewing files that changed from the base of the PR and between 5e34a44 and 869041e.

📒 Files selected for processing (6)
  • build.gradle.kts
  • src/main/java/com/p2ps/auth/security/JwtUtil.java
  • src/main/java/com/p2ps/auth/security/dto/LoginRequest.java
  • src/main/java/com/p2ps/auth/service/UserService.java
  • src/test/java/com/p2ps/P2PShoppingApplicationTests.java
  • src/test/java/resources/application-test.properties
✅ Files skipped from review due to trivial changes (3)
  • src/test/java/resources/application-test.properties
  • src/main/java/com/p2ps/auth/security/dto/LoginRequest.java
  • build.gradle.kts
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/main/java/com/p2ps/auth/service/UserService.java
  • src/main/java/com/p2ps/auth/security/JwtUtil.java

Copy link
Copy Markdown
Contributor

@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.

🧹 Nitpick comments (1)
src/test/java/com/p2ps/P2PShoppingApplicationTests.java (1)

7-16: Consolidate test configuration to avoid duplication.

Using both @ActiveProfiles("test") (which loads application-test.properties) and inline @SpringBootTest(properties = {...}) creates two sources of truth. Inline properties override profile properties for overlapping keys, making the profile-based values effectively dead code and creating maintenance drift risk.

Choose one approach:

  • Option A (recommended): Keep @ActiveProfiles("test") and move all properties to application-test.properties, removing the inline properties array.
  • Option B: Remove @ActiveProfiles("test") and rely solely on inline properties for this specific test.
♻️ Option A: Rely on profile-based configuration
-@SpringBootTest(properties = {
-        "jwt.secret=test-secret-key-care-trebuie-sa-fie-foarte-lunga-32-chars",
-        "spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1",
-        "spring.datasource.driver-class-name=org.h2.Driver",
-        "spring.datasource.username=sa",
-        "spring.datasource.password=",
-        "spring.jpa.database-platform=org.hibernate.dialect.H2Dialect",
-        "spring.jpa.hibernate.ddl-auto=create-drop"
-})
+@SpringBootTest
 `@ActiveProfiles`("test")

Ensure src/test/resources/application-test.properties contains all these properties.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/test/java/com/p2ps/P2PShoppingApplicationTests.java` around lines 7 - 16,
The test currently mixes `@SpringBootTest`(properties = { ... }) with
`@ActiveProfiles`("test"), causing duplicate/conflicting configuration; pick one
approach—recommended: remove the inline properties from the `@SpringBootTest`
annotation and move those keys into
src/test/resources/application-test.properties so `@ActiveProfiles`("test") (on
class P2PShoppingApplicationTests) drives the test config; alternatively remove
`@ActiveProfiles`("test") and keep the inline properties if you prefer per-test
overrides—update the annotation usage on the P2PShoppingApplicationTests class
and consolidate the properties accordingly.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@src/test/java/com/p2ps/P2PShoppingApplicationTests.java`:
- Around line 7-16: The test currently mixes `@SpringBootTest`(properties = { ...
}) with `@ActiveProfiles`("test"), causing duplicate/conflicting configuration;
pick one approach—recommended: remove the inline properties from the
`@SpringBootTest` annotation and move those keys into
src/test/resources/application-test.properties so `@ActiveProfiles`("test") (on
class P2PShoppingApplicationTests) drives the test config; alternatively remove
`@ActiveProfiles`("test") and keep the inline properties if you prefer per-test
overrides—update the annotation usage on the P2PShoppingApplicationTests class
and consolidate the properties accordingly.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: c2251cb9-d39d-4b24-89cd-c56b40fa0e6b

📥 Commits

Reviewing files that changed from the base of the PR and between 869041e and 86087e3.

📒 Files selected for processing (3)
  • src/main/java/com/p2ps/auth/security/dto/AuthResponse.java
  • src/main/resources/application.properties
  • src/test/java/com/p2ps/P2PShoppingApplicationTests.java
✅ Files skipped from review due to trivial changes (1)
  • src/main/java/com/p2ps/auth/security/dto/AuthResponse.java
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/main/resources/application.properties

Copy link
Copy Markdown
Contributor

@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: 1

♻️ Duplicate comments (1)
src/main/java/com/p2ps/auth/security/JwtUtil.java (1)

19-28: ⚠️ Potential issue | 🟠 Major

Harden JWT secret initialization (charset + explicit validation).

Line 27 still uses platform-default encoding and no pre-validation for null/short secrets. That can produce environment-dependent keys and fail at runtime with weak/null config.

🔧 Suggested patch
+import java.nio.charset.StandardCharsets;
@@
     `@PostConstruct`
     public void init() {
-        this.secretKey = Keys.hmacShaKeyFor(secretKeyString.getBytes());
+        if (secretKeyString == null || secretKeyString.isBlank()) {
+            throw new IllegalStateException("Missing jwt.secret configuration");
+        }
+        byte[] keyBytes = secretKeyString.getBytes(StandardCharsets.UTF_8);
+        if (keyBytes.length < 32) {
+            throw new IllegalStateException("JWT secret must be at least 32 bytes for HS256");
+        }
+        this.secretKey = Keys.hmacShaKeyFor(keyBytes);
     }
#!/bin/bash
set -euo pipefail

echo "== Verify JJWT dependency and JwtUtil init implementation =="
fd -i 'build.gradle.kts|pom.xml' -x sh -c 'echo "--- {}"; rg -n "jjwt|io\\.jsonwebtoken" "{}" || true'
fd -i 'JwtUtil.java' -x sh -c 'echo "--- {}"; nl -ba "{}" | sed -n "1,120p"'

Expected result: dependency uses JJWT, and init() should show UTF-8 conversion plus explicit null/length validation before Keys.hmacShaKeyFor(...).

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/main/java/com/p2ps/auth/security/JwtUtil.java` around lines 19 - 28, The
JwtUtil init() uses platform-default charset and lacks validation; update the
init() method to (1) validate that secretKeyString is not null/blank and that
secretKeyString.getBytes(StandardCharsets.UTF_8).length meets the minimum
required length for JJWT HMAC keys (e.g., >= 32 bytes for HS256) and throw a
clear IllegalStateException if invalid, and (2) derive secretKey using
secretKeyString.getBytes(StandardCharsets.UTF_8) passed into
Keys.hmacShaKeyFor(...). Reference: secretKeyString, init(), secretKey,
Keys.hmacShaKeyFor.
🧹 Nitpick comments (1)
src/test/java/com/p2ps/auth/UserServicesTest.java (1)

8-8: Remove unused import.

BeforeEach is imported but never used in this test class.

-import org.junit.jupiter.api.BeforeEach;
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/test/java/com/p2ps/auth/UserServicesTest.java` at line 8, Remove the
unused import of BeforeEach from UserServicesTest.java: delete the line
importing org.junit.jupiter.api.BeforeEach and verify there are no references to
the BeforeEach symbol (e.g., any `@BeforeEach` annotations or methods named for
setup) in the class; if a setup method is needed, replace the import with the
correct annotation import or add the setup method, otherwise simply remove the
import to resolve the unused import warning.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/test/java/com/p2ps/auth/UserServicesTest.java`:
- Line 22: The test class declared as UserServiceTest does not match the current
filename UserServicesTest.java; rename the file to UserServiceTest.java so the
public class UserServiceTest matches the filename exactly and the test compiles.

---

Duplicate comments:
In `@src/main/java/com/p2ps/auth/security/JwtUtil.java`:
- Around line 19-28: The JwtUtil init() uses platform-default charset and lacks
validation; update the init() method to (1) validate that secretKeyString is not
null/blank and that secretKeyString.getBytes(StandardCharsets.UTF_8).length
meets the minimum required length for JJWT HMAC keys (e.g., >= 32 bytes for
HS256) and throw a clear IllegalStateException if invalid, and (2) derive
secretKey using secretKeyString.getBytes(StandardCharsets.UTF_8) passed into
Keys.hmacShaKeyFor(...). Reference: secretKeyString, init(), secretKey,
Keys.hmacShaKeyFor.

---

Nitpick comments:
In `@src/test/java/com/p2ps/auth/UserServicesTest.java`:
- Line 8: Remove the unused import of BeforeEach from UserServicesTest.java:
delete the line importing org.junit.jupiter.api.BeforeEach and verify there are
no references to the BeforeEach symbol (e.g., any `@BeforeEach` annotations or
methods named for setup) in the class; if a setup method is needed, replace the
import with the correct annotation import or add the setup method, otherwise
simply remove the import to resolve the unused import warning.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 3dc34c75-c591-4416-a1eb-afdfc89a3889

📥 Commits

Reviewing files that changed from the base of the PR and between 86087e3 and 6a6a8f7.

📒 Files selected for processing (7)
  • src/main/java/com/p2ps/auth/controller/AuthController.java
  • src/main/java/com/p2ps/auth/dto/RegisterRequest.java
  • src/main/java/com/p2ps/auth/model/Users.java
  • src/main/java/com/p2ps/auth/security/JwtAuthFilter.java
  • src/main/java/com/p2ps/auth/security/JwtUtil.java
  • src/main/java/com/p2ps/auth/security/SecurityConfig.java
  • src/test/java/com/p2ps/auth/UserServicesTest.java
✅ Files skipped from review due to trivial changes (1)
  • src/main/java/com/p2ps/auth/model/Users.java
🚧 Files skipped from review as they are similar to previous changes (4)
  • src/main/java/com/p2ps/auth/controller/AuthController.java
  • src/main/java/com/p2ps/auth/dto/RegisterRequest.java
  • src/main/java/com/p2ps/auth/security/JwtAuthFilter.java
  • src/main/java/com/p2ps/auth/security/SecurityConfig.java

Copy link
Copy Markdown
Contributor

@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.

🧹 Nitpick comments (3)
src/main/java/com/p2ps/exception/GlobalExceptionHandler.java (1)

57-65: Consider using consistent response type across handlers.

This handler returns ResponseEntity<Map<String, String>> while others return ResponseEntity<ErrorResponse>. For API consistency, consider using ErrorResponse here as well.

♻️ Proposed refactor for consistency
     `@ExceptionHandler`({BadCredentialsException.class, UsernameNotFoundException.class})
-    public ResponseEntity<Map<String, String>> handleAuthenticationError(Exception ex) {
-        return ResponseEntity
-                .status(HttpStatus.UNAUTHORIZED) // Trimitem 401 în loc de 500
-                .body(Map.of(
-                        "error", "Unauthorized",
-                        "message", "Invalid email or password" // Mesaj generic, sigur
-                ));
+    public ResponseEntity<ErrorResponse> handleAuthenticationError(Exception ex) {
+        ErrorResponse errorResponse = new ErrorResponse(
+                "Unauthorized",
+                "Invalid email or password"
+        );
+        return new ResponseEntity<>(errorResponse, HttpStatus.UNAUTHORIZED);
     }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/main/java/com/p2ps/exception/GlobalExceptionHandler.java` around lines 57
- 65, The handleAuthenticationError method in GlobalExceptionHandler currently
returns ResponseEntity<Map<String, String>>; change it to return
ResponseEntity<ErrorResponse> and construct/return an ErrorResponse instance
(populating the same "error" and "message" values used now) with status
HttpStatus.UNAUTHORIZED so the handler matches other exception handlers that use
ErrorResponse; update the method signature and body in handleAuthenticationError
to create and return the ErrorResponse accordingly.
src/main/java/com/p2ps/auth/controller/AuthController.java (1)

45-53: The authentication result is captured but not used.

The authenticate() call correctly validates credentials, but the returned Authentication object is assigned to a variable that's never used. You could either remove the variable assignment or use the authenticated principal to generate the token.

♻️ Option 1: Remove unused variable
-        Authentication authentication = authenticationManager.authenticate(
+        authenticationManager.authenticate(
                 new UsernamePasswordAuthenticationToken(
                         request.getEmail(),
                         request.getPassword()
                 )
         );
-
-
         String token = jwtUtil.generateToken(request.getEmail());
♻️ Option 2: Use authenticated principal
         Authentication authentication = authenticationManager.authenticate(
                 new UsernamePasswordAuthenticationToken(
                         request.getEmail(),
                         request.getPassword()
                 )
         );
-
-
-        String token = jwtUtil.generateToken(request.getEmail());
+        String token = jwtUtil.generateToken(authentication.getName());
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/main/java/com/p2ps/auth/controller/AuthController.java` around lines 45 -
53, AuthController captures the result of
authenticationManager.authenticate(...) into the unused variable authentication;
either remove the assignment and call authenticationManager.authenticate(...)
for its side-effect only, or use the authenticated principal when generating the
JWT (e.g., extract the principal or username from the returned Authentication
and pass that into jwtUtil.generateToken instead of using request.getEmail()).
Locate the call to authenticationManager.authenticate with
UsernamePasswordAuthenticationToken and update the subsequent
jwtUtil.generateToken invocation accordingly to use
authentication.getPrincipal()/getName() or delete the unused variable.
src/test/java/com/p2ps/auth/AuthControllerTest.java (1)

47-48: Test method name suggests 201 Created, but endpoint returns 200 OK.

The method is named register_ShouldReturnCreated but the assertion expects status().isOk() (HTTP 200). Either rename the method to register_ShouldReturnOk or update the endpoint to return 201 Created if that's the intended behavior for resource creation.

♻️ Rename to match actual behavior
     `@Test`
-    void register_ShouldReturnCreated() throws Exception {
+    void register_ShouldReturnOk() throws Exception {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/test/java/com/p2ps/auth/AuthControllerTest.java` around lines 47 - 48,
The test method name register_ShouldReturnCreated in AuthControllerTest is
misleading because the assertion uses status().isOk(); rename the test to
register_ShouldReturnOk (or alternatively change the controller/register
endpoint to return 201 Created if you intend creation semantics). Update the
method name register_ShouldReturnCreated to register_ShouldReturnOk and adjust
any references or test frameworks that rely on the method name; if you choose
the endpoint change, modify the AuthController register handler to return
ResponseEntity.status(HttpStatus.CREATED) for successful registration and update
the test assertion to status().isCreated().
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@src/main/java/com/p2ps/auth/controller/AuthController.java`:
- Around line 45-53: AuthController captures the result of
authenticationManager.authenticate(...) into the unused variable authentication;
either remove the assignment and call authenticationManager.authenticate(...)
for its side-effect only, or use the authenticated principal when generating the
JWT (e.g., extract the principal or username from the returned Authentication
and pass that into jwtUtil.generateToken instead of using request.getEmail()).
Locate the call to authenticationManager.authenticate with
UsernamePasswordAuthenticationToken and update the subsequent
jwtUtil.generateToken invocation accordingly to use
authentication.getPrincipal()/getName() or delete the unused variable.

In `@src/main/java/com/p2ps/exception/GlobalExceptionHandler.java`:
- Around line 57-65: The handleAuthenticationError method in
GlobalExceptionHandler currently returns ResponseEntity<Map<String, String>>;
change it to return ResponseEntity<ErrorResponse> and construct/return an
ErrorResponse instance (populating the same "error" and "message" values used
now) with status HttpStatus.UNAUTHORIZED so the handler matches other exception
handlers that use ErrorResponse; update the method signature and body in
handleAuthenticationError to create and return the ErrorResponse accordingly.

In `@src/test/java/com/p2ps/auth/AuthControllerTest.java`:
- Around line 47-48: The test method name register_ShouldReturnCreated in
AuthControllerTest is misleading because the assertion uses status().isOk();
rename the test to register_ShouldReturnOk (or alternatively change the
controller/register endpoint to return 201 Created if you intend creation
semantics). Update the method name register_ShouldReturnCreated to
register_ShouldReturnOk and adjust any references or test frameworks that rely
on the method name; if you choose the endpoint change, modify the AuthController
register handler to return ResponseEntity.status(HttpStatus.CREATED) for
successful registration and update the test assertion to status().isCreated().

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 099b50b7-4a9a-4182-94de-829d6646413c

📥 Commits

Reviewing files that changed from the base of the PR and between 86087e3 and b2d34f3.

📒 Files selected for processing (13)
  • build.gradle.kts
  • src/main/java/com/p2ps/auth/controller/AuthController.java
  • src/main/java/com/p2ps/auth/dto/RegisterRequest.java
  • src/main/java/com/p2ps/auth/model/Users.java
  • src/main/java/com/p2ps/auth/security/JwtAuthFilter.java
  • src/main/java/com/p2ps/auth/security/JwtUtil.java
  • src/main/java/com/p2ps/auth/security/SecurityConfig.java
  • src/main/java/com/p2ps/auth/security/dto/LoginRequest.java
  • src/main/java/com/p2ps/auth/service/UserService.java
  • src/main/java/com/p2ps/exception/GlobalExceptionHandler.java
  • src/test/java/com/p2ps/auth/AuthControllerTest.java
  • src/test/java/com/p2ps/auth/UserSeriviceTest.java
  • src/test/java/resources/application-test.properties
✅ Files skipped from review due to trivial changes (2)
  • src/test/java/resources/application-test.properties
  • src/main/java/com/p2ps/auth/model/Users.java
🚧 Files skipped from review as they are similar to previous changes (5)
  • src/main/java/com/p2ps/auth/dto/RegisterRequest.java
  • src/main/java/com/p2ps/auth/security/dto/LoginRequest.java
  • src/main/java/com/p2ps/auth/security/JwtAuthFilter.java
  • src/main/java/com/p2ps/auth/security/SecurityConfig.java
  • build.gradle.kts

Copy link
Copy Markdown
Contributor

@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: 1

🧹 Nitpick comments (1)
build.gradle.kts (1)

50-51: Align Testcontainers versions with Spring Boot 4.0.4 BOM management.

Lines 50-51 pin Testcontainers to 1.19.0, which is significantly outdated. Spring Boot 4.0.4 manages Testcontainers 2.0.4. Remove explicit versions to leverage the BOM and avoid version misalignment:

Proposed change
-    testImplementation("org.testcontainers:testcontainers:1.19.0")
-    testImplementation("org.testcontainers:postgresql:1.19.0")
+    testImplementation("org.testcontainers:testcontainers")
+    testImplementation("org.testcontainers:postgresql")
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@build.gradle.kts` around lines 50 - 51, Remove the hard-coded Testcontainers
versions so the Spring Boot 4.0.4 BOM can manage them: replace the two
dependency declarations that currently reference
org.testcontainers:testcontainers:1.19.0 and
org.testcontainers:postgresql:1.19.0 with versionless coordinates (i.e., keep
"org.testcontainers:testcontainers" and "org.testcontainers:postgresql" in the
testImplementation entries) so the BOM-provided 2.0.4 version is used.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@build.gradle.kts`:
- Around line 38-48: Remove the duplicated dependency declaration for
org.springframework.boot:spring-boot-starter-test: locate both occurrences of
testImplementation("org.springframework.boot:spring-boot-starter-test") and
delete the redundant one so only a single testImplementation for that coordinate
remains (keep
testImplementation("org.springframework.boot:spring-boot-starter-webmvc-test")
as-is since it transitively brings in the needed test artifacts).

---

Nitpick comments:
In `@build.gradle.kts`:
- Around line 50-51: Remove the hard-coded Testcontainers versions so the Spring
Boot 4.0.4 BOM can manage them: replace the two dependency declarations that
currently reference org.testcontainers:testcontainers:1.19.0 and
org.testcontainers:postgresql:1.19.0 with versionless coordinates (i.e., keep
"org.testcontainers:testcontainers" and "org.testcontainers:postgresql" in the
testImplementation entries) so the BOM-provided 2.0.4 version is used.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 9d8f7ee3-1219-4837-900d-5281fb114044

📥 Commits

Reviewing files that changed from the base of the PR and between c9a20f7 and ada55dd.

📒 Files selected for processing (4)
  • build.gradle.kts
  • src/test/java/com/p2ps/auth/AuthControllerTest.java
  • src/test/java/com/p2ps/auth/UserSeriviceTest.java
  • src/test/java/resources/application-test.properties
✅ Files skipped from review due to trivial changes (1)
  • src/test/java/resources/application-test.properties
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/test/java/com/p2ps/auth/AuthControllerTest.java
  • src/test/java/com/p2ps/auth/UserSeriviceTest.java

Copy link
Copy Markdown
Contributor

@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: 1

🧹 Nitpick comments (2)
src/test/java/com/p2ps/auth/AuthControllerTest.java (2)

85-99: Strengthen login success test by asserting the token payload.

Right now this test only checks status. Add a JSON assertion so payload regressions are caught.

Suggested assertion upgrade
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
@@
         mockMvc.perform(post("/api/auth/login")
                         .contentType(MediaType.APPLICATION_JSON)
                         .content(objectMapper.writeValueAsString(request)))
-                .andExpect(status().isOk());
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.token").value("mocked-jwt-token-123"));
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/test/java/com/p2ps/auth/AuthControllerTest.java` around lines 85 - 99,
The test login_ShouldReturnOk in AuthControllerTest currently only asserts HTTP
200; enhance it to also assert the response JSON contains the JWT by adding a
JSON body assertion on the mockMvc.perform result (e.g.,
andExpect(content().contentType(MediaType.APPLICATION_JSON))
andExpect(jsonPath("$.token").value("mocked-jwt-token-123"))). Keep the existing
stubbing of jwtUtil.generateToken("...") and Authentication mock; update the
mockMvc.perform chain to include these jsonPath assertions so the test verifies
the token payload is returned.

56-70: Rename this test or assert 201 Created to match intent.

The method name says “ShouldReturnCreated” but the assertion expects 200 OK. Aligning the name with actual behavior avoids confusion.

Suggested minimal rename
-    void register_ShouldReturnCreated() throws Exception {
+    void register_ShouldReturnOk() throws Exception {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/test/java/com/p2ps/auth/AuthControllerTest.java` around lines 56 - 70,
The test method register_ShouldReturnCreated is inconsistent: its name implies
it should assert HTTP 201 but the assertion uses status().isOk(); either change
the assertion in the mockMvc.perform(...) chain to expect status().isCreated()
or rename the test method (register_ShouldReturnOk) to match the current
behavior. Locate the method register_ShouldReturnCreated in AuthControllerTest,
update the expectation on mockMvc.perform(...).andExpect(...) to
status().isCreated() if the controller is meant to return 201, or rename the
test method to reflect 200 OK if you prefer to keep the assertion.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/test/java/com/p2ps/auth/JwtAuthFilterTest.java`:
- Around line 47-75: Tests in JwtAuthFilterTest leak SecurityContextHolder state
across tests causing order-dependent failures; add a cleanup hook that invokes
SecurityContextHolder.clearContext() after each test (e.g., an `@AfterEach` method
in the JwtAuthFilterTest class) so doFilterInternal tests always run with a
fresh security context and no leftover Authentication.

---

Nitpick comments:
In `@src/test/java/com/p2ps/auth/AuthControllerTest.java`:
- Around line 85-99: The test login_ShouldReturnOk in AuthControllerTest
currently only asserts HTTP 200; enhance it to also assert the response JSON
contains the JWT by adding a JSON body assertion on the mockMvc.perform result
(e.g., andExpect(content().contentType(MediaType.APPLICATION_JSON))
andExpect(jsonPath("$.token").value("mocked-jwt-token-123"))). Keep the existing
stubbing of jwtUtil.generateToken("...") and Authentication mock; update the
mockMvc.perform chain to include these jsonPath assertions so the test verifies
the token payload is returned.
- Around line 56-70: The test method register_ShouldReturnCreated is
inconsistent: its name implies it should assert HTTP 201 but the assertion uses
status().isOk(); either change the assertion in the mockMvc.perform(...) chain
to expect status().isCreated() or rename the test method
(register_ShouldReturnOk) to match the current behavior. Locate the method
register_ShouldReturnCreated in AuthControllerTest, update the expectation on
mockMvc.perform(...).andExpect(...) to status().isCreated() if the controller is
meant to return 201, or rename the test method to reflect 200 OK if you prefer
to keep the assertion.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: a4cff4f7-3136-4d72-ae11-7de8e66bdb2a

📥 Commits

Reviewing files that changed from the base of the PR and between 3eea4b2 and c797bfa.

📒 Files selected for processing (4)
  • src/main/java/com/p2ps/auth/security/JwtAuthFilter.java
  • src/test/java/com/p2ps/auth/AuthControllerTest.java
  • src/test/java/com/p2ps/auth/JwtAuthFilterTest.java
  • src/test/java/com/p2ps/auth/JwtUtilTest.java
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/main/java/com/p2ps/auth/security/JwtAuthFilter.java

Copy link
Copy Markdown
Member

@driedpampas driedpampas left a comment

Choose a reason for hiding this comment

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

lgbt!

Copy link
Copy Markdown
Contributor

@Bianca-Alexandru Bianca-Alexandru left a comment

Choose a reason for hiding this comment

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

lgbt

@driedpampas driedpampas merged commit 2fef06c into main Apr 1, 2026
2 checks passed
@driedpampas driedpampas deleted the feature/auth-backend-setup branch April 1, 2026 09:04
@sonarqubecloud
Copy link
Copy Markdown

sonarqubecloud bot commented Apr 1, 2026

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.

6 participants