argos/dmp-backend/src/main/java/security/CustomAuthenticationProvide...

80 lines
2.8 KiB
Java

package security;
import java.util.ArrayList;
import javax.naming.NameAlreadyBoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;
import dao.entities.security.UserInfoDao;
import entities.security.UserInfo;
import exceptions.NonValidTokenException;
import security.validators.GoogleTokenValidator;
import security.validators.NativeTokenValidator;
import security.validators.TokenValidator;
@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {
@Autowired private UserInfoDao userInfoDao;
@Autowired private GoogleTokenValidator googleTokenValidator;
@Autowired private NativeTokenValidator nativeTokenValidator;
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
if (authentication != null) {
String token = (String)authentication.getCredentials();
TokenValidator tokenValidator = null;
if(TokenAuthenticationFilter.HEADER_GOOGLE_TOKEN_FIELD.equals(authentication.getPrincipal()))
tokenValidator = googleTokenValidator;
else if(TokenAuthenticationFilter.HEADER_NATIVE_TOKEN_FIELD.equals(authentication.getPrincipal()))
tokenValidator = nativeTokenValidator;
else
throw new AuthenticationServiceException("The appropriate http headers have not been set. Please check!");
try {
tokenValidator.validateToken(token);
} catch (NonValidTokenException e) {
System.out.println("Could not validate a user by his token! Reason: "+e.getMessage());
throw new AuthenticationServiceException("Token validation failed - Not a valid token");
}
//store to database if new
// UserInfo existingUserInfo = userInfoDao.getByKey(userInfo.getId(), userInfo.getEmail());
// if(existingUserInfo == null)
// userInfoDao.create(userInfo);
// if reached this point, authentication is ok, so return just an instance with whatever.
return new UsernamePasswordAuthenticationToken(authentication.getPrincipal(), authentication.getCredentials(), new ArrayList<>());
}
else
throw new AuthenticationServiceException("Authentication failed");
// //DELETE THIS, USE THE ABOVE
// return new UsernamePasswordAuthenticationToken("", "", new ArrayList<>());
}
@Override
public boolean supports(Class<?> authentication) {
return authentication.equals(UsernamePasswordAuthenticationToken.class);
}
}