Skip to content

Conversation

@OtavioXimarelli
Copy link
Owner

@OtavioXimarelli OtavioXimarelli commented Jun 11, 2025

PR Type

Enhancement


Description

• Implement comprehensive Spring Security with JWT authentication
• Add user registration and login endpoints with DTOs
• Configure environment variable loading via dotenv
• Refactor security configuration and remove unused CORS setup


Changes walkthrough 📝

Relevant files
Formatting
1 files
AiFoodAppApplication.java
Minor code formatting improvement                                               
+1/-1     
Configuration changes
5 files
CorsConfig.java
Remove unused CORS configuration class                                     
+0/-31   
DotenvEnvironmentPostProcessor.java
Add dotenv environment variable processor                               
+25/-0   
SecurityConfig.java
Remove old security configuration file                                     
+0/-23   
spring.factories
Register dotenv environment post processor                             
+2/-0     
application.properties
Configure environment variables and JWT settings                 
+13/-8   
Enhancement
10 files
AuthenticationController.java
Add authentication controller with login/register endpoints
+60/-0   
AuthenticationDTO.java
Add authentication DTO for login data                                       
+4/-0     
LoginResponseDTO.java
Add login response DTO with token                                               
+4/-0     
RegisterDTO.java
Add registration DTO for user signup                                         
+28/-0   
User.java
Add constructor and improve code formatting                           
+8/-1     
UserRepository.java
Update findByLogin method return type and imports               
+4/-6     
SecurityConfig.java
Implement comprehensive security configuration with JWT filter
+52/-0   
SecurityFilter.java
Add JWT authentication filter for request processing         
+51/-0   
TokenService.java
Implement JWT token generation and validation service       
+52/-0   
AuthorizationService.java
Update user loading logic for authentication                         
+5/-2     
Documentation
1 files
README.MD
Update documentation to reflect security implementation   
+98/-103
Dependencies
1 files
pom.xml
Add security dependencies and reorganize structure             
+129/-129

Need help?
  • Type /help how to ... in the comments thread for any questions about Qodo Merge usage.
  • Check out the documentation for more information.
  • Resumo por Sourcery

    Implementa segurança abrangente do Spring com autenticação JWT e suporte a variáveis de ambiente baseadas em dotenv, refatora a configuração de segurança, atualiza as dependências e as propriedades da aplicação e atualiza a documentação.

    Novas Funcionalidades:

    • Adiciona endpoints de registro e login de usuário baseados em JWT
    • Integra o carregamento de variáveis de ambiente com dotenv

    Melhorias:

    • Refatora a configuração de segurança em um filtro JWT sem estado e remove a configuração CORS não utilizada
    • Externaliza configurações sensíveis para variáveis de ambiente nas propriedades da aplicação

    Build:

    • Reorganiza as dependências do pom.xml para incluir Spring Security, java-jwt, dotenv-java e atualiza as configurações do plugin

    Documentação:

    • Atualiza o README para documentar os novos fluxos de autenticação e a configuração do .env

    Tarefas:

    • Remove CorsConfig obsoleto e classes de configuração de segurança antigas
    • Aplica pequenas melhorias na formatação do código
    Original summary in English

    Resumo por Sourcery

    Implementa segurança Spring abrangente com autenticação e registro baseados em JWT, habilita configuração de ambiente orientada por dotenv, refatora a configuração de segurança, atualiza dependências e aprimora a documentação

    Novas funcionalidades:

    • Adiciona endpoints de registro e login de usuário com autenticação JWT
    • Introduz geração de token JWT, serviço de validação e filtro de segurança para autenticação sem estado
    • Suporta carregamento de variáveis de ambiente de .env via um Spring EnvironmentPostProcessor

    Aprimoramentos:

    • Refatora a configuração do Spring Security para um filtro JWT sem estado e remove a configuração CORS obsoleta
    • Externaliza configurações confidenciais para variáveis de ambiente e atualiza application.properties de acordo
    • Reorganiza as dependências do projeto para incluir Spring Security, java-jwt e dotenv

    Documentação:

    • Atualiza o README para documentar fluxos de autenticação, configuração JWT e uso de .env

    Tarefas:

    • Remove a configuração de segurança antiga e a classe CorsConfig
    • Aplica pequenas melhorias na formatação do código
    Original summary in English

    Summary by Sourcery

    Implement comprehensive Spring Security with JWT-based authentication and registration, enable dotenv-driven environment configuration, refactor security setup, update dependencies, and enhance documentation

    New Features:

    • Add user registration and login endpoints with JWT authentication
    • Introduce JWT token generation, validation service, and security filter for stateless auth
    • Support environment variable loading from .env via a Spring EnvironmentPostProcessor

    Enhancements:

    • Refactor Spring Security configuration to a stateless JWT filter and remove obsolete CORS setup
    • Externalize sensitive settings to environment variables and update application.properties accordingly
    • Reorganize project dependencies to include Spring Security, java-jwt, and dotenv

    Documentation:

    • Update README to document authentication flows, JWT setup, and .env usage

    Chores:

    • Remove old security configuration and CorsConfig class
    • Apply minor code formatting improvements

    OtavioXimarelli and others added 30 commits June 1, 2025 23:32
    @qodo-code-review
    Copy link

    PR Reviewer Guide 🔍

    Here are some key observations to aid the review process:

    ⏱️ Estimated effort to review: 4 🔵🔵🔵🔵⚪
    🧪 No relevant tests
    🔒 Security concerns

    Sensitive information exposure:
    The application.properties file shows a hardcoded API key in the old version (maritaca.api.key=107504935113477439114_ea6f180a4332d6ed) which was removed but indicates previous exposure. The TokenService throws RuntimeExceptions with potentially sensitive error messages that could leak information about token validation failures. The registration endpoint returns different HTTP status codes for existing vs non-existing users, enabling username enumeration attacks.

    ⚡ Recommended focus areas for review

    Syntax Error

    Missing closing brace in password() method causing compilation error

        public String password() { return password;
    }
    Security Risk

    Hard-coded timezone offset and RuntimeException throwing on token validation may expose sensitive information or cause service disruption

        } catch (JWTVerificationException verificationException) {
            throw new RuntimeException("Invalid token", verificationException);
        }
    }
    
    private Instant genExperationDate() {
        return LocalDateTime.now().plusHours(2).toInstant(ZoneOffset.of("-03:00"));
    Security Concern

    User existence check returns different HTTP status codes which could enable username enumeration attacks

    if (userRepository.findByLogin(data.login()) != null) return ResponseEntity.badRequest().build();

    @qodo-code-review
    Copy link

    qodo-code-review bot commented Jun 11, 2025

    PR Code Suggestions ✨

    Explore these optional code suggestions:

    CategorySuggestion                                                                                                                                    Impact
    Possible issue
    Return null for invalid tokens

    The method should return null for invalid tokens instead of throwing a
    RuntimeException. This allows the security filter to handle invalid tokens
    gracefully by not authenticating the user.

    src/main/java/com/otavio/aifoodapp/security/TokenService.java [34-45]

     public String validateToken(String token) {
         try {
             Algorithm algorithm = Algorithm.HMAC256(secret);
             return JWT.require(algorithm)
                     .withIssuer("auth-api")
                     .build()
                     .verify(token)
                     .getSubject();
         } catch (JWTVerificationException verificationException) {
    -        throw new RuntimeException("Invalid token", verificationException);
    +        return null;
         }
     }
    • Apply / Chat
    Suggestion importance[1-10]: 8

    __

    Why: The suggestion correctly points out that throwing a RuntimeException for an invalid token is not ideal. Returning null allows the SecurityFilter to handle this case gracefully without crashing the request, which is a significant improvement in robustness.

    Medium
    General
    Fix method formatting consistency

    The method has incorrect formatting with the closing brace on a new line. This
    should be properly formatted for consistency with the rest of the codebase.

    src/main/java/com/otavio/aifoodapp/dto/RegisterDTO.java [16-17]

    -public String password() { return password;
    +public String password() { 
    +    return password;
     }
    • Apply / Chat
    Suggestion importance[1-10]: 2

    __

    Why: The suggestion addresses a minor code formatting inconsistency. While correct, this is a low-impact change related to code style and does not affect functionality.

    Low
    Security
    Add input validation for registration data

    The registration endpoint should validate input data before processing to
    prevent potential security issues. Add null checks for login and password fields
    to ensure they are not empty or null before proceeding with user creation.

    src/main/java/com/otavio/aifoodapp/controller/AuthenticationController.java [49-59]

     @PostMapping("/register")
     public ResponseEntity<?> register(@RequestBody @Valid RegisterDTO data) {
    +    if (data.login() == null || data.login().trim().isEmpty() || 
    +        data.password() == null || data.password().trim().isEmpty()) {
    +        return ResponseEntity.badRequest().build();
    +    }
    +    
         if (userRepository.findByLogin(data.login()) != null) return ResponseEntity.badRequest().build();
     
         String encryptedPassword = this.passwordEncoder.encode(data.password());
     
         User newUser = new User(data.login(), encryptedPassword, data.role());
         userRepository.save(newUser);
     
         return ResponseEntity.ok().build();
     }
    • Apply / Chat
    Suggestion importance[1-10]: 8

    __

    Why: The suggestion correctly identifies a missing validation. Although the @Valid annotation is present, the RegisterDTO class lacks validation annotations (like @NotBlank), making the @Valid ineffective. Adding explicit null/empty checks for login and password is crucial for data integrity and security to prevent the creation of users with invalid credentials.

    Medium
    Validate Authorization header format properly

    The token recovery method should validate the Authorization header format before
    extracting the token. Check if the header starts with "Bearer " to ensure proper
    token format and prevent potential issues with malformed headers.

    src/main/java/com/otavio/aifoodapp/security/SecurityFilter.java [46-50]

     private String recoverToken(HttpServletRequest request) {
         var authHeader = request.getHeader("Authorization");
    -    if (authHeader == null) return null;
    +    if (authHeader == null || !authHeader.startsWith("Bearer ")) return null;
         return authHeader.replace("Bearer ", "");
     }
    • Apply / Chat
    Suggestion importance[1-10]: 7

    __

    Why: The suggestion correctly points out that the code should validate the Authorization header format. The current implementation would not return null for a malformed header (e.g., one without the "Bearer " prefix), which could lead to issues in the token validation logic. Adding !authHeader.startsWith("Bearer ") makes the token recovery more robust.

    Medium
    General
    Add exception handling for dotenv loading

    The method should handle potential exceptions when loading the .env file to
    prevent application startup failures. Wrap the dotenv loading in a try-catch
    block to ensure graceful degradation if the .env file is malformed or
    inaccessible.

    src/main/java/com/otavio/aifoodapp/config/DotenvEnvironmentPostProcessor.java [16-21]

     public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
    -    Dotenv dotenv = Dotenv.configure().ignoreIfMissing().load();
    -    Map<String, Object> envMap = new HashMap<>();
    -    dotenv.entries().forEach(entry -> envMap.put(entry.getKey(), entry.getValue()));
    -    environment.getPropertySources().addFirst(new MapPropertySource("dotenv", envMap));
    +    try {
    +        Dotenv dotenv = Dotenv.configure().ignoreIfMissing().load();
    +        Map<String, Object> envMap = new HashMap<>();
    +        dotenv.entries().forEach(entry -> envMap.put(entry.getKey(), entry.getValue()));
    +        environment.getPropertySources().addFirst(new MapPropertySource("dotenv", envMap));
    +    } catch (Exception e) {
    +        // Log warning but don't fail startup - allow fallback to default properties
    +        System.err.println("Warning: Failed to load .env file: " + e.getMessage());
    +    }
     }
    • Apply / Chat
    Suggestion importance[1-10]: 7

    __

    Why: The suggestion correctly points out that while ignoreIfMissing() handles a non-existent .env file, it doesn't prevent a DotenvException if the file is malformed. Adding a try-catch block improves the application's robustness by preventing startup failures from a syntactically incorrect .env file.

    Medium
    • More

    @OtavioXimarelli OtavioXimarelli merged commit 8dcd4b9 into master Jun 11, 2025
    8 checks passed
    @OtavioXimarelli OtavioXimarelli deleted the SpringSecurity-implementation branch June 11, 2025 11:58
    Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

    Projects

    None yet

    Development

    Successfully merging this pull request may close these issues.

    2 participants