-
Notifications
You must be signed in to change notification settings - Fork 1
parte de security feita com sucesso, register e login do usuario #9
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
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,60 @@ | ||
| package com.example.LibraryLoop.controller; | ||
|
|
||
| import com.example.LibraryLoop.Repository.userRepository; | ||
| import com.example.LibraryLoop.dto.user.LoginRequestDTO; | ||
| import com.example.LibraryLoop.dto.user.RegisterRequestDTO; | ||
| import com.example.LibraryLoop.dto.user.ResponseDTO; | ||
| import com.example.LibraryLoop.entity.User; | ||
| import com.example.LibraryLoop.security.config.TokenService; | ||
| import lombok.RequiredArgsConstructor; | ||
| import org.springframework.http.ResponseEntity; | ||
| import org.springframework.security.crypto.password.PasswordEncoder; | ||
| import org.springframework.web.bind.annotation.*; | ||
|
|
||
| import java.util.Map; | ||
| import java.util.Optional; | ||
|
|
||
| @RestController | ||
| @RequestMapping("/auth") | ||
| @RequiredArgsConstructor | ||
| public class AuthController { | ||
|
|
||
| private final userRepository repository; | ||
| private final PasswordEncoder passwordEncoder; | ||
| private final TokenService tokenService; | ||
|
|
||
| @PostMapping("/login") | ||
| public ResponseEntity<?> login(@RequestBody LoginRequestDTO body) { | ||
| User user = this.repository.findByEmail(body.email()) | ||
| .orElseThrow(() -> new RuntimeException("User not found")); | ||
|
|
||
| if (passwordEncoder.matches(body.password(), user.getPassword())) { | ||
| String token = this.tokenService.generateToken(user); | ||
| return ResponseEntity.ok(new ResponseDTO(user.getUsername(), token)); | ||
| } | ||
| return ResponseEntity.badRequest().build(); | ||
| } | ||
|
|
||
| @PostMapping("/register") | ||
| public ResponseEntity<?> register(@RequestBody RegisterRequestDTO body) { | ||
|
|
||
| if (this.repository.findByEmail(body.email()).isPresent()) { | ||
| return ResponseEntity.badRequest() | ||
| .body(Map.of("error", "Já existe um usuário com esse e-mail cadastrado.")); | ||
| } | ||
|
|
||
| if (this.repository.findByUsername(body.username()).isPresent()) { | ||
| return ResponseEntity.badRequest() | ||
| .body(Map.of("error", "Já existe um usuário com esse username cadastrado.")); | ||
| } | ||
|
|
||
| User newUser = new User(); | ||
| newUser.setPassword(passwordEncoder.encode(body.password())); | ||
| newUser.setEmail(body.email()); | ||
| newUser.setUsername(body.username()); | ||
| this.repository.save(newUser); | ||
|
|
||
| String token = this.tokenService.generateToken(newUser); | ||
| return ResponseEntity.ok(new ResponseDTO(newUser.getUsername(), token)); | ||
| } | ||
| } |
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. esse arquivo mesmo é refatoração, nao ta ruim, é até bom, mas ai tem que ser um PR exclusivo pra isso, pensa no futuro caso vc queira olhar o historico do repo pra achar onde ta as alterações dessa parte. Vc nao acharia
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. vdd vou melhorar isso, acabei colocando tudo no mesmo pacote |
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. mesmo BO de refatoração |
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. aqui tem um metodo nao finalizado, esse arquivo é praticamente um arquivo de comentario pra lembrar de fazer o metodo dps, isso nao subiria pra produção. imagine o repositorio aqui como produção |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| package com.example.LibraryLoop.dto.user; | ||
|
|
||
| public record LoginRequestDTO(String email, String password) {} |
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. aqui tem um metodo nao finalizado, esse arquivo é praticamente um arquivo de comentario pra lembrar de fazer o metodo dps, isso nao subiria pra produção. imagine o repositorio aqui como produção |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| package com.example.LibraryLoop.dto.user; | ||
|
|
||
| public record RegisterRequestDTO(String username, String email, String password) {} |
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. aqui tem um metodo nao finalizado, esse arquivo é praticamente um arquivo de comentario pra lembrar de fazer o metodo dps, isso nao subiria pra produção. imagine o repositorio aqui como produção |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| package com.example.LibraryLoop.dto.user; | ||
|
|
||
| public record ResponseDTO(String username, String token) {} |
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. aqui ta uma alteração que gostei bastante, fez uma refatoração no lombok que faz sentido com o pr proposto. percebeu que tava duplicado o bgl, e add as info pra segurança do usuario, isso aqui passaria tranquilo, por mim logico |
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. aprovado |
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. aprovado |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,22 @@ | ||
| package com.example.LibraryLoop.security.config; | ||
|
|
||
| import com.example.LibraryLoop.Repository.userRepository; | ||
| import com.example.LibraryLoop.entity.User; | ||
| import org.springframework.beans.factory.annotation.Autowired; | ||
| import org.springframework.security.core.userdetails.UserDetails; | ||
| import org.springframework.security.core.userdetails.UserDetailsService; | ||
| import org.springframework.security.core.userdetails.UsernameNotFoundException; | ||
| import org.springframework.stereotype.Component; | ||
|
|
||
| import java.util.ArrayList; | ||
|
|
||
| @Component | ||
| public class CustomUserDetailsService implements UserDetailsService { | ||
| @Autowired | ||
| private userRepository repository; | ||
| @Override | ||
| public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { | ||
| User user = this.repository.findByEmail(username).orElseThrow(() -> new UsernameNotFoundException("User not found")); | ||
| return new org.springframework.security.core.userdetails.User(user.getEmail(), user.getPassword(), new ArrayList<>()); | ||
| } | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,48 @@ | ||
| package com.example.LibraryLoop.security.config; | ||
|
|
||
| import lombok.RequiredArgsConstructor; | ||
| import org.springframework.context.annotation.Bean; | ||
| import org.springframework.context.annotation.Configuration; | ||
| import org.springframework.security.config.annotation.web.builders.HttpSecurity; | ||
| import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; | ||
| import org.springframework.security.config.http.SessionCreationPolicy; | ||
| import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; | ||
| import org.springframework.security.crypto.password.PasswordEncoder; | ||
| import org.springframework.security.web.SecurityFilterChain; | ||
| import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; | ||
|
|
||
| @Configuration | ||
| @EnableWebSecurity | ||
| @RequiredArgsConstructor | ||
| public class SecurityConfig { | ||
|
|
||
| private final SecurityFilter securityFilter; | ||
|
|
||
| @Bean | ||
| public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { | ||
|
|
||
| http | ||
| // desabilita CSRF (necessário para API REST) | ||
| .csrf(csrf -> csrf.disable()) | ||
|
|
||
| // API stateless (JWT) | ||
| .sessionManagement(session -> | ||
| session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) | ||
|
|
||
| // configuração de rotas | ||
| .authorizeHttpRequests(auth -> auth | ||
| .requestMatchers("/auth/**").permitAll() | ||
| .anyRequest().authenticated() | ||
| ) | ||
|
|
||
| // adiciona filtro JWT antes do filtro padrão | ||
| .addFilterBefore(securityFilter, UsernamePasswordAuthenticationFilter.class); | ||
|
|
||
| return http.build(); | ||
| } | ||
|
|
||
| @Bean | ||
| public PasswordEncoder passwordEncoder() { | ||
| return new BCryptPasswordEncoder(); | ||
| } | ||
| } |
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.
aqui eu nao entendi oo motivo dessa interface existir. c todos os atributos são opcionais, prq criar uma lei que os obrigue?