1. import java.util.HashMap;
  2. import java.util.Map;
  3. public class CookieValidator {
  4. private static final int MAX_COOKIES_PER_USER = 10; // Example rate limit
  5. private static final long RATE_LIMIT_WINDOW = 60; // Seconds
  6. private static final Map<String, Integer> cookieCounts = new HashMap<>(); // User ID -> Cookie count
  7. private static final long lastAccessTime = 0; //Last access timestamp
  8. public static boolean validateCookies(String userId, Map<String, String> cookies) {
  9. // Check if user ID exists in cookie counts
  10. if (!cookieCounts.containsKey(userId)) {
  11. cookieCounts.put(userId, 0); // Initialize count if user is new
  12. }
  13. // Check rate limit
  14. long currentTime = System.currentTimeMillis();
  15. if (currentTime - lastAccessTime < RATE_LIMIT_WINDOW * 1000) {
  16. return false; // Rate limit exceeded
  17. }
  18. lastAccessTime = currentTime;
  19. int currentCount = cookieCounts.get(userId);
  20. if (currentCount >= MAX_COOKIES_PER_USER) {
  21. return false; // Rate limit exceeded
  22. }
  23. // Increment cookie count
  24. cookieCounts.put(userId, currentCount + cookies.size());
  25. return true; // Cookies are valid
  26. }
  27. public static void resetCookieCount(String userId) {
  28. cookieCounts.put(userId, 0);
  29. }
  30. }

Add your comment