|
| 1 | +package express.middleware; |
| 2 | + |
| 3 | +import express.events.HttpRequest; |
| 4 | +import express.http.Request; |
| 5 | +import express.http.Response; |
| 6 | +import express.http.cookie.Cookie; |
| 7 | + |
| 8 | +import java.math.BigInteger; |
| 9 | +import java.security.SecureRandom; |
| 10 | +import java.util.concurrent.ConcurrentHashMap; |
| 11 | + |
| 12 | +public class CookieSession extends ExpressWorker implements HttpRequest, ExpressMiddleware { |
| 13 | + |
| 14 | + private final static String MIDDLEWARE_NAME = "SessionCookie"; |
| 15 | + |
| 16 | + private final ConcurrentHashMap<String, SessionCookie> COOKIES = new ConcurrentHashMap<>(); |
| 17 | + private final String COOKIE_NAME; |
| 18 | + private final long MAX_AGE; |
| 19 | + |
| 20 | + public CookieSession(String cookieName, long maxAge) { |
| 21 | + this.COOKIE_NAME = cookieName; |
| 22 | + this.MAX_AGE = maxAge; |
| 23 | + } |
| 24 | + |
| 25 | + @Override |
| 26 | + public String getName() { |
| 27 | + return MIDDLEWARE_NAME; |
| 28 | + } |
| 29 | + |
| 30 | + @Override |
| 31 | + public void handle(Request req, Response res) { |
| 32 | + Cookie cookie = req.getCookie(COOKIE_NAME); |
| 33 | + |
| 34 | + if (cookie != null && COOKIES.containsKey(cookie.getValue())) { |
| 35 | + |
| 36 | + req.addMiddlewareContent(this, COOKIES.get(cookie.getValue())); |
| 37 | + } else { |
| 38 | + String token = generateSecureToken(32); |
| 39 | + |
| 40 | + cookie = new Cookie(COOKIE_NAME, token).setMaxAge(MAX_AGE); |
| 41 | + res.setCookie(cookie); |
| 42 | + |
| 43 | + SessionCookie sessionCookie = new SessionCookie(MAX_AGE); |
| 44 | + COOKIES.put(token, sessionCookie); |
| 45 | + |
| 46 | + req.addMiddlewareContent(this, sessionCookie); |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + @Override |
| 51 | + long getDelay() { |
| 52 | + return 15000; // 1min |
| 53 | + } |
| 54 | + |
| 55 | + @Override |
| 56 | + void update() { |
| 57 | + long current = System.currentTimeMillis(); |
| 58 | + |
| 59 | + COOKIES.forEach((s, o) -> { |
| 60 | + if (current > o.getCreated() + o.getMaxAge()) |
| 61 | + COOKIES.remove(s); |
| 62 | + }); |
| 63 | + } |
| 64 | + |
| 65 | + private static String generateSecureToken(int byteLength) { |
| 66 | + SecureRandom secureRandom = new SecureRandom(); |
| 67 | + byte[] token = new byte[byteLength]; |
| 68 | + secureRandom.nextBytes(token); |
| 69 | + return new BigInteger(1, token).toString(16); //hex encoding |
| 70 | + } |
| 71 | + |
| 72 | +} |
0 commit comments