Skip to content

feat: Add admin-only endpoint to search user by email #203

Merged
lindaeskilsson merged 2 commits into
mainfrom
feat/search-user-by-email
Apr 14, 2026
Merged

feat: Add admin-only endpoint to search user by email #203
lindaeskilsson merged 2 commits into
mainfrom
feat/search-user-by-email

Conversation

@lindaeskilsson

@lindaeskilsson lindaeskilsson commented Apr 14, 2026

Copy link
Copy Markdown
Contributor

Implementerar GET /api/users/search?email= som endast admins kan använda, enligt issue #132.
Ändringar

UserController — lagt till GET /api/users/search?email= med @PreAuthorize("hasRole('ADMIN')")
UserService — lagt till searchByEmail(String email) som returnerar UserResponse (den befintliga getByEmail() används internt och returnerar entiteten)
SecurityConfig — lagt till @EnableMethodSecurity för att aktivera @PreAuthorize

Säkerhet
Endpointen är skyddad med @PreAuthorize("hasRole('ADMIN')") — anrop utan admin-token ger 403 Forbidden, anrop utan token ger 401 Unauthorized.

Notering
Manuellt test via Postman väntar på att AuthController (login-endpoint) implementeras. Alla 430 befintliga enhetstester passerar.

Closes #132

Summary by CodeRabbit

  • New Features

    • Introduced a new user search capability for administrators, enabling searches by email address with consistent response formatting.
  • Security

    • Enabled method-level authorization controls to enforce role-based access restrictions throughout the application.

@coderabbitai

coderabbitai Bot commented Apr 14, 2026

Copy link
Copy Markdown

Warning

Rate limit exceeded

@lindaeskilsson has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 55 minutes and 42 seconds before requesting another review.

Your organization is not enrolled in usage-based pricing. Contact your admin to enable usage-based pricing to continue reviews beyond the rate limit, or try again in 55 minutes and 42 seconds.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 0f3f3e90-6c42-462e-9c88-c2cb383aac96

📥 Commits

Reviewing files that changed from the base of the PR and between fc0b439 and 49c4da7.

📒 Files selected for processing (1)
  • src/main/java/org/example/vet1177/controller/UserController.java
📝 Walkthrough

Walkthrough

This pull request adds a new admin-only email search endpoint for users. The changes introduce a GET /api/users/search endpoint secured with Spring Security role-based authorization, enable method-level security checks in the configuration, and implement the corresponding service method to search users by email and return DTOs.

Changes

Cohort / File(s) Summary
Admin-Only Search Endpoint
src/main/java/org/example/vet1177/controller/UserController.java
Added searchByEmail() endpoint mapped to GET /api/users/search with @PreAuthorize("hasRole('ADMIN')") that accepts email as a request parameter, delegates to service, and returns UserResponse with HTTP 200.
Method-Level Security Configuration
src/main/java/org/example/vet1177/security/SecurityConfig.java
Added @EnableMethodSecurity annotation to enable Spring Security method-level authorization checks via annotations like @PreAuthorize.
User Search Service Logic
src/main/java/org/example/vet1177/services/UserService.java
Implemented searchByEmail(String email) method that retrieves users by email, throws ResourceNotFoundException when not found, and returns a mapped UserResponse DTO.

Sequence Diagram

sequenceDiagram
    actor Admin as Admin User
    participant Controller as UserController
    participant Security as Spring Security
    participant Service as UserService
    participant Repo as UserRepository
    
    Admin->>Controller: GET /api/users/search?email=...
    Controller->>Security: Check `@PreAuthorize`("hasRole('ADMIN')")
    alt User is Admin
        Security-->>Controller: Authorization granted
        Controller->>Service: searchByEmail(email)
        Service->>Repo: findByEmail(email)
        alt User found
            Repo-->>Service: User entity
            Service->>Service: mapToResponse(user)
            Service-->>Controller: UserResponse DTO
            Controller-->>Admin: HTTP 200 + UserResponse
        else User not found
            Repo-->>Service: Optional.empty()
            Service-->>Controller: ResourceNotFoundException
            Controller-->>Admin: HTTP 404
        end
    else User is not Admin
        Security-->>Controller: Access denied
        Controller-->>Admin: HTTP 403
    end
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Possibly related PRs

Suggested reviewers

  • johanbriger
  • annikaholmqvist94
  • TatjanaTrajkovic

Poem

🐰 A new endpoint hops into view,
Admins search by email—secure and true!
Spring Security guards the path so bright,
UserResponse returns, the query takes flight!
One feature complete, the code's done just right! 🎉

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: adding an admin-only endpoint to search users by email, which matches the primary objective.
Linked Issues check ✅ Passed All requirements from issue #132 are met: GET /api/users/search?email= endpoint [#132], admin-only access via @PreAuthorize [#132], Spring Security method-level authorization enabled [#132].
Out of Scope Changes check ✅ Passed All code changes are directly aligned with issue #132 requirements: the new endpoint, authorization restriction, service method, and security configuration enable the requested functionality with no extraneous modifications.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ 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 feat/search-user-by-email

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

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)
src/main/java/org/example/vet1177/services/UserService.java (1)

75-79: Reuse existing lookup path to avoid logic duplication.

Lines 77-78 duplicate getByEmail (Lines 68-72). Prefer one source of truth for lookup + exception handling.

♻️ Proposed refactor
 public UserResponse searchByEmail(String email) {
     log.debug("Searching user by email={}", email);
-    User user = userRepository.findByEmail(email)
-            .orElseThrow(() -> new ResourceNotFoundException("User", email));
+    User user = getByEmail(email);
     return mapToResponse(user);
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/main/java/org/example/vet1177/services/UserService.java` around lines 75
- 79, The searchByEmail method duplicates lookup and exception logic already
implemented in getByEmail; change searchByEmail to reuse that single lookup path
by calling getByEmail(email) and then mapping the returned User to UserResponse
(or extract a private helper like findUserByEmail to be called by both
getByEmail and searchByEmail) so exception handling is centralized in one place
(update references to mapToResponse and ensure method names: searchByEmail,
getByEmail, mapToResponse, and any helper you add).
🤖 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/main/java/org/example/vet1177/controller/UserController.java`:
- Around line 49-51: The log in UserController.searchByEmail currently emits the
raw email (PII); change the logging to avoid sensitive data by either removing
the email from the log (log only the endpoint and request received) or log a
masked version of the email (e.g., replace local-part with asterisks) before
calling userService.searchByEmail; update the log statement in
UserController.searchByEmail accordingly and ensure any downstream logs or
exceptions do not reintroduce the raw email.

---

Nitpick comments:
In `@src/main/java/org/example/vet1177/services/UserService.java`:
- Around line 75-79: The searchByEmail method duplicates lookup and exception
logic already implemented in getByEmail; change searchByEmail to reuse that
single lookup path by calling getByEmail(email) and then mapping the returned
User to UserResponse (or extract a private helper like findUserByEmail to be
called by both getByEmail and searchByEmail) so exception handling is
centralized in one place (update references to mapToResponse and ensure method
names: searchByEmail, getByEmail, mapToResponse, and any helper you add).
🪄 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: 2b570beb-1e0b-41d5-94d6-83c2d2f707da

📥 Commits

Reviewing files that changed from the base of the PR and between 0a3b07d and fc0b439.

📒 Files selected for processing (3)
  • src/main/java/org/example/vet1177/controller/UserController.java
  • src/main/java/org/example/vet1177/security/SecurityConfig.java
  • src/main/java/org/example/vet1177/services/UserService.java

Comment thread src/main/java/org/example/vet1177/controller/UserController.java
@lindaeskilsson
lindaeskilsson merged commit 8deee0c into main Apr 14, 2026
2 checks passed
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.

Add endpoint to search user by email (admin only)

2 participants