Skip to content

Commit

Permalink
refs #1 - Alterações para novo alinhamento de escopo
Browse files Browse the repository at this point in the history
  • Loading branch information
ruan-pb committed Feb 12, 2021
1 parent 10a7481 commit 99c6c6b
Show file tree
Hide file tree
Showing 9 changed files with 104 additions and 46 deletions.
14 changes: 11 additions & 3 deletions src/main/java/org/ayty/hatcher/api/v1/security/JwtAuthFilter.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,15 @@

import java.io.IOException;



import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.ayty.hatcher.api.v1.user.service.UserServiceImpl;
import org.ayty.hatcher.api.v1.user.service.LoadUserByUsarname;
import org.ayty.hatcher.api.v1.user.service.LoginImpl;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
Expand All @@ -20,7 +23,12 @@
public class JwtAuthFilter extends OncePerRequestFilter {

private final JwtService jwtService;
private final UserServiceImpl userService;

//private final LoginImpl loginImpl;

//private final UserServiceImpl userService;

private final LoadUserByUsarname load;

@Override
protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,FilterChain filterChain) throws ServletException, IOException {
Expand All @@ -31,7 +39,7 @@ protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServl
boolean isValid = jwtService.validToken(token);
if (isValid) {
String userLogin = jwtService.getUserLogin(token);
UserDetails userDetails = userService.loadUserByUsername(userLogin);
UserDetails userDetails = load.loadUserByUsername(userLogin);
UsernamePasswordAuthenticationToken user = new UsernamePasswordAuthenticationToken(userDetails, null,
userDetails.getAuthorities());
user.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpServletRequest));
Expand Down
25 changes: 16 additions & 9 deletions src/main/java/org/ayty/hatcher/api/v1/security/SecurityConfig.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package org.ayty.hatcher.api.v1.security;

import org.ayty.hatcher.api.v1.user.service.UserServiceImpl;
import org.ayty.hatcher.api.v1.user.service.LoadUserByUsarname;
import org.ayty.hatcher.api.v1.user.service.LoginImpl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpMethod;
Expand All @@ -13,31 +15,36 @@
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.filter.OncePerRequestFilter;

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
private UserServiceImpl userService;
//@Autowired
//private UserServiceImpl userService;
@Autowired
JwtService jwtService;

/*
@Autowired
LoginImpl loginImpl;
*/
@Autowired
LoadUserByUsarname load;

@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userService).passwordEncoder(passwordEncoder());
auth.userDetailsService(load).passwordEncoder(passwordEncoder());

//auth.userDetailsService(userService).passwordEncoder(passwordEncoder());
}
@Bean
public OncePerRequestFilter jwtFilter() {
return new JwtAuthFilter(jwtService, userService);
return new JwtAuthFilter(jwtService, load);
}
@Override
protected void configure( HttpSecurity http ) throws Exception {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,9 @@ public TokenDTO authenticate(@Valid @RequestBody LoginDTO credenciais){
public List<UserListDTO> ListUsers() {
return listUserService.listOfRegisteredUsers();
}



@ResponseStatus(HttpStatus.NO_CONTENT)
@RequestMapping(value = "/remove/{id}", method = RequestMethod.DELETE)
@CrossOrigin("*")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@

@Repository
public interface UserRepository extends JpaRepository<User, Long>{

Optional<User> findByLogin(String login);

Optional<User> findByPassword(String password);
boolean existsByLogin(String login);
boolean existsByPassword(String password);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,25 +1,43 @@
package org.ayty.hatcher.api.v1.user.service;

import java.util.Optional;

import org.ayty.hatcher.api.v1.user.entity.User;
import org.ayty.hatcher.api.v1.user.exception.IncorrectUserOrPassword;
import org.ayty.hatcher.api.v1.user.exception.UsernameNotFoundException;
import org.ayty.hatcher.api.v1.user.jpa.UserRepository;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;

import lombok.RequiredArgsConstructor;

@RequiredArgsConstructor
@Service
public class LoadUserByUsarname implements UserDetailsService {

private final UserRepository userBD;

@Override
public UserDetails loadUserByUsername(String login) throws UsernameNotFoundException {
User user = userBD.findByLogin(login).orElseThrow(() -> new IncorrectUserOrPassword());
String[] roles = user.isAdmin() ? new String[] { "ADMIN", "USER" } : new String[] { "USER" };
return org.springframework.security.core.userdetails.User.builder().username(user.getLogin())
.password(user.getPassword()).roles(roles).build();
}




System.out.println("primeira viagem "+login);



Optional<User> user = userBD.findByLogin("admin");
System.out.println("Segunda viagem "+login);
// .orElseThrow(() -> new IncorrectUserOrPassword());
//String[] roles = user.isAdmin() ? new String[] { "ADMIN", "USER" } : new String[] { "USER" };
System.out.println("terceira viagem "+login);

return org.springframework.security.core.userdetails.
User.builder().username(user.get().getLogin())
.password("$2y$04$Hexn6JOpJn8ohHTdX0zJdODijX1ks6JmjUqlgJYJiAuV9KatL3aqS")
.roles("ADMIN").build();

}
}

29 changes: 27 additions & 2 deletions src/main/java/org/ayty/hatcher/api/v1/user/service/LoginImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,21 +7,26 @@
import org.ayty.hatcher.api.v1.user.exception.UserDoesNotExist;
import org.ayty.hatcher.api.v1.user.jpa.UserRepository;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import lombok.RequiredArgsConstructor;

@RequiredArgsConstructor
@Service
public class LoginImpl implements Login {
public class LoginImpl implements Login/*UserDetailsService*/ {

private final PasswordEncoder encoder;
private final LoadUserByUsarname load;
private final UserRepository userBD;
//private final UserServiceImpl userService;

public UserDetails authenticate(User user) {
UserDetails userDetails = load.loadUserByUsername(user.getLogin());
System.out.println("user dentro do authenticate "+user.getLogin());

UserDetails userDetails = load.loadUserByUsername("admin");

if (userDetails.getUsername() == null) {
throw new LoginNotFound();
Expand All @@ -35,4 +40,24 @@ public UserDetails authenticate(User user) {
throw new IncorrectUserOrPassword();
}
}
/*
@Override
public UserDetails loadUserByUsername(String login) throws UsernameNotFoundException {
System.out.println("dentro do loadUser da classe loginImpl "+login);
System.out.println(userBD.findByLogin(login));
User user = userBD.findByLogin(login).orElseThrow(() -> new LoginNotFound());
String[] roles = user.isAdmin() ? new String[] {"ADMIN","USER"} : new String[] {"USER"};
System.out.println("antes do User builder "+login);
return org.springframework.security.core.userdetails.
User.builder()
.username(user.getLogin())
.password(user.getLogin())
.roles(roles)
.build();
}
*/
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package org.ayty.hatcher.api.v1.user.service;


/*
Expand All @@ -10,9 +10,11 @@
import org.ayty.hatcher.api.v1.user.dto.RegisterUserDTO;
import org.ayty.hatcher.api.v1.user.entity.User;
import org.ayty.hatcher.api.v1.user.exception.IncorrectUserOrPassword;
import org.ayty.hatcher.api.v1.user.exception.LoginNotFound;
import org.ayty.hatcher.api.v1.user.jpa.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
Expand All @@ -23,12 +25,14 @@
@Service
public class UserServiceImpl implements UserDetailsService {
public class UserServiceImpl implements UserDetailsService {
@Autowired
private PasswordEncoder encoder;
@Autowired
UserRepository userBD;
@Transactional
public User save(RegisterUserDTO user) {
boolean admin = false;
Expand All @@ -46,24 +50,21 @@ public User save(RegisterUserDTO user) {
}
public UserDetails authenticate( User user ){
UserDetails userDetails = loadUserByUsername(user.getLogin());
boolean PasswordsMatch= encoder.matches( user.getPassword(), userDetails.getPassword() );
boolean PasswordsMatch= encoder.matches(user.getPassword(), userDetails.getPassword() );
if(PasswordsMatch){
return userDetails;
}
throw new IncorrectUserOrPassword();
}

@Override
public UserDetails loadUserByUsername(String login) throws UsernameNotFoundException {
User user = userBD.findByLogin(login).orElseThrow(() -> new UsernameNotFoundException("User not found in the database"));
String[] roles = user.isAdmin() ? new String[] {"ADMIN","USER"} : new String[] {"USER"};


return org.springframework.security.core.userdetails.
User.builder()
.username(user.getLogin())
.password(user.getPassword())
.roles(roles)
.build();
@Override
public UserDetails loadUserByUsername(String login) throws UsernameNotFoundException {
System.out.println("load "+login);
User user = userBD.findByLogin(login).orElseThrow(() -> new IncorrectUserOrPassword());
String[] roles = user.isAdmin() ? new String[] { "ADMIN", "USER" } : new String[] { "USER" };
return org.springframework.security.core.userdetails.
User.builder().username(login)
.password(user.getPassword()).roles(roles).build();
}
}
}
*/

2 changes: 1 addition & 1 deletion src/main/resources/application-dev.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ spring:
datasource:
url: jdbc:postgresql://localhost:5432/hatcher-db
username: postgres
password: 123Mudar
password: ruan
flyway:
enabled: true
jpa:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,20 +49,14 @@ void UserRolesTests() {
UserDetails userD = load.loadUserByUsername("vito");


assertEquals("[ROLE_ADMIN, ROLE_USER]", userD.getAuthorities().toString());



assertEquals("[ROLE_ADMIN, ROLE_USER]", userD.getAuthorities().toString());

}


@Test
void UserNamenonexistent() {

assertThrows(IncorrectUserOrPassword.class,() -> load.loadUserByUsername("cleyson"));
}



}

0 comments on commit 99c6c6b

Please sign in to comment.