|
1 | 1 | package org.barcodeapi.server.cache; |
2 | 2 |
|
| 3 | +import org.barcodeapi.core.Config; |
| 4 | +import org.barcodeapi.core.Config.Cfg; |
3 | 5 | import org.barcodeapi.server.core.Reputation; |
4 | 6 | import org.barcodeapi.server.core.Tokens; |
5 | 7 | import org.json.JSONObject; |
|
11 | 13 | */ |
12 | 14 | public class CachedLimiter extends CachedObject { |
13 | 15 |
|
| 16 | + // Default values for new limiters |
| 17 | + private static final int DEFLIMIT_RATE; |
| 18 | + private static final boolean DEFLIMIT_ENFORCE; |
| 19 | + |
| 20 | + static { |
| 21 | + |
| 22 | + // Load plan from configuration |
| 23 | + JSONObject freePlan = Config// |
| 24 | + .get(Cfg.Plans).getJSONObject("free"); |
| 25 | + |
| 26 | + // Free plan defaults |
| 27 | + DEFLIMIT_RATE = freePlan.getInt("limit"); |
| 28 | + DEFLIMIT_ENFORCE = freePlan.getBoolean("enforce"); |
| 29 | + } |
| 30 | + |
14 | 31 | private static final long serialVersionUID = 20260503L; |
15 | 32 |
|
16 | | - private final String caller; |
| 33 | + private final String callerID; |
17 | 34 |
|
18 | 35 | private final Reputation reputation; |
19 | 36 |
|
20 | 37 | private final Tokens tokens; |
21 | 38 |
|
22 | | - public CachedLimiter(boolean enforce, String caller, long requests) { |
| 39 | + public CachedLimiter(Subscriber sub, String address) { |
23 | 40 | super("limiter"); |
24 | 41 |
|
25 | | - this.caller = caller; |
| 42 | + // Assign the userID |
| 43 | + this.callerID = (sub != null) ? sub.getCustomer() : address; |
26 | 44 |
|
27 | | - this.reputation = new Reputation(enforce); |
| 45 | + // Determine token limits for the limiter |
| 46 | + int limit = (sub != null) ? sub.getLimit() : DEFLIMIT_RATE; |
| 47 | + boolean enforce = (sub != null) ? sub.isEnforced() : DEFLIMIT_ENFORCE; |
| 48 | + this.tokens = new Tokens(enforce, limit); |
28 | 49 |
|
29 | | - this.tokens = new Tokens(enforce, requests); |
| 50 | + // Setup user reputation tracker |
| 51 | + boolean repBlock = (sub != null) ? false : enforce; |
| 52 | + this.reputation = new Reputation(repBlock); |
30 | 53 | } |
31 | 54 |
|
32 | 55 | public void touch(CachedSession session) { |
@@ -54,8 +77,8 @@ public boolean isShortLived() { |
54 | 77 | * |
55 | 78 | * @return caller |
56 | 79 | */ |
57 | | - public String getCaller() { |
58 | | - return caller; |
| 80 | + public String getCallerID() { |
| 81 | + return callerID; |
59 | 82 | } |
60 | 83 |
|
61 | 84 | /** |
@@ -101,7 +124,7 @@ public boolean onRequest(boolean valid, double cost) { |
101 | 124 | public JSONObject asJSON() { |
102 | 125 |
|
103 | 126 | return (new JSONObject()// |
104 | | - .put("caller", getCaller())// |
| 127 | + .put("callerID", getCallerID())// |
105 | 128 | .put("requests", getAccessCount())// |
106 | 129 | .put("reputation", reputation.value())// |
107 | 130 | .put("time", new JSONObject() // |
|
0 commit comments