-
Notifications
You must be signed in to change notification settings - Fork 0
Add authentication endpoint #14
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
…t and add authentication manager
Guia do RevisorEste PR impõe autenticação em toda a aplicação, atualizando a cadeia de filtros de segurança, registra os beans de autenticação necessários (AuthenticationManager e BCryptPasswordEncoder), muda a geração de ID da entidade de usuário para a estratégia UUID e adiciona um endpoint de login com seu DTO correspondente. Diagrama de Sequência para o Processo de Login do UsuáriosequenceDiagram
actor User
participant AuthController as AuthenticationController
participant AuthManager as AuthenticationManager
User->>AuthController: POST /api/auth/login (AuthenticationDTO)
AuthController->>AuthManager: authenticate(usernamePasswordToken)
AuthManager-->>AuthController: Authentication Result (Authenticated User)
AuthController-->>User: HTTP 200 OK (Authentication Token/Details)
Diagrama ER: Atualização da Geração de ID da Entidade de UsuárioerDiagram
User {
Long id PK "Estratégia alterada para GenerationType.UUID"
String login "único, nullable=false"
String password "nullable=false"
}
Diagrama de Classes: Novo AuthenticationDTOclassDiagram
class AuthenticationDTO {
<<Record>>
+String login
+String password
}
Diagrama de Classes: Novo AuthenticationControllerclassDiagram
class AuthenticationController {
-AuthenticationManager authenticationManager
+ResponseEntity login(AuthenticationDTO data)
}
AuthenticationController ..> AuthenticationManager : uses
AuthenticationController ..> AuthenticationDTO : uses
Diagrama de Classes: Entidade de Usuário AtualizadaclassDiagram
class User {
<<Entity>>
-Long id "Anotação: @GeneratedValue(strategy = GenerationType.UUID) adicionada"
-String login
-String password
+getAuthorities() Collection~GrantedAuthority~
+getPassword() String
+getUsername() String
+isAccountNonExpired() boolean
+isAccountNonLocked() boolean
+isCredentialsNonExpired() boolean
+isEnabled() boolean
}
Diagrama de Classes: SecurityConfig AtualizadoclassDiagram
class SecurityConfig {
+SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) "Atualizado: impõe .anyRequest().authenticated()"
+AuthenticationManager authenticationManagerBean(AuthenticationConfiguration authConfig) "Novo método"
+PasswordEncoder passwordEncoder() "Novo método (retorna BCryptPasswordEncoder)"
}
SecurityConfig ..> HttpSecurity : configures
SecurityConfig ..> AuthenticationConfiguration : uses
SecurityConfig ..> AuthenticationManager : creates
SecurityConfig ..> PasswordEncoder : creates
SecurityConfig ..> BCryptPasswordEncoder : instantiates
Alterações no Nível do Arquivo
Dicas e comandosInteragindo com o Sourcery
Personalizando Sua ExperiênciaAcesse seu painel para:
Obtendo Ajuda
Original review guide in EnglishReviewer's GuideThis PR enforces authentication across the application by updating the security filter chain, registers necessary authentication beans (AuthenticationManager and BCryptPasswordEncoder), switches the user entity’s ID generation to UUID strategy, and adds a login endpoint with its corresponding DTO. Sequence Diagram for User Login ProcesssequenceDiagram
actor User
participant AuthController as AuthenticationController
participant AuthManager as AuthenticationManager
User->>AuthController: POST /api/auth/login (AuthenticationDTO)
AuthController->>AuthManager: authenticate(usernamePasswordToken)
AuthManager-->>AuthController: Authentication Result (Authenticated User)
AuthController-->>User: HTTP 200 OK (Authentication Token/Details)
ER Diagram: User Entity ID Generation UpdateerDiagram
User {
Long id PK "Strategy changed to GenerationType.UUID"
String login "unique, nullable=false"
String password "nullable=false"
}
Class Diagram: New AuthenticationDTOclassDiagram
class AuthenticationDTO {
<<Record>>
+String login
+String password
}
Class Diagram: New AuthenticationControllerclassDiagram
class AuthenticationController {
-AuthenticationManager authenticationManager
+ResponseEntity login(AuthenticationDTO data)
}
AuthenticationController ..> AuthenticationManager : uses
AuthenticationController ..> AuthenticationDTO : uses
Class Diagram: Updated User EntityclassDiagram
class User {
<<Entity>>
-Long id "Annotation: @GeneratedValue(strategy = GenerationType.UUID) added"
-String login
-String password
+getAuthorities() Collection~GrantedAuthority~
+getPassword() String
+getUsername() String
+isAccountNonExpired() boolean
+isAccountNonLocked() boolean
+isCredentialsNonExpired() boolean
+isEnabled() boolean
}
Class Diagram: Updated SecurityConfigclassDiagram
class SecurityConfig {
+SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) "Updated: enforces .anyRequest().authenticated()"
+AuthenticationManager authenticationManagerBean(AuthenticationConfiguration authConfig) "New method"
+PasswordEncoder passwordEncoder() "New method (returns BCryptPasswordEncoder)"
}
SecurityConfig ..> HttpSecurity : configures
SecurityConfig ..> AuthenticationConfiguration : uses
SecurityConfig ..> AuthenticationManager : creates
SecurityConfig ..> PasswordEncoder : creates
SecurityConfig ..> BCryptPasswordEncoder : instantiates
File-Level Changes
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Olá @OtavioXimarelli - Revisei suas alterações e encontrei alguns problemas que precisam ser resolvidos.
Problemas bloqueantes:
- O endpoint de login é protegido por authenticated() (link)
Comentários gerais:
- Seu @GeneratedValue(strategy = GenerationType.UUID) não funcionará em um ID Long—altere o tipo de campo para UUID ou mude para uma estratégia de geração numérica, como IDENTITY ou AUTO.
- O endpoint de login atualmente retorna o objeto Authentication bruto—considere mapeá-lo para um DTO seguro ou emitir um JWT em vez de expor detalhes de autenticação internos.
- Prefira a injeção de construtor em vez de @Autowired de campo em AuthenticationController para melhorar a testabilidade e a imutabilidade.
Aqui está o que eu examinei durante a revisão
- 🟡 Problemas gerais: 4 problemas encontrados
- 🟢 Segurança: tudo parece bom
- 🟢 Teste: tudo parece bom
- 🟢 Complexidade: tudo parece bom
- 🟢 Documentação: tudo parece bom
Sourcery é gratuito para código aberto - se você gosta de nossas análises, considere compartilhá-las ✨
Original comment in English
Hey @OtavioXimarelli - I've reviewed your changes and found some issues that need to be addressed.
Blocking issues:
- Login endpoint is protected by authenticated() (link)
General comments:
- Your @GeneratedValue(strategy = GenerationType.UUID) won’t work on a Long id—either change the field type to UUID or switch to a numeric generation strategy such as IDENTITY or AUTO.
- The login endpoint currently returns the raw Authentication object—consider mapping it to a safe DTO or issuing a JWT rather than exposing internal authentication details.
- Prefer constructor injection over field @Autowired in AuthenticationController to improve testability and immutability.
Here's what I looked at during the review
- 🟡 General issues: 4 issues found
- 🟢 Security: all looks good
- 🟢 Testing: all looks good
- 🟢 Complexity: all looks good
- 🟢 Documentation: all looks good
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.
| public class AuthenticationController { | ||
| @Autowired | ||
| private AuthenticationManager authenticationManager; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
suggestion: Prefira a injeção de construtor em vez da injeção de campo
Isso melhora a testabilidade e torna as dependências explícitas.
| public class AuthenticationController { | |
| @Autowired | |
| private AuthenticationManager authenticationManager; | |
| public class AuthenticationController { | |
| private final AuthenticationManager authenticationManager; | |
| public AuthenticationController(AuthenticationManager authenticationManager) { | |
| this.authenticationManager = authenticationManager; | |
| } |
Original comment in English
suggestion: Prefer constructor injection over field injection
It improves testability and makes dependencies explicit.
| public class AuthenticationController { | |
| @Autowired | |
| private AuthenticationManager authenticationManager; | |
| public class AuthenticationController { | |
| private final AuthenticationManager authenticationManager; | |
| public AuthenticationController(AuthenticationManager authenticationManager) { | |
| this.authenticationManager = authenticationManager; | |
| } |
| @PostMapping("/login") | ||
| public ResponseEntity login(@RequestBody @Valid AuthenticationDTO data) { | ||
| var usernamePassword = new UsernamePasswordAuthenticationToken(data.login(), data.password()); | ||
| var auth = this.authenticationManager.authenticate(usernamePassword); | ||
|
|
||
| return ResponseEntity.ok(auth); | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
suggestion: Especifique um tipo genérico para ResponseEntity
Usar um tipo específico como ResponseEntity<Authentication> ou um DTO personalizado melhora a segurança de tipo e evita tipos brutos.
| @PostMapping("/login") | |
| public ResponseEntity login(@RequestBody @Valid AuthenticationDTO data) { | |
| var usernamePassword = new UsernamePasswordAuthenticationToken(data.login(), data.password()); | |
| var auth = this.authenticationManager.authenticate(usernamePassword); | |
| return ResponseEntity.ok(auth); | |
| } | |
| @PostMapping("/login") | |
| public ResponseEntity<Authentication> login(@RequestBody @Valid AuthenticationDTO data) { | |
| var usernamePassword = new UsernamePasswordAuthenticationToken(data.login(), data.password()); | |
| var auth = this.authenticationManager.authenticate(usernamePassword); | |
| return ResponseEntity.ok(auth); | |
| } |
Original comment in English
suggestion: Specify a generic type for ResponseEntity
Using a specific type like ResponseEntity<Authentication> or a custom DTO enhances type safety and avoids raw types.
| @PostMapping("/login") | |
| public ResponseEntity login(@RequestBody @Valid AuthenticationDTO data) { | |
| var usernamePassword = new UsernamePasswordAuthenticationToken(data.login(), data.password()); | |
| var auth = this.authenticationManager.authenticate(usernamePassword); | |
| return ResponseEntity.ok(auth); | |
| } | |
| @PostMapping("/login") | |
| public ResponseEntity<Authentication> login(@RequestBody @Valid AuthenticationDTO data) { | |
| var usernamePassword = new UsernamePasswordAuthenticationToken(data.login(), data.password()); | |
| var auth = this.authenticationManager.authenticate(usernamePassword); | |
| return ResponseEntity.ok(auth); | |
| } |
| var usernamePassword = new UsernamePasswordAuthenticationToken(data.login(), data.password()); | ||
| var auth = this.authenticationManager.authenticate(usernamePassword); | ||
|
|
||
| return ResponseEntity.ok(auth); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🚨 issue (security): Evite retornar o objeto Authentication completo na resposta
Retorne apenas os dados de autenticação necessários, como um token JWT ou um DTO mínimo, para evitar expor detalhes de segurança internos.
Original comment in English
🚨 issue (security): Avoid returning full Authentication object in response
Return only the necessary authentication data, such as a JWT token or a minimal DTO, to avoid exposing internal security details.
…te SecurityFilter
… in login response
…for API integration
Resumo por Sourcery
Introduzir autenticação de usuário protegendo requisições HTTP, configurando a codificação de senhas e o gerenciador de autenticação, migrando a estratégia de ID de usuário para UUIDs e fornecendo um endpoint de API de login.
Novas Funcionalidades:
Melhorias:
Original summary in English
Summary by Sourcery
Introduce user authentication by securing HTTP requests, setting up password encoding and authentication manager, migrating user ID strategy to UUIDs, and providing a login API endpoint
New Features:
Enhancements: