Skip to content

Commit

Permalink
Task 62 : Add missing Java Doc for product service
Browse files Browse the repository at this point in the history
  • Loading branch information
Rapter1990 committed Jul 21, 2024
1 parent b2b1617 commit b72db61
Show file tree
Hide file tree
Showing 18 changed files with 254 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,27 @@
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

/**
* Feign client interface named {@link UserServiceClient} for interacting with the User Service.
* Provides methods to validate tokens and retrieve authentication information.
*/
@FeignClient(name = "userservice", path = "/api/v1/users", configuration = FeignClientConfig.class)
public interface UserServiceClient {

/**
* Validates the provided token by making a request to the user service.
*
* @param token the token to validate
*/
@PostMapping("/validate-token")
void validateToken(@RequestParam String token);

/**
* Retrieves authentication information based on the provided token.
*
* @param token the token to use for retrieving authentication information
* @return {@link UsernamePasswordAuthenticationToken} containing authentication details
*/
@GetMapping("/authenticate")
UsernamePasswordAuthenticationToken getAuthentication(@RequestParam String token);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,19 @@
import java.util.Collection;
import java.util.Map;

/**
* Configuration class named {@link FeignClientConfig} for setting up Feign client components.
* Configures custom error handling, object mapping, and decoding for Feign clients.
*/
@Slf4j
@Configuration
public class FeignClientConfig {

/**
* Provides a custom {@link ObjectMapper} bean configured with Jackson modules.
*
* @return a configured {@link ObjectMapper} instance
*/
@Bean
public ObjectMapper objectMapper() {
ObjectMapper objectMapper = new ObjectMapper();
Expand All @@ -42,11 +51,22 @@ public ObjectMapper objectMapper() {
return objectMapper;
}

/**
* Provides a custom {@link Decoder} bean for Feign clients.
*
* @param objectMapper the {@link ObjectMapper} to use for decoding
* @return a {@link Decoder} instance
*/
@Bean
public Decoder feignDecoder(ObjectMapper objectMapper) {
return new CustomDecoder(objectMapper);
}

/**
* Provides a custom {@link ErrorDecoder} bean for Feign clients.
*
* @return a {@link ErrorDecoder} instance
*/
@Bean
public ErrorDecoder errorDecoder() {
return new CustomErrorDecoder();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,18 +24,36 @@

import java.util.List;

/**
* Security configuration class named {@link SecurityConfig} for setting up security filters and policies.
* Configures HTTP security settings, CORS, CSRF, and session management.
*/
@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
@EnableMethodSecurity
@Slf4j
public class SecurityConfig {

/**
* Configures the session authentication strategy.
*
* @return a {@link SessionAuthenticationStrategy} instance
*/
@Bean
protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
return new RegisterSessionAuthenticationStrategy(new SessionRegistryImpl());
}

/**
* Configures the security filter chain for HTTP requests.
*
* @param httpSecurity the {@link HttpSecurity} to configure
* @param customBearerTokenAuthenticationFilter the custom filter for token authentication
* @param customAuthenticationEntryPoint the custom entry point for authentication errors
* @return a configured {@link SecurityFilterChain} instance
* @throws Exception if an error occurs while configuring security
*/
@Bean
public SecurityFilterChain filterChain(
final HttpSecurity httpSecurity,
Expand All @@ -60,6 +78,11 @@ public SecurityFilterChain filterChain(
return httpSecurity.build();
}

/**
* Provides CORS configuration for the application.
*
* @return a {@link CorsConfigurationSource} instance
*/
private CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(List.of("*"));
Expand All @@ -70,6 +93,11 @@ private CorsConfigurationSource corsConfigurationSource() {
return source;
}

/**
* Provides a {@link PasswordEncoder} bean for encoding passwords.
*
* @return a {@link PasswordEncoder} instance
*/
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@
import java.security.PrivateKey;
import java.security.PublicKey;

/**
* Configuration class named {@link TokenConfigurationParameter} for token parameters.
* Provides access to token expiration settings and cryptographic keys.
*/
@Getter
@Configuration
public class TokenConfigurationParameter {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
* REST controller named {@link ProductController} for managing products.
* Provides endpoints to create, read, update, and delete products.
*/
@RestController
@RequestMapping("/api/v1/products")
@RequiredArgsConstructor
Expand All @@ -37,6 +41,12 @@ public class ProductController {
private final CustomPageToCustomPagingResponseMapper customPageToCustomPagingResponseMapper =
CustomPageToCustomPagingResponseMapper.initialize();

/**
* Creates a new product.
*
* @param productCreateRequest the request payload containing product details
* @return a {@link CustomResponse} containing the ID of the created product
*/
@PostMapping
@PreAuthorize("hasAnyAuthority('ADMIN')")
public CustomResponse<String> createProduct(@RequestBody @Valid final ProductCreateRequest productCreateRequest) {
Expand All @@ -47,6 +57,12 @@ public CustomResponse<String> createProduct(@RequestBody @Valid final ProductCre
return CustomResponse.successOf(createdProduct.getId());
}

/**
* Retrieves a product by its ID.
*
* @param productId the ID of the product to retrieve
* @return a {@link CustomResponse} containing the product details
*/
@GetMapping("/{productId}")
@PreAuthorize("hasAnyAuthority('ADMIN', 'USER')")
public CustomResponse<ProductResponse> getProductById(@PathVariable @UUID final String productId) {
Expand All @@ -59,6 +75,12 @@ public CustomResponse<ProductResponse> getProductById(@PathVariable @UUID final

}

/**
* Retrieves a paginated list of products based on the paging request.
*
* @param productPagingRequest the request payload containing paging information
* @return a {@link CustomResponse} containing the paginated list of products
*/
@GetMapping
@PreAuthorize("hasAnyAuthority('ADMIN', 'USER')")
public CustomResponse<CustomPagingResponse<ProductResponse>> getProducts(
Expand All @@ -73,6 +95,13 @@ public CustomResponse<CustomPagingResponse<ProductResponse>> getProducts(

}

/**
* Updates an existing product by its ID.
*
* @param productUpdateRequest the request payload containing updated product details
* @param productId the ID of the product to update
* @return a {@link CustomResponse} containing the updated product details
*/
@PutMapping("/{productId}")
@PreAuthorize("hasAnyAuthority('ADMIN')")
public CustomResponse<ProductResponse> updatedProductById(
Expand All @@ -86,6 +115,12 @@ public CustomResponse<ProductResponse> updatedProductById(
return CustomResponse.successOf(productResponse);
}

/**
* Deletes a product by its ID.
*
* @param productId the ID of the product to delete
* @return a {@link CustomResponse} indicating successful deletion
*/
@DeleteMapping("/{productId}")
@PreAuthorize("hasAnyAuthority('ADMIN')")
public CustomResponse<Void> deleteProductById(@PathVariable @UUID final String productId) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,33 @@

import java.io.IOException;

/**
* Custom filter named {@link CustomBearerTokenAuthenticationFilter} for handling Bearer token authentication in HTTP requests.
* This filter extracts the Bearer token from the Authorization header,
* validates it, and sets the authentication context if the token is valid.
*/
@Slf4j
@Component
@RequiredArgsConstructor
public class CustomBearerTokenAuthenticationFilter extends OncePerRequestFilter {

private final UserServiceClient userServiceClient;

/**
* Processes the incoming HTTP request and performs Bearer token authentication.
*
* <p>Extracts the Bearer token from the Authorization header, validates the token using
* {@link UserServiceClient#validateToken(String)}, and sets the authentication context
* if the token is valid. If validation fails, sets the appropriate HTTP status and
* writes an error message to the response. The filter chain proceeds regardless of
* token validation success or failure.</p>
*
* @param httpServletRequest the HTTP request
* @param httpServletResponse the HTTP response
* @param filterChain the filter chain to proceed with
* @throws ServletException if an error occurs during filtering
* @throws IOException if an I/O error occurs during filtering
*/
@Override
protected void doFilterInternal(@NonNull final HttpServletRequest httpServletRequest,
@NonNull final HttpServletResponse httpServletResponse,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,11 @@
import lombok.Getter;
import lombok.RequiredArgsConstructor;

/**
* Enum representing configuration parameters used for token management and key settings.
* This enum provides default values for various configuration parameters related
* to authentication, including token expiration settings and cryptographic keys.
*/
@Getter
@RequiredArgsConstructor
public enum ConfigurationParameter {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,11 @@
import java.time.Instant;
import java.util.Map;

/**
* Represents a JWT (JSON Web Token) with its components and metadata.
* This record contains information about the token, its headers, claims,
* issuance and expiration times, subject, issuer, and audience.
*/
public record JwtRecord(String tokenValue, Map<String, Object> headers, Map<String, Object> claims,
Instant issuedAt, Instant expiresAt, String subject, String issuer, String audience) {
// You can add any necessary methods or constructors here if needed
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@
import lombok.Getter;
import org.springframework.util.StringUtils;

/**
* Represents authentication tokens used for access and refresh.
* This class contains the access token, its expiration time, and the refresh token.
*/
@Getter
@Builder
public class Token {
Expand All @@ -14,11 +18,23 @@ public class Token {

private static final String TOKEN_PREFIX = "Bearer ";

/**
* Checks if the provided authorization header contains a Bearer token.
*
* @param authorizationHeader the authorization header to check
* @return {@code true} if the header contains a Bearer token, {@code false} otherwise
*/
public static boolean isBearerToken(final String authorizationHeader) {
return StringUtils.hasText(authorizationHeader) &&
authorizationHeader.startsWith(TOKEN_PREFIX);
}

/**
* Extracts the JWT from the provided authorization header.
*
* @param authorizationHeader the authorization header containing the JWT
* @return the JWT extracted from the header
*/
public static String getJwt(final String authorizationHeader) {
return authorizationHeader.replace(TOKEN_PREFIX, "");
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
package com.springbootmicroservices.productservice.model.auth;

/**
* Enum representing various user statuses in the system.
* This enum is used to indicate the current status of a user account.
*/
public enum UserStatus {
ACTIVE,
PASSIVE,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
package com.springbootmicroservices.productservice.model.auth;

/**
* Enum representing different user types in the system.
* This enum is used to categorize users based on their roles or permissions.
*/
public enum UserType {
USER,
ADMIN
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,11 @@
import lombok.Getter;
import lombok.RequiredArgsConstructor;

/**
* Enum representing various JWT token claims and their corresponding keys.
* This enum defines the standard claims used in JWT tokens along with their
* JSON keys, which are utilized for encoding and decoding JWT payloads.
*/
@Getter
@RequiredArgsConstructor
public enum TokenClaims {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,11 @@
import java.io.IOException;
import java.text.DateFormat;

/**
* Custom implementation of the {@link AuthenticationEntryPoint} interface.
* This component is responsible for handling unauthorized access attempts
* by sending a custom error response when authentication fails.
*/
@Component
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {

Expand All @@ -23,7 +28,15 @@ public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint
OBJECT_MAPPER.registerModule(new JavaTimeModule());
}


/**
* Handles authentication errors by sending a custom error response to the client.
* Sets the HTTP status to 401 Unauthorized and sends a JSON response with error details.
*
* @param httpServletRequest the request that resulted in an AuthenticationException
* @param httpServletResponse the response to send to the client
* @param authenticationException the exception that triggered this entry point
* @throws IOException if an input or output exception occurs
*/
@Override
public void commence(final HttpServletRequest httpServletRequest, final HttpServletResponse httpServletResponse,
final AuthenticationException authenticationException) throws IOException {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,24 @@
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
* Custom serializer for {@link LocalDateTime} objects.
* This serializer formats the {@link LocalDateTime} as an ISO-8601 string.
*/
public class LocalDateTimeSerializer extends JsonSerializer<LocalDateTime> {
private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ISO_LOCAL_DATE_TIME;

/**
* Serializes the given {@link LocalDateTime} value to an ISO-8601 formatted string.
*
* @param value the {@link LocalDateTime} value to serialize
* @param gen the {@link JsonGenerator} used to write the serialized value
* @param serializers the {@link SerializerProvider} that can be used to get serializers for other types
* @throws IOException if an I/O error occurs
*/
@Override
public void serialize(LocalDateTime value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeString(value.format(FORMATTER));
}

}
Loading

0 comments on commit b72db61

Please sign in to comment.