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

65 lines
2.3 KiB
Java

package security;
import java.util.ArrayList;
import javax.servlet.http.HttpServletRequest;
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.security.core.token.Token;
import org.springframework.security.core.token.TokenService;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import dao.entities.security.UserInfoDao;
import entities.security.UserInfo;
import exceptions.NonValidTokenException;
@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {
@Autowired private UserInfoDao userInfoDao;
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
if (authentication != null) {
// check whether the token is valid
String token = (String)authentication.getCredentials();
GoogleTokenValidator gValidator = new GoogleTokenValidator();
UserInfo userInfo = null;
try {
userInfo = gValidator.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);
}
else
throw new AuthenticationServiceException("Authentication failed");
//authentication is ok
return new UsernamePasswordAuthenticationToken(authentication.getPrincipal(), authentication.getCredentials(), new ArrayList<>());
}
@Override
public boolean supports(Class<?> authentication) {
return authentication.equals(UsernamePasswordAuthenticationToken.class);
}
}