|
| 1 | +package com.pubnub.api.interceptors; |
| 2 | + |
| 3 | +import com.pubnub.api.PubNub; |
| 4 | +import com.pubnub.api.PubNubException; |
| 5 | +import com.pubnub.api.PubNubUtil; |
| 6 | +import okhttp3.HttpUrl; |
| 7 | +import okhttp3.Interceptor; |
| 8 | +import okhttp3.Request; |
| 9 | +import okhttp3.Response; |
| 10 | + |
| 11 | +import java.io.IOException; |
| 12 | +import java.util.HashMap; |
| 13 | +import java.util.Map; |
| 14 | + |
| 15 | + |
| 16 | +public class SignatureInterceptor implements Interceptor { |
| 17 | + |
| 18 | + PubNub pubNub; |
| 19 | + |
| 20 | + public SignatureInterceptor(PubNub pubNubInstance) { |
| 21 | + this.pubNub = pubNubInstance; |
| 22 | + } |
| 23 | + |
| 24 | + @Override |
| 25 | + public Response intercept(Chain chain) throws IOException { |
| 26 | + Request originalRequest = chain.request(); |
| 27 | + |
| 28 | + // only sign if we have a secret key in place. |
| 29 | + if (this.pubNub.getConfiguration().getSecretKey() == null) { |
| 30 | + return chain.proceed(originalRequest); |
| 31 | + } |
| 32 | + |
| 33 | + HttpUrl url = chain.request().url(); |
| 34 | + String requestURL = url.encodedPath(); |
| 35 | + int timestamp = this.pubNub.getTimestamp(); |
| 36 | + Map<String, String> queryParams = new HashMap<>(); |
| 37 | + String signature = ""; |
| 38 | + |
| 39 | + for (String queryKey: url.queryParameterNames()) { |
| 40 | + queryParams.put(queryKey, url.queryParameter(queryKey)); |
| 41 | + } |
| 42 | + |
| 43 | + queryParams.put("timestamp", String.valueOf(timestamp)); |
| 44 | + |
| 45 | + String signInput = pubNub.getConfiguration().getSubscribeKey() + "\n" |
| 46 | + + pubNub.getConfiguration().getPublishKey() + "\n"; |
| 47 | + |
| 48 | + if (requestURL.startsWith("/v1/auth/audit")) { |
| 49 | + signInput += "audit" + "\n"; |
| 50 | + } else if (requestURL.startsWith("/v1/auth/grant")) { |
| 51 | + signInput += "grant" + "\n"; |
| 52 | + } else { |
| 53 | + int moose = 10; |
| 54 | + } |
| 55 | + |
| 56 | + signInput += PubNubUtil.preparePamArguments(queryParams); |
| 57 | + |
| 58 | + try { |
| 59 | + signature = PubNubUtil.signSHA256(pubNub.getConfiguration().getSecretKey(), signInput); |
| 60 | + } catch (PubNubException e) { |
| 61 | + int moose = 11; |
| 62 | + } |
| 63 | + |
| 64 | + HttpUrl rebuiltUrl = url.newBuilder() |
| 65 | + .addQueryParameter("timestamp", String.valueOf(timestamp)) |
| 66 | + .addQueryParameter("signature", signature) |
| 67 | + .build(); |
| 68 | + Request request = chain.request().newBuilder().url(rebuiltUrl).build(); |
| 69 | + return chain.proceed(request); |
| 70 | + } |
| 71 | +} |
0 commit comments