92 lines
2.9 KiB
Java
Executable File
92 lines
2.9 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;
|
|
|
|
/**
|
|
* Spring authentication provider
|
|
*/
|
|
@Component
|
|
public class AuthenticationProvider extends AbstractUserDetailsAuthenticationProvider {
|
|
|
|
@Autowired
|
|
private UserService userService;
|
|
|
|
@Override
|
|
protected void additionalAuthenticationChecks(UserDetails userDetails,
|
|
UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
|
|
}
|
|
|
|
@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() {
|
|
if (user.isCredentialsNonExpired()) {
|
|
userService.save(user);
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
@Override
|
|
public boolean isEnabled() {
|
|
return true;
|
|
}
|
|
|
|
};
|
|
|
|
return response;
|
|
}
|
|
|
|
}
|