backend/restservice/src/main/java/com/plannaplan/security/AuthenticationProvider.java
Filip Izydorczyk 5fd688fc7a Added roles
2020-10-16 16:31:10 +02:00

88 lines
2.8 KiB
Java
Executable File

package com.plannaplan.security;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import com.plannaplan.entities.User;
import com.plannaplan.services.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
@Component
public class AuthenticationProvider extends AbstractUserDetailsAuthenticationProvider {
@Autowired
private UserService userService;
@Override
protected void additionalAuthenticationChecks(UserDetails userDetails,
UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
// is being done in other task
}
@Override
protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication)
throws AuthenticationException {
final String token = authentication.getCredentials().toString();
User user = this.userService.getByToken(token)
.orElseThrow(() -> new UsernameNotFoundException("Cannot find user with given authority"));
UserDetails response = new UserDetails() {
private static final long serialVersionUID = 1L;
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
final AuthorityRoles role = AuthorityRoles.getAuthorityRole(user.getRole())
.orElseThrow(() -> new NullPointerException("Failed to get user role"));
final List<AuthorityRoles> response = Arrays.asList(role);
return response;
}
@Override
public String getPassword() {
return null;
}
@Override
public String getUsername() {
return user.getEmail();
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
// is being done in other task
return true;
}
@Override
public boolean isEnabled() {
return true;
}
};
return response;
}
}