Skip to content

Renamed GlobalExceptionHandler#17

Open
ehottinen wants to merge 38 commits into
mainfrom
rename-globalexceptionhandler
Open

Renamed GlobalExceptionHandler#17
ehottinen wants to merge 38 commits into
mainfrom
rename-globalexceptionhandler

Conversation

@ehottinen

@ehottinen ehottinen commented Apr 3, 2025

Copy link
Copy Markdown
Collaborator

Summary by CodeRabbit

  • Refactor
    • Updated internal naming conventions in the exception handling component, ensuring consistency while maintaining identical functionality for end-users.

@coderabbitai

coderabbitai Bot commented Apr 3, 2025

Copy link
Copy Markdown

Important

Review skipped

More than 25% of the files skipped due to max files limit. The review is being skipped to prevent a low-quality review.

98 files out of 205 files are above the max files limit of 100. Please upgrade to Pro plan to get higher limits.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

This pull request renames a class within the exception handling package to better reflect its REST-related functionality. The class was previously named GlobalExceptionHandler and was updated to GlobalRESTExceptionHandler. No other changes to logic, error handling, or control flow were made.

Changes

File Change Summary
src/main/java/org/.../GlobalRESTExceptionHandler.java Renamed class from GlobalExceptionHandler to GlobalRESTExceptionHandler

Suggested reviewers

  • JenDevs

Poem

I'm a hopping rabbit in the code-filled glen,
Skipping through files again and again.
I cheer as class names gracefully change,
In our Spring Boot world, nothing's strange.
With each small rename, my circuits sing in delight!


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

@ehottinen
ehottinen requested a review from a team April 3, 2025 06:50
malvamalmgren and others added 3 commits April 3, 2025 13:09
* Update User entity and add User repository, service, controller

* Update css structure and add user-details.html and user-list.html

* Fix repository variable names

* Update controller, service and repository

* Update UserRepository and add exception handling in UserService

* Update UserViewController

* Update UserViewController and file structure

* Update and refactor user controllers and service

* Update UserViewController

* Update UserRepository, UserService, UserRestController, User entity and add html

* Update UserViewController

* Minor fix and add temp html

* Fix UserViewController if statements

* Fix UserViewController add method

* Cleanup and update add user form

* Add check for unique username and email, and add GlobalViewExceptionHandler with UserAlreadyExistsException

* Add check for unique username and email during update, and add delete account functionality

* Remove sensitive info
* Add RecommendationRepository, service logic, and exception handling

* Add RecommendationController with REST endpoints

* Add RecommendationService logic and exception handling

* Add placeholder Thymeleaf template for recommendations

* Fix: Align PUT and PATCH logic in RecommendationService with actual entity fields

* Add PUT and PATCH endpoints to RecommendationController

* Typo

* refactor(recommendation): replaced RecommendationNotFoundException with shared NotFoundException

* Deleted RecommendationNotFoundException

* Renamed controller
Added RecommendationViewController & HTML template for consistency

* Changed messages and comments to english

* refactor: English translation and class-level @transactional in RecommendationService
* Add CRUD support and placeholder view for Reminder entity

* Add PUT and PATCH support for Reminder entity

* Improve Reminder API robustness and validation

* Add setter for reminderId to enable full updates

* refactor(reminder): replaced ReminderNotFoundException with shared NotFoundException

* Deleted ReminderNotFoundException

* Renamed controller
Added ReminderViewController & HTML template for consistency

* Changed messages and comments to english

* refactor: English translation and class-level @transactional in ReminderService
malvamalmgren
malvamalmgren previously approved these changes Apr 3, 2025

@malvamalmgren malvamalmgren left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Amazing 🌟

ehottinen and others added 7 commits April 3, 2025 13:18
… for consistency changed messages and comments to english (#13)

* Renamed controller
Added RecommendationViewController & HTML template for consistency
changed messages and comments to english

* refactor(service): move @transactional to class level in PostService and EventService
* Added CatController, CatRepository and CatService

* Removed unused import statement and updated path variable id in request mapping

* Updated path variable id in request mapping for deletemapping.

* Added getAllCats in CatController

* Updated ids throughout CO-RE-SE

* Added cat classes into their respective directories

* Renamed CatController to CatRestController

* Added CatViewController, added HTML for cat-detail, cat-form, cat-list

* Added text to HTML

* Editting HTML for cats. Added code to cat-detail, cat-form and cats-list

* Split the cat forms to edit existing cat and adding a new cat

* Updated to NotFoundException in CatService

* Updated CatRestController and CatViewcController, editing existing cat html according to Coderabbit. Added CSFR token for protection, updated the headlines for HTML, added try catch for exception handling to update cat, delete cat and create cat in view and rest controllers.

* Commented out CSFR token in the cat forms for now. Added partial update to CatRestController CatViewController and CatService

* Removed NotNull to test and am considering removing partialupdatecat

* Added NotNull back
* Create EventParticipantRepository with basic CRUD support

* Add service layer and update repository with existsByUserIdAndEventId method

* Add and refactor EventParticipant feature: controller, service, repository, HTML views, and global exception handling

* Refactor EventParticipant and views based on CodeRabbit feedback

* git commit -m "Remove ServiceValidator"

* Temporarily remove failing test to fix CI pipeline

* Refactor: updated HTML views and restructured repo/service/controller

* Add missing index page

* Fix correct UserRepository in EvenParticipantService and resolve duplicate exception handlers

* Update handler imports

* Remove duplicate GlobalExceptionHandler, GlobalViewExceptionHandler and NotFoundException
* Har nu fixat Min Catphoto Controller, Service och Repository

* Fixed the CodeRabbit suggestions

* Moved my classes to the right folders

* Moved my classes to the right folders

Signed-off-by: LinusAltemark <Linalt0905@gmail.com>

---------

Signed-off-by: LinusAltemark <Linalt0905@gmail.com>
Signed-off-by: LinusAltemark <Linalt0905@gmail.com>
JenDevs
JenDevs previously approved these changes Apr 10, 2025
JenDevs and others added 10 commits April 11, 2025 11:26
* Add GraphQL dependencies and configuration

* Add Schema.graphqls and User.graphqls for User

* Add DTOs and mapper for converting between User entity and DTOs

* Add GraphQL controller with create, update, delete, and fetch operations

* Fix: correct method name to match GraphQL schema (case-sensitive)

* Add validation to UserInputDTO

* Disable GraphiQL in production and enable only in dev profile

* Add DateTime scalar and require input in updateUser

* Add pagination types and update user input/output definitions

* Improve mapper readability and add email validation

* Add global exception handler for GraphQL

* Add validation to UserOutputDTO and UserUpdateDTO

* Improve validation and error handling in controller methods

* Remove pagination from GraphQL schema and controller

* Add extended input validation to controller methods

* Replace NotBlank with NotNull on ID field and remove unused imports

* Add custom UserNotFoundException

* Improve email validation

* Add stricter validation of required fields

* Handle UserNotFoundException in global GraphQL exception handler

* Add valid annotation to createUser for automatic input validation

* Rename package Mapper to mapper

* Rename package DTO to dto, and Mapper to mapper

* Rename UserAlreadyExistsException to AlreadyExistsException for consistency

* Replace UserNotFoundException with generic NotFoundException and remove old class
* Created SecurityConfig

* Created security package
-CustomUserDetails (empty)
-CustomUsersDetailsService (empty)
-SecurityConfig (example)

* Created config package and placed SecurityConfig there

* Add Spring Security dependency and config package

* Security commit so I don't mess anything up when I checkout

* Created SecurityConfig

* Created security package
-CustomUserDetails (empty)
-CustomUsersDetailsService (empty)
-SecurityConfig (example)

* Add ApiKeyAuthenticationToken and filter

* Converted CustomUserDetails to a record

* Fixed SecurityConfig.java

* Recreated CustomUserDetailsService

* Added lombok to pom

* Added get/set password in User

* Waiting for Enum into main

* Created auth directory in templates
- login.html (empty)
- register.html (empty)

* Update partial user role handling to use enum userRoles

* feat: Add Lombok annotations for User entity to reduce boilerplate

- Replaced manual getters/setters with @Getter and @Setter
- Simplified class structure using Lombok

* fixed return "post" to return "post/post"

* Created AdminController
Created templates/admin
-posts
-users
-settings
these are empty

* fixed typo

* Added simpel html code

* fixed typo

* Add OAuth with google and update UserRole and userPassword

* Refactor: subtracted lombok

* Use constructor-based dependency injection for PostService and userService

* Add @PreAuthorize annotations to AdminController methods for extra security

* Deleted unused import

* Add ownership and role-based access control to PostRESTController

Add helper method isNotOwnerOrAdmin for cleaner access control logic in PostRESTController

* Add ownership and role-based access control to EventRESTController

Add helper method isNotOwnerOrAdmin for cleaner access control logic in EventRESTController

* Deleted duplicates CatPhotoService and CatPhotoRepository

* Add security and ownership checks to UserRestController

- Restricted access to user data using @PreAuthorize
- Only admins can view all users
- Only the user themselves or an admin can update or delete user accounts
- Added isNotOwnerOrAdmin() helper method for reusable access logic
- Integrated Authentication to fetch current user from the session

* Secure ReminderRestController with role and ownership checks

- Added @PreAuthorize to all Reminder API endpoints
- Implemented access control to ensure only the owner or an admin can view, update, or delete a reminder
- Linked Reminder entity to User (added user field with @manytoone)
- Created getUser() and setUser() in Reminder
- Added ReminderRepository method findAllByUser(User user)
- Added getRemindersByUser(...) method in ReminderService

* Secure RecommendationRESTController with ownership and role-based access control

* Secure EventParticipantRestController with role and ownership restrictions

* Secure CatRestController with role-based and ownership checks

- Added @PreAuthorize to all endpoints for authentication and role control
- Ensured only the owner or ADMIN can view, update or delete a cat
- Injected Authentication and UserService to identify current user
- Added ownership helper method isNotOwnerOrAdmin(Cat, User)
- Replaced setUser(...) with setUserCatOwner(...) to match entity structure
- Connected controller with new CatService method getAllCatsByUser(User)
- Fixed minor logic bug: update now verifies ownership against existing entity, not input

* Fix user password handling in User entity

- Updated getUserPassword() to return actual password value
- Corrected variable name in setUserPassword() to avoid undefined 'password'
- Ensures password is properly encoded using BCrypt before storing

* Changed location for filters to security

* fixed event and post names

* fixed google login

* Changes by Malva

* fixed .env

* Changes by Malva

* test fix application-dev.properties

* Implement custom user authentication via CustomUserDetails and improved login logging

- Added CustomUserDetails class implementing UserDetails with role-based authorities
- Implemented CustomUserDetailsService to load users from the database using UserRepository
- Included logging for failed login attempts with unknown usernames
- Ensured repository method findByUserName(String userName) exists for authentication

* ✨ Hash password before saving user

Added PasswordEncoder injection to UserService and applied password hashing when creating a new user. Ensures stored passwords are securely encoded

* feat(admin): add error handling and logging for user deletion

- Wrapped deleteUser method in a try-catch block to handle exceptions during deletion.
- Redirects to admin user page with error query param if deletion fails.
- Added SLF4J logger for logging error messages.

Improves robustness and user feedback in admin panel.

* Add error handling for admin post listing to handle service exceptions gracefully

* måsvinge..........

* Add basic admin error view for graceful error handling

* fix(post): added null-check for authenticated user in createPost

* fix(post): prevent user ownership override in updatePost

* fix(post): sanitize PATCH input to prevent user override

* fix(cat): prevent NullPointerException in isNotOwnerOrAdmin by adding null check

* fix: @PreAuthorize("hasRole('ADMIN')") in AdminController changeUserRole

* add error handling for deletepost and showallusers

* add null check before accessing post.getUser()

* fixed Inefficient password encoder instantiation

* fixed: changed return null in getuserpassword to not expose hashed password

added checkpassword

* fixed blank line 133

* tried to fix google login error 401

* Changes by Malva

* feat(security): improve OAuth2 login, remember-me & logout handling

- Added remember-me support with 1-week token validity
- Improved logout by clearing session and cookies
- OAuth2 login now redirects based on role (admin vs user)
- Google OAuth2 endpoints and client credentials wired via .env and application-dev.properties
- Configured issuer-uri for dynamic metadata resolution

* Improve security config: added remember-me, OAuth2 success handler & env-based key

- Added remember-me support with environment-based key for better user experience
- Refined logout configuration (invalidates session and removes JSESSIONID)
- Customized OAuth2 login success handler to redirect based on user role
- Cleaned up bean definitions and applied secure password encoder strategy

* Improve security config: OAuth2 success handler, remember-me fallback key, and safer logout

- Added role-based redirection after OAuth2 login (admin vs. user)
- Improved remember-me config with fallback SecureRandom key if env is missing
- Enhanced logout: invalidates session & deletes cookies
- Ensured all public paths are accessible without auth

* +spring.config.import=file:.env[.properties]

* created admin dashboard
tried to fix build

* test spring.config.import=optional:file:.env[.properties]

* fixed: Missed admin authorization checks on certain endpoints

* fixed: class-level ADMIN role restriction in AdminController

* Added necessary error handling for the updateUser flow

* fixed: Be aware of “remember-me” key resets

fix(security): improve SecurityConfig readability and remove warnings

* fixed UserRole enum

* fixed trim in user

---------

Co-authored-by: Malva Malmgren <malva.malmgren@gmail.com>
* Add logout button to header.html

* Add login button to header.html

* Database fix

* Add LoginViewController

* Change login redirect, add login/out button in header.html

* Cleanup
* rebase from main

* Fixed unnecessary titles in header.html

* Fixed coderabbits nitpicks

* Fixed merge conflicts
* Translate README to English to trigger GitHub Actions workflow

* Expand README with project features and development approach

* Re-run CI to clear required check state
* Add DTOs for Cat

* Add CatMapper for converting between entity and DTOs

* Add GraphQL schema definitions for Cat and update Schema.graphqls

* Add CatNotFoundException

* Add controller for Cat.graphqls

* Improve CatMapper readability and trim input values

* Comment out unused scalar DateTime in schema.graphqls

* Rename package DTO to dto

* Replace temporary user exception in CatMapper with NotFoundException

* Add Validated to controller and replace CatNotFoundException with NotFoundException

* Handle NotFoundException in deleteCat method

* Trim input values in CatMapper when creating a cat

* Add userId to CatOutputDTO
* Add create post form and favicon.ico

* Implement post view update and delete

* Implement event view update and delete, with custom LocalDateTimeFormatter

* Change header, add dependency for markdown, add about page

* Add homepage link for Catinder header text

* Update main.css

* Add create button to post-list.html and event-list.html

* Update index.html and add create button to cats-list.html

* Implement user save on first google login including email, random username and full name

* Fix username bug on login and logout user on account deletion

* Fix entity relations, add view functionalities for cats, posts, events

* Cleanup

* Fix after rebase

* Minor fixes
* Add Event GraphQL setup with custom scalar and schema definitions

* Rename EventUpdateInput to EventUpdate in schema and event.graphqls

* Commit with unfinished event-related classes

* Rename package Mapper to mapper and DTO to dto

* Temporarily comment out code to resolve merge conflict with main

* Revert to LocalDateTime in Event entity

* Add validation annotations to EventInputDTO

* Add eventPlanner field to EventOutputDTO

* Convert to/from OffsetDateTime in EventMapper

* Complete all main queries and mutations in EventGraphQLController

* Uncomment userEventPlanner in event.graphqls

* Remove unused import

* Fix indentation in the closing braces of the conditional block

* Improve EventMapper timezone handling, add @Valid to updateEvent, and handle delete exceptions

* Add null check for user in createEvent to prevent nullPointerException.

* Document intentional time zone discard in EventMapper

* Remove unused import

* Add error handling and null checks in EventGraphQLController methods
* Add GraphQL schema for Reminder

* Add DTOs and Mapper for Reminder

* Add GraphQL controller for reminder

* Update Reminder update mutation to include userId and catId

* Switch to OffsetDateTime in DTO and add mapper conversion

* Add Flyway V6 migration with new constraints and column updates

* Add hashCode, equals and toString

* Add validation checks

* Add validation to field

* Add null checks

* Fix flyway migration problem
* Add GraphQL schema for EventParticipant

* Create DTOs and mapper for EventParticipant

* Add GraphController and create new methods in service for EventParticipant

* Fix GraphQL mutations for updating and deleting EventParticipants

* Enhance EventParticipantUpdateDTO with validation, constructors, and utility methods

* Refactor create method, rename service/mapper, add getByUserName query

* Add constructors, equals/hashCode/toString, and validation to InputDTO

* Add null check in toDTO method in EventParticipantMapper

* Improve delete and update logic in EventParticipantService

* Rename getEventParticipantByName to getEventParticipantByUserName and make delete return nullable

* Add equals, hashCode, and toString to EventParticipantOutputDTO

* Simplify equals and hashCode in EventParticipantUpdateDTO for consistency

* Remove 2 unused imports

* Add null checks for DTO, User, and Event in EventParticipantMapper methods

* Remove unused UserService and EventService from EventParticipantService

* Add duplicate check to updateParticipant to prevent user-event conflicts

* Improve duplicate check in updateParticipant to prevent conflicting user-event combinations

* Add setting to disable session persistence
JenDevs and others added 4 commits April 16, 2025 22:58
* Add GraphQL schema for Post

* Add DTOs and mapper for Post

* Add GraphQlController for Post

* Convert LocalDateTime to OffsetDateTime in PostMapper.toDTO to match GraphQL schema

* Add hashCode, toString and equals

* Add hashCode, toString and equals

* Update schema for PostOutputDTO and postImageUrl

* Add input and ID validation

* Remove extra spaces

* Add null checks
…sed access (#32)

* refactor(user): migrate to DTO-based architecture and enforce role-based access

- Replaced direct entity usage in UserRestController with UserInputDTO, UserUpdateDTO, and UserOutputDTO
- Updated UserService to handle all logic using DTOs and UserMapper
- Extended UserRepository with custom query methods for user search and filtering
- Enforced role-based access using @PreAuthorize and ownership checks in REST endpoints
- Improved validation in UserMapper for email formats
- Prepared system for Google-only login

* feat(mapper): finalize UserMapper with full DTO conversion and inline validation

- Added conversions between UserOutputDTO, UserInputDTO, UserUpdateDTO, and User
- Centralized validation logic (e.g. email format) inside updateUserFromDto()
- Documented update strategy to clarify mapper-based validation
- Ensured null safety and strict DTO mapping across layers

* fix(auth): add null-safety to isNotOwnerOrAdmin check in UserRestController

- Prevented potential NullPointer

* fix(security): restrict changeUserRole to ADMIN users only

- Added role-based check in UserService.changeUserRole
- Prevents unauthorized users from modifying role assignments
- Mitigates risk of privilege escalation

* fix(user): ensure atomic user creation with DB constraints and exception handling

- Replaced pre-checks for email/username duplicates with try-catch around userRepository.save()
- Added support for handling DataIntegrityViolationException to prevent race conditions
- Improves reliability of user creation under concurrent requests

* feat(user): enforce unique constraints on userEmail and userName at DB level

- Added @column(unique = true) on userEmail and userName fields in User entity
- Ensures database-level enforcement of uniqueness
- Complements service-layer exception handling for safe concurrent user creation

* fix(admin): finalize DTO integration and secure role change logic

- Fully replaced entity usage with UserOutputDTO and UserUpdateDTO
- Aligned with UserService methods and UserMapper conversions
- Secured changeUserRole via authenticated user context
- Improved stability, null-safety, and maintainability in admin panel

* Changes admin/logs to admin/dashboard since logs does not exist yet

* Added missing methods to UserService class

* fixed missed return statement

* fixed typo

* added javadoc and fixed method

* refactor(security): remove custom login and password handling for Google-only auth

- Removed UserDetailsService and password encoder beans
- Simplified SecurityConfig to rely solely on Google OAuth2 login
- Ensured logout and remember-me support remain intact

* refactor(mapper): complete and validate all user DTO/entity mappings

- Added bidirectional mapping between User, UserInputDTO, UserOutputDTO, and UserUpdateDTO
- Implemented outputToUpdateDTO for edit forms
- Added null checks and email validation

* refactor(user): ensure consistent field mapping for DTOs and entity

- Removed any lingering mismatch in User entity
- Confirmed 1:1 mapping between User and all DTOs
- Fixed setUserId to reference correct field

* refactor(view): connect UserViewController to DTO-based service layer
added
user-edit
user-error

* refactor(security): convert CustomUserDetails to Java record

* typo

* fix(graphql): resolve type mismatches by refactoring UserGraphQLController to use DTOs

* coderabbit nitpicks:
Remove unused validation method
Remove unnecessary UserMapper parameter from constructor

* Refactor UserViewController update and delete methods

- Replaced old PUT method using User entity with a correct version using UserUpdateDTO
- Fixed method nesting issue and removed broken @PostMapping inside @PutMapping
- Improved error handling and form binding for user updates
- Renamed and separated deleteUser methods:
  - deleteUserFromList (POST) for admin UI
  - deleteOwnAccount (DELETE) for self-deletion with session clearing
- Ensured consistent use of DTOs instead of entities in the controller

* Fix: Replace deprecated method in GlobalControllerAdvice

- Replaced call to getUserByUserName(...) with findUserByUserName(...)
  to align with updated service structure
- Ensures compatibility with refactored UserService using DTO separation

* Refactor: Use UserUpdateDTO in CustomOAuth2UserService

- Replaced usage of updateUser(Long, User) with updateUser(Long, UserUpdateDTO)
- Prevents direct entity updates and enforces DTO usage for consistency and security
- Aligns OAuth2 user sync logic with new application architecture

* Refactor: Secure and clean UserRestController with DTO structure

- Ensured all API responses use UserOutputDTO instead of exposing entities
- Replaced internal logic with findUserByUserName() for current user access
- Added getCurrentUser(Authentication) helper to avoid repetition
- Applied role-based access control with @PreAuthorize and owner/admin checks
- Followed consistent RESTful design for all endpoints

* Fix: Align UserViewController with updated UserService methods

- Replaced deprecated getUserById(...) with getUserDtoById(...)
- Replaced getUserByUserName(...) with findUserByUserName(...)
- Ensures compatibility with refactored service using DTO structure

* Refactor: Clean and restructure UserService with DTO separation and consistency

- Split entity and DTO responsibilities:
  - findUserById(), findUserByUserName(), findUserByEmail() for internal logic
  - getUserDtoById(), getUserDtoByUserName(), getUserDtoByEmail() for external API use
- Replaced entity-based update with DTO-driven updateUser(Long, UserUpdateDTO)
- Improved password handling with encoder in addUser(User)
- Ensured safe partial updates with map-based patch method
- Added validation for unique email/username across all update methods
- Standardized naming and logging for clarity and debugging

* Fix: Add JSON ignore annotations and finalize User entity for safe serialization

* Fix: Update EventViewController to match refactored UserService method names

* Fix: Update PostViewController to match refactored UserService method names

* Fix: Replace deprecated getUserByUserName with findUserByUserName in EventParticipantRestController

* Fix: Replace deprecated getUserByUserName with findUserByUserName in EventParticipantRestController

* typo

* Fix: Finalize CatRestController with secure user access and updated UserService integration

- Replaced deprecated getUserByUserName with findUserByUserName
- Implemented access control to allow only owners/admins to view or modify cats
- Secured all endpoints with proper role-based authorization
- Clean and RESTful responses (200, 201, 204, etc.)

* Refactor: Clean up AdminController by removing redundant mapping and fixing model binding

* Fix: getUserById to findUserById

* Fix: getUserById to findUserById

* Fix: Correct method for getUserById in GraphQL controller

* Fixed error message

* Resolved MVC view

* fixed get to find method

* typo

* added javadoc

* nitpicks

* deleted user-edit and user-error

* fixed
* Add CatPhoto schema and catphoto.graphqls

* Add DTOs and mapper for CatPhoto

* Add validation to catPhotoCaption field

* Fix schema method name from etallCatPhot to getAllCatPhotos

* Add GraphQlController for CatPhoto

* Use OffsetDateTime in CatPhotoOutputDTO and convert from LocalDateTime in mapper

* Add constructor, equals, hashCode, and toString

* Correct field name in toString (catPhotoName to catPhotoCaption)

* Add constructor, equals, hashCode and toString

* Rename GraphQL param to catPhotoId and update argument mapping

* Improve error messages and add not found check to delete

* Remove one unused import

* Refactor updateCatPhoto logic
* Fix create event, secure CSRF, and add GetMapping for delete for consistency

* Replace error-page.html with error.html

* Fix header buttons

* Add catPhoto slideshow for index.html

* Add security context refresh on userRole update, and link to admin dashboard

* Updated cat slideshow and admin dashboard

* Add handle cats button with userRole check for index page

* Fix after rebase

* Cleanup

* Fix AuthenticationToken in UserViewController PutMapping
JenDevs and others added 13 commits April 20, 2025 19:07
* Add external cat image API with view

* Remove unused CatImageDto class

* Add menu link to Cat API image page

* Style Cat API page to match the rest of the site

* Removed extra space and rename test method for clarity

* Add API key support, error handling and fallback to CatImageService

* Improve CatImageService for missing API key handling and add dependency

* Add autowire annotation

* Configure CATAPI_KEY for dev and CI, update CatImageService with logging and base path

* Remove @RequestMapping("/catimage") from CatImageController

* Limit CATAPI_KEY exposure to Maven step in CI for improved security
* Created comment entity

* Created comment dto input and output

* Created commentmapper

* Created CommentRepository

* Created CommentService

* Created CommentRestController

* Updated

* basic html for comments under posts + forms

* Refactor: Improved comment feature with null checks, role check fixes, and view logic

* Created graphql

* updated comment.graphql

* omg jag ångrar find metoden
* Add GraphQL schema for recommendation

* Add DTOs and mapper for recommendation

* Add graphqlcontroller for recommendation

* Add userId and catId to update input, rename file to .graphqls

* Adjust line break for readability

* Add validation to fields

* Add null checks

* Remove ! from deleteRecommendation

* Add safe delete handling for recommendation
* Added a search bar to the event page and implemented attributes for it.

* Removed unused imports
* Added Reminder funcionalities, connected reminders to cat in classes.

* rebase

* Created pages for reminder and removed placeholder reminder.html

* rebase

* Added List to find all user and remindertype.

* rebase some languages for reminder

* Removed unnecessary class.

* Removed unused import statement. Replaced with enhanced switch.

* Updated enhanced switch.

* Removed comment and updated the viewcontroller to only allow the user and admin to change their own reminder.

* Updating inconsistent exception handling in delete operation. Centralized and validated user retrieval

* Centralized and validated user retrieval in showAllReminders.

* Validated reminder object.

* Validated reminder object.

* Removed semicolon

* rebase html to fit the rest of the pages.

* rebase reminder to put in userID as hidden because validation would fail otherwise.

* Edited reminder to put in userID as hidden because validation would fail otherwise.

* Removed ID in thymeleaf

* Removed unnused header

* Added lang en

* Added logging for security events.

* Removed unnused design

* Added missing model attributes in validation error case.

* Removed comments.
* Limited the age for cats to 25. Sadge

* Limited to 10 breeds to pick from.

* Limited to 10 breeds to pick from in edit.

* Added CatGender as an enum, updated flyway migration as well.

* Refactored breed list to avoid duplication. added try-catch for enum conversion, fixed incorrect exception type used for validation errors

* Removed unused imports
#46)

* Fix participant add and view (by user/event), removed update feature from HTML/controller

* Validate empty userName and eventName before adding participant
* Updated languages, delete buttons and their layouts. Added, adapted and aligned view, edit and delete.

* Deleted comments and fixed html

* Updated notifications

* Updated language html
* refactor(user): migrate to DTO-based architecture and enforce role-based access

- Replaced direct entity usage in UserRestController with UserInputDTO, UserUpdateDTO, and UserOutputDTO
- Updated UserService to handle all logic using DTOs and UserMapper
- Extended UserRepository with custom query methods for user search and filtering
- Enforced role-based access using @PreAuthorize and ownership checks in REST endpoints
- Improved validation in UserMapper for email formats
- Prepared system for Google-only login

* feat(mapper): finalize UserMapper with full DTO conversion and inline validation

- Added conversions between UserOutputDTO, UserInputDTO, UserUpdateDTO, and User
- Centralized validation logic (e.g. email format) inside updateUserFromDto()
- Documented update strategy to clarify mapper-based validation
- Ensured null safety and strict DTO mapping across layers

* fix(auth): add null-safety to isNotOwnerOrAdmin check in UserRestController

- Prevented potential NullPointer

* fix(security): restrict changeUserRole to ADMIN users only

- Added role-based check in UserService.changeUserRole
- Prevents unauthorized users from modifying role assignments
- Mitigates risk of privilege escalation

* fix(user): ensure atomic user creation with DB constraints and exception handling

- Replaced pre-checks for email/username duplicates with try-catch around userRepository.save()
- Added support for handling DataIntegrityViolationException to prevent race conditions
- Improves reliability of user creation under concurrent requests

* feat(user): enforce unique constraints on userEmail and userName at DB level

- Added @column(unique = true) on userEmail and userName fields in User entity
- Ensures database-level enforcement of uniqueness
- Complements service-layer exception handling for safe concurrent user creation

* fix(admin): finalize DTO integration and secure role change logic

- Fully replaced entity usage with UserOutputDTO and UserUpdateDTO
- Aligned with UserService methods and UserMapper conversions
- Secured changeUserRole via authenticated user context
- Improved stability, null-safety, and maintainability in admin panel

* Changes admin/logs to admin/dashboard since logs does not exist yet

* Added missing methods to UserService class

* fixed missed return statement

* fixed typo

* added javadoc and fixed method

* refactor(security): remove custom login and password handling for Google-only auth

- Removed UserDetailsService and password encoder beans
- Simplified SecurityConfig to rely solely on Google OAuth2 login
- Ensured logout and remember-me support remain intact

* refactor(mapper): complete and validate all user DTO/entity mappings

- Added bidirectional mapping between User, UserInputDTO, UserOutputDTO, and UserUpdateDTO
- Implemented outputToUpdateDTO for edit forms
- Added null checks and email validation

* refactor(user): ensure consistent field mapping for DTOs and entity

- Removed any lingering mismatch in User entity
- Confirmed 1:1 mapping between User and all DTOs
- Fixed setUserId to reference correct field

* refactor(view): connect UserViewController to DTO-based service layer
added
user-edit
user-error

* refactor(security): convert CustomUserDetails to Java record

* typo

* fix(graphql): resolve type mismatches by refactoring UserGraphQLController to use DTOs

* coderabbit nitpicks:
Remove unused validation method
Remove unnecessary UserMapper parameter from constructor

* Refactor: Separate Cat entity from API using DTOs

* Refactor Cat API to use DTOs and secure ownership access

- Replaced direct Cat entity exposure with CatInputDTO, CatOutputDTO, and CatUpdateDTO
- Updated CatService to handle all logic using DTOs
- Centralized ownership checks and error handling
- Improved controller methods to use secure service methods only
- Ensured no entity is leaked directly to clients

* paus commit

* Refactor UserViewController update and delete methods

- Replaced old PUT method using User entity with a correct version using UserUpdateDTO
- Fixed method nesting issue and removed broken @PostMapping inside @PutMapping
- Improved error handling and form binding for user updates
- Renamed and separated deleteUser methods:
  - deleteUserFromList (POST) for admin UI
  - deleteOwnAccount (DELETE) for self-deletion with session clearing
- Ensured consistent use of DTOs instead of entities in the controller

* Fix: Replace deprecated method in GlobalControllerAdvice

- Replaced call to getUserByUserName(...) with findUserByUserName(...)
  to align with updated service structure
- Ensures compatibility with refactored UserService using DTO separation

* Refactor: Use UserUpdateDTO in CustomOAuth2UserService

- Replaced usage of updateUser(Long, User) with updateUser(Long, UserUpdateDTO)
- Prevents direct entity updates and enforces DTO usage for consistency and security
- Aligns OAuth2 user sync logic with new application architecture

* Refactor: Secure and clean UserRestController with DTO structure

- Ensured all API responses use UserOutputDTO instead of exposing entities
- Replaced internal logic with findUserByUserName() for current user access
- Added getCurrentUser(Authentication) helper to avoid repetition
- Applied role-based access control with @PreAuthorize and owner/admin checks
- Followed consistent RESTful design for all endpoints

* Fix: Align UserViewController with updated UserService methods

- Replaced deprecated getUserById(...) with getUserDtoById(...)
- Replaced getUserByUserName(...) with findUserByUserName(...)
- Ensures compatibility with refactored service using DTO structure

* Refactor: Clean and restructure UserService with DTO separation and consistency

- Split entity and DTO responsibilities:
  - findUserById(), findUserByUserName(), findUserByEmail() for internal logic
  - getUserDtoById(), getUserDtoByUserName(), getUserDtoByEmail() for external API use
- Replaced entity-based update with DTO-driven updateUser(Long, UserUpdateDTO)
- Improved password handling with encoder in addUser(User)
- Ensured safe partial updates with map-based patch method
- Added validation for unique email/username across all update methods
- Standardized naming and logging for clarity and debugging

* Fix: Add JSON ignore annotations and finalize User entity for safe serialization

* Fix: Update EventViewController to match refactored UserService method names

* Fix: Update PostViewController to match refactored UserService method names

* Fix: Replace deprecated getUserByUserName with findUserByUserName in EventParticipantRestController

* Fix: Replace deprecated getUserByUserName with findUserByUserName in EventParticipantRestController

* typo

* Fix: Finalize CatRestController with secure user access and updated UserService integration

- Replaced deprecated getUserByUserName with findUserByUserName
- Implemented access control to allow only owners/admins to view or modify cats
- Secured all endpoints with proper role-based authorization
- Clean and RESTful responses (200, 201, 204, etc.)

* Refactor: Clean up AdminController by removing redundant mapping and fixing model binding

* Fix: getUserById to findUserById

* Fix: getUserById to findUserById

* Fix: Correct method for getUserById in GraphQL controller

* Fixed error message

* Resolved MVC view

* fixed get to find method

* typo

* added javadoc

* nitpicks

* Refactor CatMapper to match style of other mappers

* Organized CatService with internal and external methods

* Added findByCatNameContainingIgnoreCase to repository

* restructured to work with dto

* changed notFoundException to IllegalArgumentException

* created InvalidInputException

* updated exception

* fixing error after merge

* fixing error "Cannot resolve method 'getCatById' in 'CatService'"

* nitpick in GlobalExceptionHandler

* helvete

* after merge

* fixed build fail

* nitpick

* added shit back

* fixed userservice

* fixed catservice after merge

* fixed cats to dto

* fixes after merge

* fixed: Security in view and graph
* Add reminder notification with icon color

* Add contact site

* Cleanup

* Add /contact to filter chain

* Remove /contact from filter chain, cleanup

* Remove unused imports

* Fix after rebase

* Comment out tests

* Add /contact

* Remove plugin for flyway repair

* Cleanup Contact
…nto rename-globalexceptionhandler

# Conflicts:
#	src/main/java/org/example/springboot25/exceptions/GlobalRESTExceptionHandler.java
@ehottinen
ehottinen dismissed stale reviews from JenDevs and malvamalmgren via cc7014b April 22, 2025 14:28
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.

5 participants