How to properly implement validated registration in the database?

64 Views Asked by At

The same "springboot.model.User.setUsername(String)" because "users" is null" error is constantly coming out. The error is clear, it says that you cannot set null. I send json data to the DTO class, where I check if it is in the database and if it is not there, then I install. Perhaps I am making a serious mistake and do not see it. Please tell me what needs to be done, how to assign values correctly?

ERROR:

java.lang.NullPointerException: Cannot invoke "com.nor.springboot.model.User.setUsername(String)" because "users" is null
    at com.nor.springboot.service.JwtUserService.register(JwtUserService.java:121) ~[classes/:na]
    at com.coooo.springboot.controller.UserAuthenticationController.registerUser(UserAuthenticationController.java:88) ~[classes/:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
    at java.base/java.lang.reflect.Method.invoke(Method.java:564) ~[na:na]
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:197) ~[spring-web-5.3.8.jar:5.3.8]
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:141) ~[spring-web-5.3.8.jar:5.3.8]
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:106) ~[spring-webmvc-5.3.8.jar:5.3.8]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:894) ~[spring-webmvc-5.3.8.jar:5.3.8]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808) ~[spring-webmvc-5.3.8.jar:5.3.8]
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.3.8.jar:5.3.8]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1063) ~[spring-webmvc-5.3.8.jar:5.3.8]

JSON Request:

{"username":"Ivanov",
"email":"[email protected]",
"password":"1a234567890"}

RESPONSE:

{
    "timestamp": "2021-07-03T18:48:42.872+00:00",
    "status": 500,
    "error": "Internal Server Error",
    "path": "/auth/signup"
}

ENTITY:

@Entity
@Table(name="usr",

uniqueConstraints = {
        @UniqueConstraint(columnNames = "username"),
        @UniqueConstraint(columnNames = "email"),
        @UniqueConstraint(columnNames = "phone")
})
public class User extends BaseEntity  {
    
    @NotBlank(message = "Username cannot be empty")
    @Size(min=3, message="min 3 characters")
    @Column(name = "username")
    private String username;
    
    @Column(name = "secondName")
    private String secondName;
    
    @NotBlank(message = "Password cannot be empty")
    @Size(min=8, message="min 8 characters")
    @Column(name = "password")
    private String password;
    
    @Column(name = "phone")
    private String phone;
    
    @Column(name = "description")
    private String description;
    
    @Email(message = "Email is not correct")
    @NotBlank(message = "Email cannot be empty")
    @Column(name = "email")
    private String email;
    
    @Column(name = "active")
    private boolean active;
    
    @ElementCollection(targetClass = Role.class, fetch = FetchType.EAGER)
    @CollectionTable(name = "user_role", joinColumns = @JoinColumn(name = "user_id"))
    @Enumerated(EnumType.STRING)
    private Set<Role> roles;

    public String getUsername() {
        return this.username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getSecondName() {
        return companyName;
    }

    public void setSecondName(String companyName) {
        this.companyName = companyName;
    }

    public String getPassword() {
        return this.password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public boolean isActive() {
        return active;
    }

    public void setActive(boolean active) {
        this.active = active;
    }

    public Set<Role> getRoles() {
        return roles;
    }

    public void setRoles(Set<Role> roles) {
        this.roles = roles;
    }
}

SERVICE REGISTRATION METHOD:

     public class JwtUserService implements UserDetailsService{
            
            
            private UserRepository userRepository;
            
            private BCryptPasswordEncoder passwordEncoder;
            
              @Autowired
                public JwtUserService(UserRepository userRepository,  BCryptPasswordEncoder passwordEncoder) {
                    this.userRepository = userRepository;        
                    this.passwordEncoder = passwordEncoder;
              }
    
@Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
         User user = userRepository.findByUsername(username);
         
         if (user == null) {
                throw new UsernameNotFoundException("User with username: " + username + " not found");
            }
          JwtUser jwtUser = JwtUserFactory.create(user);
          
            return jwtUser;
    }
    
        public ResponseEntity<?> register(JwtUser user) {
                
                User users = userRepository.findByUsername(user.getUsername());
                User emails = userRepository.findByEmail(user.getEmail());
             if(users != null && emails !=null) {
                 return ResponseEntity
                    .badRequest()
                    .body(new MessageResponse("Error: Username or email is exist"));
                    
                }
            
                       
                users.setUsername(user.getUsername()); 
                users.setPassword(passwordEncoder.encode(user.getPassword()));
                users.setRoles(Collections.singleton(Role.USER));
                users.setEmail(user.getEmail());
                users.setActive(true);
              
                userRepository.save(users);
                
               
        
                return new ResponseEntity<>("User Created!", HttpStatus.OK);
            
            
            }

CONFIG:

@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    
    
    private static final String LOGIN_ENDPOINT = "/auth/**";
    
     @Autowired
     private  JwtTokenProvider jwtTokenProvider;
     
       @Bean
        @Override
        public AuthenticationManager authenticationManagerBean() throws Exception {
            return super.authenticationManagerBean();
       }
     
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        
        http 
        .httpBasic().disable()
        .csrf().disable()
        .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        .and()
        .authorizeRequests()
        .antMatchers(LOGIN_ENDPOINT).permitAll()       
        .anyRequest().authenticated()
        .and()
        .apply(new JwtConfigurer(jwtTokenProvider));
        
    }
}

CLASS JWT UserDetails:

public class JwtUser implements UserDetails {
    
    private String token;

    private  Long id;
    
    private  String username;

    private  String secondName;
    
    private  String password;
    
    private  String phone;
    
    private  String description;
    
    private  String email;

    private  boolean active;
    
    private  Date lastPasswordResetDate;

    private  Collection<? extends GrantedAuthority> authorities;
    
    
    public JwtUser(Long id, String username, String secondName, String password, String phone, String description,
            String email, boolean active, Date lastPasswordResetDate,
            Collection<? extends GrantedAuthority> authorities) {
        
        this.id = id;
        this.username = username;
        this.secondName = companyName;
        this.password = password;
        this.phone = phone;
        this.description = description;
        this.email = email;
        this.active = active;
        this.lastPasswordResetDate = lastPasswordResetDate;
        this.authorities = authorities;
    }
    
    
    
    public JwtUser(String token, Long id, String username, String secondName,  String phone, String description,
            String email, Collection<? extends GrantedAuthority> authorities) {
        this.token=token;
        this.id = id;
        this.username = username;
        this.secondName = companyName;      
        this.phone = phone;
        this.description = description;
        this.email = email;     
        this.authorities = authorities;
    }
    

    public JwtUser(String username, String password, Collection<? extends GrantedAuthority> authorities,
            String email, boolean active) {
                
        this.username = username;
        this.password=password;
        this.authorities = authorities;
        this.email = email;     
        this.active=active;
        
    }
    
    public JwtUser(){
        
    }
    
    
    
    
    
    
    public String getToken() {
        return token;
    }

    public void setToken(String token) {
        this.token = token;
    }

    @JsonIgnore 
    public Long getId() {
        return id;
    }

    public String getSecondName() {
        return companyName;
    }

    public String getPhone() {
        return phone;
    }

    public String getDescription() {
        return description;
    }

    public String getEmail() {
        return email;
    }

    public boolean isActive() {
        return active;
    }
    @JsonIgnore
    public Date getLastPasswordResetDate() {
        return lastPasswordResetDate;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        
        return authorities;
    }
    @JsonIgnore
    @Override
    public String getPassword() {
        
        return password;
    }

    @Override
    public String getUsername() {
        
        return username;
    }
    public void setUsername(String username) {
        this.username=username;
    }
    
    @JsonIgnore
    @Override
    public boolean isAccountNonExpired() {
        
        return true;
    }
    @JsonIgnore
    @Override
    public boolean isAccountNonLocked() {
        
        return true;
    }
    @JsonIgnore
    @Override
    public boolean isCredentialsNonExpired() {
        
        return true;
    }

    @Override
    public boolean isEnabled() {
        
        return true;
    }

}
0

There are 0 best solutions below