User API Implementation: Profile Management & Approval Revocation
In this article, we will delve into the implementation of the User API, focusing on enhancing user profile management and incorporating essential features like user approval revocation. This comprehensive guide will walk you through the key aspects of the API development, covering everything from the functional description to the detailed requirements, security considerations, and testing checklists. Whether you are a seasoned developer or just starting, this article provides valuable insights into building robust and user-centric APIs.
Functional Description
The primary goal is to add functionality for user profile management and user approval revocation. This involves implementing four key API endpoints to support both front-end profile page development and back-end administrative functions. Let's explore the functionalities in detail:
1. Revoke User Approval (Admin-Only)
As part of the user management enhancements, the revoke user approval feature is crucial for administrators. This functionality allows administrators to change the status of an approved user back to rejected. This is essential for maintaining the integrity and security of the platform. The API endpoint PATCH /admin/users/{userId}/reject is designed to handle this operation efficiently.
-
Key features include:
- Restricting access to only users with the ADMIN role using
@PreAuthorize("hasRole('ADMIN')"). - Updating the
Userstatus fromAPPROVEDtoREJECTED. - Returning a
RejectUserResponseDTO to provide comprehensive feedback.
- Restricting access to only users with the ADMIN role using
-
Exception handling is a critical aspect, with specific measures in place to manage scenarios such as:
- Attempts to reject an already
REJECTEDuser. - Cases where the
userIddoes not exist. - Attempts to transition a user from
PENDINGtoREJECTED(theapproveendpoint should be used instead).
- Attempts to reject an already
2. Get User Information (Common)
Every user needs a way to view their profile information. The get user information API fulfills this need by allowing users to retrieve their details. This API is designed to be accessible to both ADMIN and EXECUTOR roles, ensuring that all users can manage their profiles effectively. The endpoint GET /users/me is dedicated to this function.
-
Key aspects of this API include:
- Creating a new
UserProfileControllerto manage the/users/mepath. - Utilizing JWT tokens to extract the
userIdfrom the authentication context (@AuthenticationPrincipal CustomUserDetails). - Reusing the existing
GetUserDetailResponseDTO to maintain consistency.
- Creating a new
-
Security is paramount, with the following exception handling implemented:
- Handling unauthenticated users (401 status code).
- Addressing situations where user information cannot be found (404 status code).
3. Update User Information (Common)
The ability to update user information is a vital part of user profile management. This API enables users to modify their profile details such as email, phone number, and department. Similar to the get user information API, this functionality is available to both ADMIN and EXECUTOR roles. The endpoint for this operation is PATCH /users/me.
-
Key features of this API include:
- Creating a new
UpdateMyInfoRequestDTO to handle request parameters (excluding roles). - Reusing the
UpdateUserResponseDTO for the response. - Limiting modifiable fields to
email,phone, anddepartment. - Preventing users from modifying
role,status,username, andname(these are admin-controlled).
- Creating a new
-
Comprehensive input validation is in place, including:
- Email format validation using
@Email. - Phone number format validation using
@Pattern. - Ensuring email uniqueness, excluding the user's current email.
- Email format validation using
-
Exception handling includes:
- Managing email duplication errors (409 Conflict).
- Handling invalid input formats (400 Bad Request).
4. Change Password (Common)
Security is a top priority, and the ability to change password is a critical feature for maintaining user account security. This API allows users to securely update their passwords. It is accessible to both ADMIN and EXECUTOR roles, ensuring that all users can protect their accounts. The dedicated endpoint for this is PATCH /users/me/password.
-
Key components of this API include:
- Creating a new
UpdatePasswordRequestDTO containingcurrentPasswordandnewPassword. - Introducing a new
UpdatePasswordResponseDTO with a message field. - Implementing rigorous password validation logic.
- Creating a new
-
Password validation includes:
- Verifying the current password using
PasswordEncoder.matches(). - Enforcing new password format requirements (minimum 8 characters, including letters, numbers, and special characters) using
@Pattern. - Preventing the use of the same password.
- Verifying the current password using
-
Security measures also include:
- Encrypting the new password before saving it using
PasswordEncoder.encode().
- Encrypting the new password before saving it using
-
Exception handling is comprehensive:
- Handling incorrect current passwords (400 Bad Request).
- Managing password format errors (400 Bad Request).
- Preventing the use of the same password as the current one (400 Bad Request).
Implementation Goals
The overarching objective is to deliver a set of user-centric APIs that enhance profile management and security. Let's outline the implementation goals in detail:
Providing Administrative Control
The primary goal is to empower administrators with the ability to revoke user approvals. This feature is crucial for maintaining platform integrity and managing user access effectively. By implementing this functionality, administrators can easily revert approved users to a rejected status, ensuring that only authorized individuals have access to the system. This level of control is essential for platforms dealing with sensitive data or requiring strict access management protocols.
Empowering User Profile Management
Another key objective is to enable all users, regardless of their role (ADMIN or EXECUTOR), to manage their profiles efficiently. This includes providing the ability to view and modify their personal information, such as contact details and department affiliations. By giving users control over their profiles, the system promotes user engagement and satisfaction. This self-service approach also reduces the administrative burden, as users can independently update their information as needed.
Ensuring Password Security
Security is paramount, and the implementation aims to provide users with a secure mechanism to change their passwords. This involves implementing robust validation checks and encryption protocols to safeguard user credentials. By allowing users to update their passwords easily and securely, the system minimizes the risk of unauthorized access and data breaches. This feature is critical for maintaining user trust and ensuring the overall security posture of the platform.
Building RESTful APIs
A core goal is to construct RESTful APIs that adhere to industry best practices. This includes designing intuitive endpoints, using standard HTTP methods, and returning appropriate response codes. By following RESTful principles, the APIs become more predictable, easier to use, and integrate seamlessly with front-end applications. The adoption of RESTful architecture also promotes scalability and maintainability, making it easier to evolve the APIs over time.
Intuitive API Design
The API design will focus on creating a user-centric experience, particularly by utilizing the /users/me pattern. This approach makes the APIs more intuitive and easier to understand. By adopting this pattern, developers can quickly grasp the purpose of the endpoints and integrate them into their applications with minimal effort. This user-centric design philosophy ensures that the APIs are not only functional but also developer-friendly, contributing to a smoother development process and a better overall user experience.
Detailed Requirements
1. Revoke User Approval API
The Revoke User Approval API is a critical feature for administrative control, allowing administrators to revert approved users to a rejected state. The detailed requirements for this API are as follows:
- Endpoint:
PATCH /admin/users/{userId}/reject - Authorization: Accessible only to users with the ADMIN role (
@PreAuthorize("hasRole('ADMIN')")) - Functionality: Updates the User status from APPROVED to REJECTED
- Response DTO: Uses a newly created
RejectUserResponseDTO - Exception Handling:
- Handles scenarios where the user is already in the REJECTED state
- Manages cases where the provided userId does not exist
- Prevents direct transitions from PENDING to REJECTED (approval revocation is required first)
2. Get My Information API
The Get My Information API empowers users to view their profile details, fostering better user management and transparency. The detailed requirements include:
- Endpoint:
GET /users/me - Controller: Managed by a newly created
UserProfileControllerdedicated to the/users/mepath - Authorization: Accessible to both ADMIN and EXECUTOR roles
- Functionality: Retrieves the user's information based on the userId extracted from the JWT token (
@AuthenticationPrincipal CustomUserDetails) - Response DTO: Reuses the existing
GetUserDetailResponseDTO - Security: Leverages
SecurityContextto obtain authentication information - Exception Handling:
- Addresses unauthenticated user requests (401)
- Handles scenarios where the user information cannot be found (404)
3. Update My Information API
The Update My Information API is essential for user empowerment, enabling users to modify their profiles and keep their information current. The detailed requirements are:
- Endpoint:
PATCH /users/me - Authorization: Accessible to both ADMIN and EXECUTOR roles
- Request DTO: Utilizes a newly created
UpdateMyInfoRequestDTO containing email, phone, and department fields (excluding role) - Response DTO: Reuses the existing
UpdateUserResponseDTO - Modifiable Fields: Allows updates to email, phone, and department
- Non-Modifiable Fields: Restricts modifications to role, status, username, and name (admin-controlled)
- Input Validation:
- Email format validation using
@Email - Phone number format validation using
@Pattern - Email uniqueness validation, excluding the user's current email
- Email format validation using
- Exception Handling:
- Manages email duplication conflicts (409 Conflict)
- Handles invalid input formats (400 Bad Request)
4. Change Password API
The Change Password API is crucial for maintaining user account security, providing a secure way for users to update their credentials. The detailed requirements are:
- Endpoint:
PATCH /users/me/password - Authorization: Accessible to both ADMIN and EXECUTOR roles
- Request DTO: Employs a newly created
UpdatePasswordRequestDTO including currentPassword and newPassword fields - Response DTO: Introduces a new
UpdatePasswordResponseDTO with a message field - Password Validation:
- Current password verification using
PasswordEncoder.matches() - New password format validation (minimum 8 characters, including letters, numbers, and special characters) using
@Pattern - Prevention of using the same password
- Current password verification using
- Security: Encrypts the new password before saving it using
PasswordEncoder.encode() - Exception Handling:
- Manages incorrect current password entries (400 Bad Request)
- Handles password format errors (400 Bad Request)
- Prevents the use of the same password as the current one (400 Bad Request)
- Frontend Validation: The
newPasswordConfirmfield is validated on the frontend for enhanced user experience
Common Implementation Aspects
Controller Structure
To ensure a clean and maintainable codebase, a new UserProfileController will be created to manage the /users/me path. Additionally, the existing AdminController will be modified to include the user approval revocation method.
Service Logic Implementation
The service layer will encompass the core business logic for user management. The following methods will be implemented:
AdminService.rejectUser(): Handles the logic for revoking user approval.UserService.getMyInfo(): Retrieves user information for profile viewing.UserService.updateMyInfo(): Manages user profile updates.UserService.changePassword(): Implements the password change functionality.
Exception Handling
To provide robust error management, the following exception classes will be utilized:
NotFoundException: Handles scenarios where a resource is not found.BadRequestException: Manages invalid or malformed requests.ConflictException: Addresses situations where a request conflicts with the current state of the resource.
API Documentation
Comprehensive API documentation is crucial for usability and maintainability. The API 명세서 will be updated to reflect the new functionalities, and Swagger documentation will be added or modified to ensure accuracy and completeness.
Testing
Thorough testing is essential to ensure the reliability and correctness of the APIs. Postman will be used to conduct comprehensive testing of all endpoints, validating both successful responses and error scenarios.
Security Considerations
1. JWT Token-Based Authentication
All /users/me APIs will require JWT tokens for authentication. The @AuthenticationPrincipal annotation will be used to extract the userId from the token, ensuring that only authenticated users can access their information and perform actions.
2. Role-Based Access Control
Role-based access control will be enforced to protect sensitive operations. The @PreAuthorize("hasRole('ADMIN')") annotation will restrict access to administrative APIs, ensuring that only users with the ADMIN role can perform actions such as revoking user approval. Common APIs will be accessible to all authenticated users, regardless of their role.
3. Secure Password Management
Password security is a top priority. The following measures will be implemented:
- Current password verification using
PasswordEncoder.matches()to ensure that users can only change their passwords if they know their current one. - New password encryption using
PasswordEncoder.encode()before saving it to the database, protecting passwords from unauthorized access. - Frontend validation of password confirmation to improve user experience and reduce backend processing.
4. Limited Information Modification
To prevent unauthorized modifications, users will only be allowed to update certain fields in their profiles. The role and status fields will be restricted to admin-only modifications, ensuring that users cannot elevate their privileges or change their status without administrative approval.
5. Input Validation
Comprehensive input validation will be implemented to prevent malicious data from being processed. This includes:
- Using
@Validannotation to enable automatic validation of request bodies. - Validating email formats, phone number formats, and password complexity using annotations such as
@Emailand@Pattern. - Performing email uniqueness checks to prevent duplicate email addresses within the system.
Testing Checklist
Revoke User Approval
- [ ] Verify that the status changes from APPROVED to REJECTED.
- [ ] Ensure that an exception is thrown if the user is already REJECTED.
- [ ] Confirm that an exception is thrown for non-existent
userId. - [ ] Verify that non-ADMIN users receive a 403 Forbidden error.
Get My Information
- [ ] Verify successful retrieval of user information using a JWT token.
- [ ] Ensure a 401 Unauthorized error for unauthenticated requests.
Update My Information
- [ ] Verify successful updates to email, phone, and department fields.
- [ ] Ensure a 409 Conflict error for email duplication.
- [ ] Confirm a 400 Bad Request error for invalid input formats.
- [ ] Verify that the role field cannot be modified.
Change Password
- [ ] Verify successful password change.
- [ ] Ensure a 400 Bad Request error for incorrect current password.
- [ ] Confirm a 400 Bad Request error for invalid password format.
- [ ] Verify a 400 Bad Request error if the new password is the same as the current password.
- [ ] Ensure successful login with the new password.
Conclusion
The implementation of these User APIs is a significant step towards enhancing user profile management and overall system security. By adhering to the detailed requirements, security considerations, and testing checklists outlined in this article, developers can ensure the creation of robust, user-friendly, and secure APIs. These APIs will not only provide essential functionalities for administrators and users but also contribute to a more efficient and trustworthy platform. For more information on RESTful API design and best practices, visit REST API Tutorial.