Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0301· OpenAIAi2 WildChat-4.8M (AI2)

package com.bezkoder.springjwt.security.services; import…

  1. User

    package com.bezkoder.springjwt.security.services;

    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.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional;

    import com.bezkoder.springjwt.models.User; import com.bezkoder.springjwt.repository.UserRepository;

    @Service public class UserDetailsServiceImpl implements UserDetailsService { @Autowired UserRepository userRepository;

    @Autowired private PasswordEncoder encoder;

    @Override @Transactional public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { User user = userRepository.findByUsername(username) .orElseThrow(() -> new UsernameNotFoundException("User Not Found with username: " + username));

    return UserDetailsImpl.build(user);
    

    } @Transactional public void updateMember(User user) { User persistence = userRepository.findById(user.getId()) .orElseThrow(() -> new IllegalArgumentException("Failed to find user"));

    String rawPassword = user.getPassword();
    String encPassword = encoder.encode(rawPassword);
    
    persistence.setPassword(encPassword);
    persistence.setEmail(user.getEmail());
    

    }

    }

  2. Assistant

    As an AI language model, I am not capable of guessing if the code works as expected or not. However, the functionality of this code is to implement the UserDetailsService interface and override its method loadUserByUsername in order to load user information by username. It also includes a method updateMember that updates the user's password and email in the database after encoding the raw password using the PasswordEncoder. Overall, this code seems to be a standard implementation of a UserDetailsService.

  3. User

    I'm trying to create a member information correction function on the backend using the update member here, and the code below is the code corresponding to the controller. Tell me where to fix it package com.bezkoder.springjwt.controllers;

    import java.util.HashSet; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors;

    import javax.servlet.http.HttpServletRequest; import javax.validation.Valid;

    import com.bezkoder.springjwt.security.services.UserDetailsServiceImpl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.web.bind.annotation.*;

    import com.bezkoder.springjwt.models.ERole; import com.bezkoder.springjwt.models.Role; import com.bezkoder.springjwt.models.User; import com.bezkoder.springjwt.payload.request.LoginRequest; import com.bezkoder.springjwt.payload.request.SignupRequest; import com.bezkoder.springjwt.payload.response.JwtResponse; import com.bezkoder.springjwt.payload.response.MessageResponse; import com.bezkoder.springjwt.repository.RoleRepository; import com.bezkoder.springjwt.repository.UserRepository; import com.bezkoder.springjwt.security.jwt.JwtUtils; import com.bezkoder.springjwt.security.services.UserDetailsImpl; import com.bezkoder.springjwt.security.services.UserDetailsServiceImpl;

    @CrossOrigin(origins = "*", maxAge = 3600) @RestController @RequestMapping("/api/auth") public class AuthController { @Autowired AuthenticationManager authenticationManager;

    @Autowired UserRepository userRepository;

    @Autowired RoleRepository roleRepository;

    @Autowired PasswordEncoder encoder;

    @Autowired JwtUtils jwtUtils;

    @PostMapping("/signin") public ResponseEntity<?> authenticateUser(@Valid @RequestBody LoginRequest loginRequest) {

    Authentication authentication = authenticationManager.authenticate(
        new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword()));
    
    SecurityContextHolder.getContext().setAuthentication(authentication);
    String jwt = jwtUtils.generateJwtToken(authentication);
    
    UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();    
    List<String> roles = userDetails.getAuthorities().stream()
        .map(item -> item.getAuthority())
        .collect(Collectors.toList());
    
    return ResponseEntity.ok(new JwtResponse(jwt, 
                         userDetails.getId(), 
                         userDetails.getUsername(), 
                         userDetails.getEmail(), 
                         roles));
    

    }

    @PostMapping("/signup") public ResponseEntity<?> registerUser(@Valid @RequestBody SignupRequest signUpRequest) { if (userRepository.existsByUsername(signUpRequest.getUsername())) { return ResponseEntity .badRequest() .body(new MessageResponse("Error: Username is already taken!")); }

    if (userRepository.existsByEmail(signUpRequest.getEmail())) {
      return ResponseEntity
          .badRequest()
          .body(new MessageResponse("Error: Email is already in use!"));
    }
    
    // Create new user's account
    User user = new User(signUpRequest.getUsername(), 
               signUpRequest.getEmail(),
               encoder.encode(signUpRequest.getPassword()));
    
    Set<String> strRoles = signUpRequest.getRole();
    Set<Role> roles = new HashSet<>();
    
    if (strRoles == null) {
      Role userRole = roleRepository.findByName(ERole.ROLE_USER)
          .orElseThrow(() -> new RuntimeException("Error: Role is not found."));
      roles.add(userRole);
    } else {
      strRoles.forEach(role -> {
        switch (role) {
        case "admin":
          Role adminRole = roleRepository.findByName(ERole.ROLE_ADMIN)
              .orElseThrow(() -> new RuntimeException("Error: Role is not found."));
          roles.add(adminRole);
    
          break;
        case "mod":
          Role modRole = roleRepository.findByName(ERole.ROLE_MODERATOR)
              .orElseThrow(() -> new RuntimeException("Error: Role is not found."));
          roles.add(modRole);
    
          break;
        default:
          Role userRole = roleRepository.findByName(ERole.ROLE_USER)
              .orElseThrow(() -> new RuntimeException("Error: Role is not found."));
          roles.add(userRole);
        }
      });
    }
    
    user.setRoles(roles);
    userRepository.save(user);
    
    return ResponseEntity.ok(new MessageResponse("User registered successfully!"));
    

    } @DeleteMapping("/delete/{id}") public ResponseEntity deleteMember(HttpServletRequest request) { // Get the authenticated user's ID UserDetailsImpl userDetails = (UserDetailsImpl) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); Long userId = userDetails.getId();

    // Delete the user from the database using the user ID
    userRepository.deleteById(userId);
    
    return new ResponseEntity<>("회원 탈퇴 성공", HttpStatus.OK);
    

    }

    @PostMapping("/update") public ResponseEntity update(@RequestBody User user){ UserDetailsServiceImpl.UpdateMember(user); return new ResponseEntity(HttpStatus.OK); } }

  4. Assistant

    In the AuthController, there's an issue in the update method. The UserDetailsServiceImpl.UpdateMember(user) is a static method and should be called using the class name (not instance name). You also need to autowire the UserDetailsServiceImpl into the AuthController to be able to call its methods. You can fix it by modifying the update method as follows:

    @Autowired
    UserDetailsServiceImpl userService;
    
    @PostMapping("/update")
    public ResponseEntity<String> update(@RequestBody User user){
        userService.updateMember(user);
        return new ResponseEntity<String>(HttpStatus.OK);
    }
    

    This way, you are autowiring the UserDetailsServiceImpl and using its instance (userService) to call the updateMember method instead of calling a static method.

  5. User

    package com.bezkoder.springjwt.controllers;

    import java.util.HashSet; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors;

    import javax.servlet.http.HttpServletRequest; import javax.validation.Valid;

    import com.bezkoder.springjwt.security.services.UserDetailsServiceImpl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.web.bind.annotation.*;

    import com.bezkoder.springjwt.models.ERole; import com.bezkoder.springjwt.models.Role; import com.bezkoder.springjwt.models.User; import com.bezkoder.springjwt.payload.request.LoginRequest; import com.bezkoder.springjwt.payload.request.SignupRequest; import com.bezkoder.springjwt.payload.response.JwtResponse; import com.bezkoder.springjwt.payload.response.MessageResponse; import com.bezkoder.springjwt.repository.RoleRepository; import com.bezkoder.springjwt.repository.UserRepository; import com.bezkoder.springjwt.security.jwt.JwtUtils; import com.bezkoder.springjwt.security.services.UserDetailsImpl; import com.bezkoder.springjwt.security.services.UserDetailsServiceImpl;

    @CrossOrigin(origins = "*", maxAge = 3600) @RestController @RequestMapping("/api/auth") public class AuthController { @Autowired AuthenticationManager authenticationManager;

    @Autowired UserRepository userRepository;

    @Autowired RoleRepository roleRepository;

    @Autowired PasswordEncoder encoder; @Autowired UserDetailsServiceImpl userService;

    @Autowired JwtUtils jwtUtils;

    @PostMapping("/signin") public ResponseEntity<?> authenticateUser(@Valid @RequestBody LoginRequest loginRequest) {

    Authentication authentication = authenticationManager.authenticate(
        new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword()));
    
    SecurityContextHolder.getContext().setAuthentication(authentication);
    String jwt = jwtUtils.generateJwtToken(authentication);
    
    UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();    
    List<String> roles = userDetails.getAuthorities().stream()
        .map(item -> item.getAuthority())
        .collect(Collectors.toList());
    
    return ResponseEntity.ok(new JwtResponse(jwt, 
                         userDetails.getId(), 
                         userDetails.getUsername(), 
                         userDetails.getEmail(), 
                         roles));
    

    }

    @PostMapping("/signup") public ResponseEntity<?> registerUser(@Valid @RequestBody SignupRequest signUpRequest) { if (userRepository.existsByUsername(signUpRequest.getUsername())) { return ResponseEntity .badRequest() .body(new MessageResponse("Error: Username is already taken!")); }

    if (userRepository.existsByEmail(signUpRequest.getEmail())) {
      return ResponseEntity
          .badRequest()
          .body(new MessageResponse("Error: Email is already in use!"));
    }
    
    // Create new user's account
    User user = new User(signUpRequest.getUsername(), 
               signUpRequest.getEmail(),
               encoder.encode(signUpRequest.getPassword()));
    
    Set<String> strRoles = signUpRequest.getRole();
    Set<Role> roles = new HashSet<>();
    
    if (strRoles == null) {
      Role userRole = roleRepository.findByName(ERole.ROLE_USER)
          .orElseThrow(() -> new RuntimeException("Error: Role is not found."));
      roles.add(userRole);
    } else {
      strRoles.forEach(role -> {
        switch (role) {
        case "admin":
          Role adminRole = roleRepository.findByName(ERole.ROLE_ADMIN)
              .orElseThrow(() -> new RuntimeException("Error: Role is not found."));
          roles.add(adminRole);
    
          break;
        case "mod":
          Role modRole = roleRepository.findByName(ERole.ROLE_MODERATOR)
              .orElseThrow(() -> new RuntimeException("Error: Role is not found."));
          roles.add(modRole);
    
          break;
        default:
          Role userRole = roleRepository.findByName(ERole.ROLE_USER)
              .orElseThrow(() -> new RuntimeException("Error: Role is not found."));
          roles.add(userRole);
        }
      });
    }
    
    user.setRoles(roles);
    userRepository.save(user);
    
    return ResponseEntity.ok(new MessageResponse("User registered successfully!"));
    

    } @DeleteMapping("/delete/{id}") public ResponseEntity deleteMember(HttpServletRequest request) { // Get the authenticated user's ID UserDetailsImpl userDetails = (UserDetailsImpl) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); Long userId = userDetails.getId();

    // Delete the user from the database using the user ID
    userRepository.deleteById(userId);
    
    return new ResponseEntity<>("회원 탈퇴 성공", HttpStatus.OK);
    

    }

    @PostMapping("/update") public ResponseEntity update(@RequestBody User user){ userService.updateMember(user);

    Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword()));
    SecurityContextHolder.getContext().setAuthentication(authentication);
    
    return new ResponseEntity<String>(HttpStatus.OK);
    

    } }

    I modified the controller update part like this for the member information modification function, is there a problem?

  6. Assistant

    The updated code looks good and there are no apparent issues.

    In the update method, you are calling the updateMember method of the UserDetailsServiceImpl class for updating the member information. Then, you are authenticating the updated user with its new credentials using authenticationManager.authenticate() and updating the SecurityContextHolder with the new authentication using SecurityContextHolder.getContext().setAuthentication().

    Overall, the code seems to fulfill your requirement to create a member information correction function on the backend.

  7. User

    2023-05-25 20:41:15.375 WARN 6588 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.context.ApplicationContextException: Unable to start web server; nested exception is org.springframework.boot.web.server.WebServerException: Unable to start embedded Tomcat

  8. Assistant

    The error message you provided seems to indicate that there is a problem with starting the web server during the context initialization.

    A possible reason for this error could be that the port your application is trying to run on is already in use by another process. You can check this by looking for similar error messages that may indicate the port is already in use.

    Another possible reason for this error could be related to the dependencies or configuration of your application. You can try to remove any recently added dependencies or configuration changes that may have caused the issue and see if it resolves the error.

    It is also possible that there is a problem with the embedded Tomcat server that your application is using. You can try upgrading or downgrading the version of Tomcat and see if it resolves the issue.

    It is recommended to provide more details about the error message, including the stack trace, to get a better understanding of the root cause of the issue.

  9. User

    2023-05-25 20:41:15.373 WARN 6588 --- [ main] o.a.c.loader.WebappClassLoaderBase : The web application [ROOT] appears to have started a thread named [HikariPool-1 housekeeper] but has failed to stop it. This is very likely to create a memory leak. Stack trace of thread:

  10. Assistant

    The error message you provided is a warning message about a potential memory leak issue in your web application.

    The warning message indicates that the web application has started a thread named [HikariPool-1 housekeeper], but has failed to stop it properly. This could cause a memory leak, which can cause your application to run out of memory over time.

    This warning message is related to a thread being spawned by HikariCP, which is a high-performance JDBC connection pooling library used by your application. The HikariPool-1 thread is responsible for managing the connections to the database.

    To resolve this issue, you need to properly shutdown the Hikari connection pool when your application is shutting down. You can do this by adding the following lines of code in your Spring Boot application's main class:

    @PreDestroy
    public void shutdownHikari() {
        HikariDataSource dataSource = (HikariDataSource) dataSource();
        if (dataSource != null) {
            dataSource.close();
        }
    }
    

    This will ensure that the Hikari connection pool is properly shutdown when your application is shutting down, which will prevent any memory leaks.