View Javadoc
1   package de.dlr.shepard.auth.security;
2   
3   import java.util.Date;
4   import java.util.HashMap;
5   import java.util.Map;
6   
7   /**
8    * This cache allows to store keys along with the date of storage.
9    * This can be used to check if e.g. an api key has been used in a recent period of time.
10   *
11   * To use this, extend this class, annotate the extending class with @ApplicationScoped and set the cacheExpiration.
12   */
13  public abstract class LastSeenCache {
14  
15    private final Map<String, Date> cache;
16    private final int cacheExpirationPeriodInMs;
17  
18    /**
19     * @param cacheExpirationPeriodInMs period in ms when to expire cached keys
20     */
21    public LastSeenCache(int cacheExpirationPeriodInMs) {
22      this.cacheExpirationPeriodInMs = cacheExpirationPeriodInMs;
23      cache = new HashMap<>();
24    }
25  
26    /**
27     * @return true if the key has a cache entry that is not expired
28     */
29    public boolean isKeyCached(String key) {
30      if (!cache.containsKey(key)) return false;
31  
32      var threshold = new Date(System.currentTimeMillis() - cacheExpirationPeriodInMs);
33      return cache.get(key).after(threshold);
34    }
35  
36    public void cacheKey(String key) {
37      cache.put(key, new Date());
38    }
39  }